Middleware & Error Handling
Add CORS, request IDs, and consistent exception handlers.
Recipe
Quick-reference recipe card - copy-paste ready.
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["https://app.example"], allow_methods=["*"], allow_headers=["*"])
@app.middleware("http")
async def add_request_id(request: Request, call_next):
response = await call_next(request)
response.headers["X-Request-Id"] = request.headers.get("X-Request-Id", "generated")
return responseWhen to reach for this:
- Browser clients need CORS
- Uniform JSON errors
- Cross-cutting request metadata
Working Example
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
app = FastAPI()
class AppError(Exception):
def __init__(self, code: str, status: int = 400):
self.code = code
self.status = status
@app.exception_handler(AppError)
async def app_error_handler(_: Request, exc: AppError):
return JSONResponse(status_code=exc.status, content={"error": exc.code})
@app.get("/boom")
def boom():
raise AppError("invalid_state", 422)What this demonstrates:
- CORS middleware
- HTTP middleware for headers
- Registered exception handlers
Deep Dive
How It Works
- Middleware wraps requests outermost-first for
add_middlewareorder. - Exception handlers convert domain errors to stable JSON.
- Log server-side details; return safe messages to clients.
Gotchas
- Boundary validation skipped - Invalid data reaches persistence layers.. Fix: Validate with Pydantic or framework forms at the edge..
- Leaking stack traces - Clients see internal errors.. Fix: Map exceptions to stable HTTP responses..
- Blocking async event loops - Workers stall under concurrent load.. Fix: Use async drivers or threadpool wrappers..
- Secrets in source control - Credentials leak via git history.. Fix: Load secrets from env or a vault at runtime..
- Missing observability - Incidents are hard to debug.. Fix: Add structured logs, metrics, and request IDs..
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
| Alternate framework in this cookbook | Team standard or existing monolith | Greenfield API with different constraints |
| Managed BaaS | CRUD-only MVP | Custom auth, workflows, or compliance needs |
| gRPC | Internal high-performance RPC | Public HTTP clients and browser access |
FAQs
When should I adopt FastAPI middleware?
Use it when the patterns and trade-offs on this page match your API or data boundary.
What is the top production mistake with FastAPI middleware?
Skipping validation, timeouts, or explicit error contracts at the HTTP edge.
How do I test FastAPI middleware?
Use the framework test client, override dependencies, and assert status plus JSON shape.
Does FastAPI middleware work with Python 3.14?
Yes - examples target Python 3.14 with pinned framework versions from the stack footer.
How does FastAPI middleware relate to Pydantic 2?
Validate and serialize at boundaries; keep services working with typed domain objects.
Sync or async?
Prefer async routes when I/O dominates; keep CPU work small or offload to workers.
Where should business logic live?
Thin handlers; services own rules; repositories own queries.
How do I document APIs?
Publish OpenAPI or schema docs that match response models in code.
How do I handle versioning?
Explicit URL or header versioning with deprecation windows - avoid silent breaks.
What should I read next?
Follow the Related links for the next layer of depth in this section.
How do I stay secure?
Authenticate callers, authorize per resource, rate-limit, and never log secrets.
Performance first step?
Measure DB and upstream latency before swapping frameworks.
Related
- FastAPI Basics - Core routes and models
- Dependency Injection - Per-request providers
- Testing FastAPI - Test client patterns
- Deploying FastAPI - Production serving
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.