Designing REST APIs with FastAPI and Flask
Difficulty: Medium-Hard | Companies: Google, Meta, Amazon, Netflix, Stripe
Anyone can add a route decorator. Interviewers are listening for the decisions behind it: what the URL actually means, which status code leaves the client with no ambiguity, where validation happens, and how a caller recovers when the request is wrong.
Prerequisites
- !Python functions, decorators and type hints
- !HTTP basics: methods, headers, status codes
- !Working knowledge of dictionaries and JSON
What You'll Learn
- 1Model a domain as resources instead of ad-hoc endpoints
- 2Choose status codes and methods that describe the outcome precisely
- 3Push validation and authentication into reusable dependencies
- 4Design versioning and error bodies that clients can evolve with
Think in resources, not in endpoints
An API that models resources survives contact with new requirements; one that models individual use cases rarely does. Before writing a single decorator, name the nouns in your domain â users, orders, invoices â and let the HTTP method express what happens to the noun. GET /orders/42 reads one order, POST /orders creates one, PATCH /orders/42 applies a partial update, and DELETE /orders/42 removes it. When a design discussion begins with "we need an endpoint that emails a receipt", push back and ask which resource changed and what the resulting representation looks like. The email becomes a side effect of a state transition rather than a permanent URL you can never remove.
Nested paths should express ownership, not deep hierarchies. /users/42/orders reads well because orders belong to a user, but /users/42/orders/42/items/42/reviews is usually a signal that you want a query filter such as ?order_id=42 instead. In a live design round, draw the resource tree first, decide what is a collection versus an item second, and only then discuss payload shapes. Candidates who start with JSON fields tend to produce a bag of loosely related handlers that no client can guess.
The method and status code contract
Clients branch on your status codes, so each one must carry a single unambiguous meaning. The table below is the subset that comes up most often in interviews, along with the mistake that gets candidates marked down.
| Client action | Method and path | Success code | Common wrong choice |
|---|---|---|---|
| Read a list | GET /orders?page=2 | 200 OK | Returning 201 for a read |
| Read one item | GET /orders/42 | 200 OK | Returning an empty body with 200 when missing |
| Item does not exist | GET /orders/999 | 404 Not Found | 400 Bad Request, which blames the client |
| Create an item | POST /orders | 201 Created plus Location | 200 with no created resource |
| Malformed JSON body | POST /orders | 400 Unprocessable Entity | 500, which hides the bug |
| Missing or bad token | any protected route | 401 Unauthorized | 403 Forbidden, which mislabels the failure |
| Authenticated but not allowed | DELETE /orders/42 | 403 Forbidden | 404 used to conceal existence |
| Validation failed | POST /orders | 422 with field errors | A single string with no field detail |
| Repeating a safe request | GET or HEAD | 200 | Treating reads as state changing |
Notice the distinction between 401 and 403. 401 means "who are you?", 403 means "I know who you are and you still may not do this". Mixing them up is one of the fastest ways to show that you have shipped code without reading the specification.
Validate once, at the request boundary
Validation belongs at the edge of the process, not scattered through business logic. In FastAPI the Pydantic model is the boundary: anything that reaches your handler is already typed, range-checked and normalized, so the function body can assume valid input and stay short.
from datetime import datetime
from typing import List, Optional
from fastapi import FastAPI, HTTPException, Query, status
from pydantic import BaseModel, EmailStr, Field
app = FastAPI(title="Orders API", version="2.0.0")
class OrderItem(BaseModel):
sku: str = Field(..., min_length=3, max_length=32)
quantity: int = Field(..., gt=0, le=100)
class OrderCreate(BaseModel):
customer_email: EmailStr
items: List[OrderItem] = Field(..., min_length=1)
note: Optional[str] = Field(None, max_length=500)
class OrderResponse(BaseModel):
id: int
status: str
total_cents: int
created_at: datetime
@app.post("/orders", response_model=OrderResponse,
status_code=status.HTTP_201_CREATED)
def create_order(payload: OrderCreate):
total = sum(item.quantity * 1999 for item in payload.items)
return {"id": 42, "status": "pending", "total_cents": total,
"created_at": datetime.utcnow()}
@app.get("/orders", response_model=List[OrderResponse])
def list_orders(
page: int = Query(1, ge=1),
per_page: int = Query(20, ge=1, le=100),
status_filter: Optional[str] = Query(None, alias="status"),
):
if status_filter not in (None, "pending", "shipped", "cancelled"):
raise HTTPException(422, detail="Unknown status filter")
return []
Two details matter here. First, the response model is a separate schema from the create schema, so a password or internal_note field can never leak into a response by accident. Second, query parameters carry their own constraints, which means ?per_page=10000 fails with a 422 before your handler ever runs. Flask requires you to wire this by hand with Marshmallow or Pydantic plus a decorator, and interviewers often ask you to describe exactly where you would put that check â the answer is always the same place, the request boundary.
Authorization as composable dependencies
Authentication proves identity; authorization decides what that identity may do. In FastAPI both are dependencies, which means they compose: a route can demand a valid token, then demand a role, then demand ownership of the specific row. In Flask the same layering is expressed with stacked decorators, and the ordering of those decorators changes behaviour, a classic source of production bugs.
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt
security = HTTPBearer()
SECRET = "replace-with-env-var"
def current_user(creds: HTTPAuthorizationCredentials = Depends(security)) -> dict:
try:
payload = jwt.decode(creds.credentials, SECRET, algorithms=["HS256"])
except jwt.ExpiredSignatureError:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token expired")
except jwt.InvalidTokenError:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token")
return {"id": payload["sub"], "role": payload.get("role", "user")}
def require_role(*roles: str):
def checker(user: dict = Depends(current_user)) -> dict:
if user["role"] not in roles:
raise HTTPException(status.HTTP_403_FORBIDDEN, "Insufficient role")
return user
return checker
@app.delete("/orders/{order_id}", status_code=status.HTTP_204_NO_CONTENT)
def cancel_order(order_id: int, user: dict = Depends(require_role("admin", "ops"))):
if order_id > 1000:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Order not found")
return None
The dependency returns a value, so handlers receive a typed user object instead of re-parsing headers. That small design choice is what makes the same permission check reusable across dozens of routes without copy-paste.
Versioning and deprecation policy
Version in the URL when the contract breaks in ways clients must opt into, and avoid versioning for purely additive changes. Additive work â a new optional field, a new endpoint â never needs a new version, because well-written clients ignore what they do not recognize. The moment you rename a field, change a type, or alter the meaning of an existing one, you are breaking someone and need /api/v2.
Deprecation is a schedule, not a flag. Announce the sunset date in a Deprecation response header, keep the old version running for a defined window, and emit a Sunset header once the date is close. Interviewers respect candidates who mention that removing a field is rarer than you think and that the cheapest version is the one you never have to introduce.
Error bodies a client can branch on
A flat string forces every caller to pattern-match on prose. A structured error lets a mobile client show a field-level message and a retry policy at the same time. Pick one shape and use it everywhere, including your framework's default 404 and 500 handlers.
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
@app.exception_handler(RequestValidationError)
async def validation_handler(request, exc: RequestValidationError):
errors = [{"field": ".".join(str(p) for p in e["loc"][1:]),
"message": e["msg"]} for e in exc.errors()]
return JSONResponse(status_code=422, content={"error": "validation_failed",
"details": errors})
@app.exception_handler(HTTPException)
async def http_handler(request, exc: HTTPException):
return JSONResponse(status_code=exc.status_code,
content={"error": exc.detail, "request_id": None})
Consistency here pays off twice: your own frontend can render one error component, and your logs can group failures by the stable error key instead of scraping free text.
Idempotency, pagination, and throttling
POST that creates a payment must tolerate a retry, because networks drop responses and users tap twice. The standard answer is an Idempotency-Key header: the server stores the key with the first successful response and replays that response for duplicates within a window. GET, PUT, and DELETE are already required to be idempotent by the specification.
Pagination should be cursor-based once data moves fast enough that offsets skip or duplicate rows. A cursor encodes the last seen sort key, so a page is stable even while inserts happen. Throttling protects you from the client you did not write: return 429 Too Many Requests with a Retry-After header so well-behaved callers back off instead of hammering you.
Common Mistakes
Returning 200 OK for every failure because the request was 'handled'
Fix: Let the status code carry the outcome: 404, 422, 403, 429 all exist so clients do not parse your prose.
Validating inside each handler and forgetting the new endpoint you added on Friday
Fix: Validate once with a schema at the request boundary so every route inherits the rules automatically.
Using a single response model for create, read, and update
Fix: Keep separate request and response schemas; internal fields then cannot leak by accident.
Treating versioning as something you will decide later
Fix: Write the additive-change policy down now, because adding fields must never require a new version.
Best Practices
- Model resources first, then negotiate methods, status codes, and payloads
- Name error codes as stable machine-readable strings and keep human text separate
- Return pagination metadata with every list response so clients can render progress
- Log a request id on every response and thread it through your error handler
- Document the contract with generated OpenAPI output and treat drift as a failing test
- Design the 401, 403, and 404 paths deliberately instead of letting defaults decide
Interview Questions
Q1: When would you version an API, and when would you not?
Only for breaking changes such as renaming or retyping fields. Additive changes, new optional fields, and new endpoints never need a version because conforming clients ignore unknown data.
Q2: What is the difference between 401 and 403, and why does it matter?
401 means the identity is missing or invalid and the client should authenticate; 403 means the identity is known but lacks permission. Using them interchangeably breaks client retry logic.
Q3: How do you make a create endpoint safe to retry?
Accept an Idempotency-Key header, store the key with the first response, and replay that exact response for duplicate requests inside a TTL window.
Q4: Why keep separate Pydantic models for input and output?
It prevents internal or secret fields from being serialized accidentally and lets each direction carry its own validation and documentation.
Q5: Where should authorization live in a FastAPI application?
In dependencies that return the resolved user, so handlers receive a typed object and shared checks compose instead of being re-implemented per route.
Q6: Offset pagination breaks at scale. What do you use instead?
Cursor or keyset pagination keyed on a stable sort column, which keeps pages consistent while rows are inserted or deleted.
Key Takeaways
- Resources and ownership come before payloads and handlers
- Status codes are a contract: 401, 403, 404 and 422 each mean something specific
- Validate at the request boundary with schemas, never inside business logic
- Authentication and authorization compose as dependencies in FastAPI and as stacked decorators in Flask
- Version only on breaking changes, and design retries with idempotency keys
- Structured error bodies make both client code and log analysis simpler