Building and Testing a REST API Endpoint in Python
System DesignModel answerLast 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:
-
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?
-
Implementation Mechanics: Walk through how an HTTP request becomes a function call and returns a response. Cover routing, parameter handling, validation, and error reporting.
-
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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
A Strong Answer
Part 1: REST API Design and Implementation
What makes an API RESTful?
REST (Representational State Transfer) is an architectural style with these core principles:
- Resources identified by URLs:
/prices/averagerepresents the averaging operation as a resource - Standard HTTP methods with clear semantics: GET retrieves data without side effects, POST creates or triggers computation, PUT/PATCH update, DELETE removes
- Stateless requests: each request contains all necessary information; the server doesn't maintain session state between calls
- Standard status codes: 200 for success, 400 for bad input, 404 for not found, 500 for server errors
- Structured responses: typically JSON, with consistent error formatting
Framework vs. Endpoint
FastAPI is a web framework, not an endpoint itself. The framework provides infrastructure—routing, parsing, validation, serialization—that lets you define endpoints. An endpoint is a specific URL path + HTTP method combination that maps to your code.
Example endpoint design:
GET /api/v1/prices/average?symbol=AAPL&start=2024-01-01&end=2024-12-31
This design:
- Uses GET since we're retrieving computed data without side effects
- Includes API versioning (
/v1/) for future compatibility - Passes parameters as query strings for a read operation
- Returns JSON:
{"symbol": "AAPL", "average": 178.43, "count": 252}
How an endpoint works (request lifecycle):
- Routing: Framework matches the URL path to a handler function
- Parameter extraction: Query string, path variables, or request body parsed into Python types
- Validation: Framework validates types, ranges, required fields (FastAPI uses Pydantic models)
- Handler execution: Your function runs with validated inputs
- Serialization: Return value converted to JSON
- Error handling: Exceptions mapped to appropriate HTTP status codes
Implementation pattern:
from fastapi import FastAPI, HTTPException, Query
from datetime import date
from typing import Optional
app = FastAPI()
# Business logic separated from HTTP layer
def calculate_average_price(symbol: str, start: date, end: date, data_source):
"""Pure function that doesn't know about HTTP."""
prices = data_source.get_prices(symbol, start, end)
if not prices:
return None
return sum(prices) / len(prices)
# HTTP endpoint wraps business logic
@app.get("/api/v1/prices/average")
def get_average_price(
symbol: str = Query(..., min_length=1, max_length=10),
start: date = Query(...),
end: date = Query(...)
):
if start > end:
raise HTTPException(status_code=400, detail="Start date must precede end date")
# Inject real data source
result = calculate_average_price(symbol, start, end, get_data_source())
if result is None:
raise HTTPException(status_code=404, detail=f"No data found for {symbol}")
return {
"symbol": symbol,
"average": round(result, 2),
"start": start.isoformat(),
"end": end.isoformat()
}
Key design decisions:
- Business logic (
calculate_average_price) is framework-agnostic and testable independently - Validation happens at the framework layer (type conversion, constraints)
- Domain validation (start < end) is explicit in the handler
- Error cases map to appropriate HTTP status codes
- Data access is injected, enabling test doubles
Part 2: Unit Testing Strategy
Testing approach:
Unit tests validate individual components in isolation. For this code, we test:
- The calculation logic directly (no HTTP involved)
- Edge cases: empty data, single data point, boundary dates
- Error conditions: invalid date ranges, missing data
Concrete test example:
import pytest
from datetime import date
from unittest.mock import Mock
class FakeDataSource:
"""Test double that replaces database."""
def __init__(self, prices):
self.prices = prices
def get_prices(self, symbol, start, end):
return self.prices
def test_calculate_average_normal_case():
"""Happy path: multiple prices."""
data_source = FakeDataSource([100.0, 110.0, 105.0])
result = calculate_average_price("AAPL", date(2024, 1, 1), date(2024, 1, 3), data_source)
assert result == 105.0
def test_calculate_average_single_price():
"""Edge case: only one data point."""
data_source = FakeDataSource([100.0])
result = calculate_average_price("AAPL", date(2024, 1, 1), date(2024, 1, 1), data_source)
assert result == 100.0
def test_calculate_average_no_data():
"""Missing data returns None."""
data_source = FakeDataSource([])
result = calculate_average_price("INVALID", date(2024, 1, 1), date(2024, 1, 3), data_source)
assert result is None
@pytest.mark.parametrize("prices,expected", [
([10.0, 20.0, 30.0], 20.0),
([5.5, 5.5, 5.5], 5.5),
([100.123, 200.456], 150.2895),
])
def test_calculate_average_parametrized(prices, expected):
"""Multiple cases in one test."""
data_source = FakeDataSource(prices)
result = calculate_average_price("TEST", date(2024, 1, 1), date(2024, 1, 3), data_source)
assert result == pytest.approx(expected)
What this testing strategy accomplishes:
- Isolation:
FakeDataSourcereplaces the real database, so tests run fast and don't require infrastructure - Edge case coverage: empty results, single values, floating-point precision
- Parametrization: efficiently test multiple input combinations
- Clarity: each test has a single clear purpose
What unit tests don't cover:
- Integration: Does the real data source query correctly? Do date filters work in SQL?
- HTTP layer: Parameter parsing, status code mapping, JSON serialization
- End-to-end behavior: Can a real client call the endpoint successfully?
For HTTP layer testing, use FastAPI's TestClient:
from fastapi.testclient import TestClient
def test_endpoint_validation():
client = TestClient(app)
response = client.get("/api/v1/prices/average?symbol=AAPL&start=2024-12-31&end=2024-01-01")
assert response.status_code == 400
assert "start date must precede" in response.json()["detail"].lower()
Common mistakes to avoid:
- Testing implementation details rather than behavior
- Mocking so extensively that tests become brittle and don't catch real bugs
- Skipping edge cases and error paths
- Not testing the business logic independently of the framework
- Confusing unit tests with integration tests (different purposes, different trade-offs)
Summary: A good answer demonstrates understanding of REST principles, shows clean separation between business logic and HTTP concerns, and provides concrete, runnable tests that balance isolation with meaningful coverage.