KatInterview

Building and Testing a REST API Endpoint in Python

System DesignModel answer
MediumModel answerSystem DesignREST APItestingPython

Last updated

Design a REST endpoint for a Python function and write unit tests that validate logic, handle edge cases, and isolate dependencies.

You're building a service that needs to expose Python functions over HTTP so other systems can call them. Consider a function that calculates the mean price from a time series within a given date window.

Your task is to explain:

  1. API Design: How would you expose this function as a REST endpoint? What makes an API RESTful, and what's the relationship between a web framework and an endpoint?

  2. Implementation Mechanics: Walk through how an HTTP request becomes a function call and returns a response. Cover routing, parameter handling, validation, and error reporting.

  3. Unit Testing: Write a concrete unit test for this code. Your test should cover normal operation, edge cases, and show how you isolate external dependencies. Explain what unit tests can and cannot validate.

Assume the function retrieves price data from a database or external service, performs the calculation, and returns a numeric result. Other services, dashboards, or scripts will call this endpoint.

Clarifications to address:

  • What architectural principles define REST?
  • How do you separate business logic from HTTP handling?
  • What testing strategy balances coverage with maintainability?

Hints

Hint 1

REST is an architectural style built on resources, standard HTTP methods, and stateless communication—not just 'using HTTP'

Hint 2

Keep your core calculation logic independent of the web framework so it can be tested without spinning up a server

Hint 3

Use test doubles (mocks or fakes) to replace database calls, but remember this means you're not testing the real integration