FastAPI: From Basics to Production · Building Real APIs

Middleware, CORS and Request Context

Add cross-cutting behavior: CORS, request IDs, timing and security headers.

Middleware wraps every request/response. Use CORSMiddleware for browser clients on other origins (explicit origins, not * with credentials), GZipMiddleware for compression, and TrustedHostMiddleware to reject unexpected Host headers. Write custom middleware for request IDs and timing. For heavy middleware prefer pure ASGI middleware; @app.middleware("http") is convenient but adds overhead.

import time, uuid
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)


@app.middleware("http")
async def request_context(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)
    response.headers["X-Request-ID"] = request_id
    response.headers["Server-Timing"] = f"app;dur={(time.perf_counter() - start) * 1000:.1f}"
    return response

Common pitfalls

  • allow_origins=['*'] with allow_credentials=True (browsers reject it; and it's insecure intent).
  • Thinking CORS protects your API from non-browser clients.
  • Reading the request body in middleware (consumes the stream).

Key points

  • CORS is a browser mechanism
  • Request IDs for correlation
  • Keep middleware light

Further reading: FastAPI: CORS

Go deeper: FastAPI and Starlette: Middleware, Exceptions and Dependencies in the Request Lifecycle course traces this step of the request, with a production bug and a runnable simulation.

Practice questions

Does CORS protect your API from curl or server-side attackers?

Answer

No. CORS only tells browsers which cross-origin pages may read responses; non-browser clients ignore it. Use authentication and authorization.

Why add a request ID in middleware?

Answer

To correlate logs, traces and error reports for one request across services, and let clients report it for support.

Open in the app to mark lessons complete, take notes and track your progress.