Lesson 13 of 59Building a real API
Errors and Middleware
Return consistent errors with exception handlers, and wrap every request with middleware for timing, request IDs, CORS, compression and logs.
When something goes wrong in production, two people need good information: the client, who needs a clear, consistent error it can show or handle, and you, who need a log line that says exactly which request failed and why. FastAPI gives you exception handlers for the first and middleware for the second. Getting both right is the difference between a five-minute fix and a day of guessing.
HTTPException and its limits
You have already used HTTPException. It accepts a status, a detail (a string or any JSON-able value) and optional headers:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail={"code": "duplicate_title", "message": "A todo with that title exists"},
)That works in a route. But deeper code, like a service that applies business rules, should not know about HTTP at all: the same service might be called from a background job or a command line script. Raise your own exceptions there, and translate them to HTTP in one place.
class AppError(Exception):
status_code = 400
code = "bad_request"
def __init__(self, message: str):
self.message = message
class NotFound(AppError):
status_code = 404
code = "not_found"
class Conflict(AppError):
status_code = 409
code = "conflict"from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from app.errors import AppError
app = FastAPI()
@app.exception_handler(AppError)
async def handle_app_error(request: Request, exc: AppError) -> JSONResponse:
return JSONResponse(
status_code=exc.status_code,
content={"error": {"code": exc.code, "message": exc.message}},
)Now a service raises NotFound("Todo 42 not found") and every client gets the same JSON shape. Handlers match by class, so one handler for AppError covers every subclass. You can also register a handler for FastAPI's RequestValidationError to reshape the default 422 body.
The {"error": {...}} shape here is a placeholder. Which shape to choose, and why the standard RFC 9457 application/problem+json format is usually the right answer, is the subject of Error Responses Clients Can Rely On. This lesson is about the machinery: where exceptions go and what wraps every request.
NotFound from a service instead of HTTPException(404)?What FastAPI does with an exception
Here is the mechanism in a few lines. The handler registry is a dict from exception class to function, and the lookup walks the class's parents (its MRO, method resolution order) until it finds one.
Press Run (⌘ Enter) to see what happens.Look at the last line. The ZeroDivisionError becomes a bland 500 with no stack trace. Never send tracebacks, SQL errors or file paths to clients: they help attackers map your system. Log the details on the server instead, tagged with a request id so you can find them.
Using the code above, what does this print?
def clash():
raise Conflict("Title taken")
print(call_route(clash)[0])Middleware: code around every request
Middleware wraps the whole app. It sees each request before any route and each response after, which makes it the place for cross-cutting work: timing, request ids, CORS headers, compression, logging.
import time
import uuid
@app.middleware("http")
async def add_request_id_and_timing(request: Request, call_next):
request_id = request.headers.get("x-request-id") or uuid.uuid4().hex
start = time.perf_counter()
response = await call_next(request) # everything inside runs here
elapsed_ms = (time.perf_counter() - start) * 1000
response.headers["X-Request-ID"] = request_id
response.headers["Server-Timing"] = f"app;dur={elapsed_ms:.1f}"
return responsecall_next(request) passes the request inward (to the next middleware, and eventually the route) and returns the response. Code before it runs on the way in; code after it runs on the way out. Several middlewares nest like layers of an onion.
On the way in, each layer runs the code before its call_next, outermost first.
Build the onion yourself. Each middleware takes the request and a call_next function:
Press Run (⌘ Enter) to see what happens.In the second request auth_mw returns early, so the route never runs, yet logging_mw still logs the response on the way out. That is why logging and error handling go on the outside.
build([timing, request_id], route). Order the printed steps for one request, if each middleware prints before and after call_next.
- Tap the steps below in the right order.
Registration order: the last one added is the outermost
The toy build function takes a list where the first item is the outermost layer. FastAPI works the other way round, and this catches people out. Each app.add_middleware(...) call wraps everything registered so far, so the last middleware you add becomes the outermost layer and runs first on the way in. The @app.middleware("http") decorator is the same thing as an add_middleware call at the line where it appears.
app.add_middleware(AuthMiddleware) # added first: innermost of the three
app.add_middleware(TimingMiddleware)
app.add_middleware(RequestIDMiddleware) # added last: outermost, runs firstChecked against FastAPI 0.161 and Starlette 1.9 with three middlewares that log before and after call_next, the log reads RequestID in, Timing in, Auth in, route, Auth out, Timing out, RequestID out. So the rule of thumb is to write add_middleware calls from the inside out: the thing closest to your routes first, the things that must see everything (request ids, error tracking, CORS) last.
Order is not a style choice. Two real bugs it causes:
- CORS inside auth. If an auth middleware is outside
CORSMiddleware, it rejects the browser's preflightOPTIONSrequest (which never carries credentials) with a401, and the browser reports a confusing CORS error instead of an auth error. AddCORSMiddlewarelate so it sits outside auth and answers preflights before anything else looks at them. - Timing that lies. A timing middleware inside GZip does not count compression time. If you care about the time the client actually waited, it needs to be outside.
Starlette also adds its own two layers that you never register: ServerErrorMiddleware is always the very outermost, and ExceptionMiddleware (which runs your exception handlers) sits just inside your middlewares, as the Stack above shows. That detail matters for request ids, as you will see shortly.
Each middleware appends its name to a list before calling call_next. What is the final list after one request?
app.add_middleware(Gzip)
app.add_middleware(Cors)
@app.middleware("http")
async def timing(request, call_next):
calls.append("timing")
return await call_next(request)
app.add_middleware(RequestID)
# one request later:
print(calls)BaseHTTPMiddleware versus pure ASGI middleware
The @app.middleware("http") decorator, and classes that subclass Starlette's BaseHTTPMiddleware with a dispatch(request, call_next) method, are the friendly way to write middleware. You get a Request and a Response object, and that convenience has a price you should know about.
To hand you a Response from call_next, BaseHTTPMiddleware runs the inner app in a separate task and pipes its messages back through a memory stream. Three consequences follow:
- Context variables do not flow back up. A value the middleware sets with a
ContextVarbeforecall_nextis visible in the route. A value the route sets is not visible to the middleware aftercall_nextreturns. In a test on Starlette 1.9, a middleware set a variable toset-in-mw, the route changed it toset-in-route, and aftercall_nextthe middleware still readset-in-mw. Pass data upwards throughrequest.stateinstead. - Streaming is wrapped. A
StreamingResponseor Server-Sent Events still stream, but every chunk now hops through an extra stream and task. Reading the body in the middleware means consuming the stream, so middleware that logs response bodies breaks streaming endpoints. - It costs something on every request. The extra task and stream add overhead per request per layer. For one or two layers in a typical CRUD API it is noise; stacked five deep in front of a hot endpoint, it shows up in benchmarks.
A pure ASGI middleware has none of these issues, because it is just an ASGI app wrapping an ASGI app, with the scope, receive, send shape from ASGI and Uvicorn. It never builds a Response. To change a response, it wraps send and edits messages as they pass through. Starlette's built-in middleware (CORS, GZip, TrustedHost) is written this way.
Press Run (⌘ Enter) to see what happens.The headers appear in the order the layers ran on the way out: the inner wrapper added x-request-id first, then the outer one added server-timing. The body went through without being read or buffered, which is why this style is safe for streaming.
The trade-off is that pure ASGI middleware is more code and easier to get subtly wrong: forgetting the scope["type"] check breaks websockets and lifespan, and changing the body means fixing Content-Length too. A reasonable rule at work: use @app.middleware("http") for quick, low-traffic things, and write pure ASGI middleware for anything on every request in a busy service, anything that touches context variables, and anything near streaming endpoints.
A request ID middleware with ContextVar
Logging and Observability showed why a request id in every log line matters, and set a ContextVar from a decorator middleware. Here is the production version as pure ASGI middleware, with two details that version skipped: validating the incoming header, and making the id available to the handler that builds 500 responses.
import contextvars
import uuid
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
request_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")
class RequestIDMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
incoming = dict(scope["headers"]).get(b"x-request-id", b"").decode("latin-1")
# Never trust a client header blindly: it ends up in logs and responses.
request_id = incoming if incoming.isalnum() and len(incoming) <= 64 else uuid.uuid4().hex
scope.setdefault("state", {})["request_id"] = request_id # becomes request.state.request_id
token = request_id_var.set(request_id)
async def send_with_id(message: Message) -> None:
if message["type"] == "http.response.start":
MutableHeaders(scope=message).append("X-Request-ID", request_id)
await send(message)
try:
await self.app(scope, receive, send_with_id)
finally:
request_id_var.reset(token)Validating the incoming id matters more than it looks. The header comes from the client, so without a check an attacker can send a 10 KB id, or one containing newlines that forges extra lines in plain-text logs. Accept the load balancer's id only if it looks like an id, and generate your own otherwise.
Now the subtle part. Because ServerErrorMiddleware is outside every middleware you add, a handler registered for plain Exception runs after your request id middleware has already finished. Tested on FastAPI 0.161: the 500 from such a handler had no X-Request-ID header, and request_id_var.get() inside it returned the default -. Copying the id into scope["state"] fixes it, because the scope dict is shared by every layer, so the handler can read request.state.request_id and set the header itself:
@app.exception_handler(Exception)
async def unhandled(request: Request, exc: Exception) -> JSONResponse:
request_id = getattr(request.state, "request_id", "-")
logger.exception("unhandled error", extra={"request_id": request_id})
return JSONResponse(
{"detail": "Internal server error", "request_id": request_id},
status_code=500,
headers={"X-Request-ID": request_id},
)Putting the request id in the body of a 500 is a kindness to whoever handles support tickets: the user pastes it, you search your logs for it, and the traceback is right there.
X-Request-ID to every response, yet 500 responses from your @app.exception_handler(Exception) handler arrive without it. Why?CORS
Your React app runs on https://app.example.com and calls the API on https://api.example.com. Those are different origins (scheme, host and port must all match to be the same origin). By default, browsers block JavaScript from reading responses from another origin. CORS (Cross-Origin Resource Sharing) is how the API says "this origin is allowed".
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com", "http://localhost:5173"],
allow_credentials=True, # allow cookies / Authorization
allow_methods=["*"],
allow_headers=["*"],
)For "non-simple" requests (JSON bodies, custom headers, PUT/PATCH/DELETE), the browser first sends a preflight OPTIONS request to ask permission:
Sent automatically with Origin: https://app.example.com and Access-Control-Request-Method: PATCH.
Two facts trip people up. CORS is enforced by browsers, not servers: curl and other backends ignore it, so it is not a security boundary against scripts, only a protection for users' browsers. And with allow_credentials=True you cannot use allow_origins=["*"]; you must list origins.
GZip and TrustedHost
Two more built-in middlewares belong in most production apps, and both have settings worth knowing rather than copying.
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=5)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.example.com", "*.example.com"])GZipMiddleware compresses responses when the client sends Accept-Encoding: gzip, and adds Vary: Accept-Encoding so caches keep compressed and plain copies apart. Large JSON lists often shrink by 80 to 90 percent. A few things to know:
minimum_size(default 500 bytes) skips small responses, where the gzip header overhead and CPU cost outweigh the saving.compressleveldefaults to 9, the slowest. Levels around 4 to 6 get most of the saving for much less CPU, which matters on a busy API.- In Starlette 1.9 it skips content types that are already compressed or must not be buffered: images, video, zip files, gRPC and
text/event-stream, through anexclude_content_typesoption. Older versions compressed everything, which broke Server-Sent Events by buffering them. If you stream events, check your version. - If a reverse proxy or CDN in front of you already compresses (nginx, Cloudflare, most load balancers can), doing it in Python too is wasted CPU. Pick one place.
TrustedHostMiddleware rejects requests whose Host header is not on your list with 400 Invalid host header. That sounds pointless until you remember that code builds URLs from the request: password reset links, redirects, request.url_for(...). If an attacker can send Host: evil.example and your app emails a reset link built from it, the victim clicks a link to the attacker's site. That is host header injection. Wildcards like *.example.com are allowed, and www_redirect (on by default) redirects example.com to www.example.com when only the www form is listed. In tests, remember that TestClient sends Host: testserver, so add it to the list in test settings or your whole suite gets 400s.
Match each built-in middleware to the problem it solves.
Logging
Use Python's logging module, not print. Logs have levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), go to stdout where your platform collects them, and can include structured fields.
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
logger = logging.getLogger("todo_api")
logger.info("todo created", extra={"request_id": request_id, "todo_id": todo.id})
logger.exception("payment failed") # inside except: logs the traceback tooIn production, format logs as JSON (one object per line) so tools like CloudWatch, Datadog or Grafana Loki can filter by request_id or status. Include the request id in every line, and never log passwords, tokens or full card numbers.
Match each concern to where it belongs.
Practice
A middleware chain
Requests are dicts like {"method": "GET", "path": "/todos", "headers": {...}} and responses are dicts like {"status": 200, "headers": {}, "body": ...}. A handler takes a request and returns a response. A middleware is mw(request, call_next) and returns a response.
Write three functions:
-
build_chain(middlewares, handler)returns a functionapp(request). The first middleware in the list is the outermost: it runs first on the way in and last on the way out. With an empty list,appis just the handler. -
request_id_middleware(request, call_next): use the request's"x-request-id"header if present, otherwise generateuuid.uuid4().hex. Store it asrequest["request_id"]before callingcall_next, and setresponse["headers"]["x-request-id"]on the way out. -
error_middleware(request, call_next): if anything inside raises, return{"status": 500, "headers": {}, "body": {"detail": "Internal Server Error"}}instead of crashing. Never put the exception message in the body.
app = build_chain([error_middleware, request_id_middleware], route)
app({"method": "GET", "path": "/", "headers": {"x-request-id": "abc"}})
# {"status": 200, "headers": {"x-request-id": "abc"}, "body": ...}Sliding window rate limiter
Protect an API from a client hammering it. Write RateLimiter(limit, window, clock):
limit: max requests per key within anywindowseconds.clock: a function returning the current time in seconds (tests pass a fake clock).allow(key) -> bool:Trueand record the request if the key has made fewer thanlimitrequests in the lastwindowseconds (a request at timetcounts whilenow - t < window). OtherwiseFalse, and the rejected request is not recorded.retry_after(key) -> float:0if a request would be allowed now, otherwise the seconds until the oldest counted request expires. This is what you would send in aRetry-Afterheader with a429 Too Many Requests.
Keys are independent (for example one per user id or IP).
now = [0.0]
rl = RateLimiter(limit=2, window=10, clock=lambda: now[0])
rl.allow("ada"), rl.allow("ada"), rl.allow("ada") # True, True, False
rl.retry_after("ada") # 10.0
now[0] = 10.0
rl.allow("ada") # True- exception handler
- A function registered with
@app.exception_handler(SomeError)that turns an exception into a response. - middleware
- Code that wraps the app and runs before and after every request via
call_next. - request id
- A unique id per request, returned in a header and added to every log line so one request can be traced.
- CORS
- Headers an API sends to tell browsers which other origins may read its responses.
- preflight
- An automatic
OPTIONSrequest a browser sends to ask whether a cross-origin request is allowed. - pure ASGI middleware
- Middleware written as an ASGI app that wraps another, editing messages via a wrapped
sendinstead of buildingResponseobjects. - BaseHTTPMiddleware
- Starlette's convenient
dispatch(request, call_next)base class. Runs the inner app in a separate task, so context changes do not flow back up. - host header injection
- An attack that forges the
Hostheader so the app builds links or redirects to an attacker's domain.