FastAPI interview question · Most asked

How do you add middleware and configure CORS in FastAPI?

Summary

Add middleware with app.add_middleware(...) (e.g., CORSMiddleware, GZipMiddleware, TrustedHostMiddleware) or write HTTP middleware with @app.middleware("http").

Longer Answer

CORS: list exact allow_origins (avoid * with allow_credentials=True; browsers reject it). Middleware wraps every request, so it suits timing, request IDs and security headers. For performance-critical code, pure ASGI middleware avoids the overhead of BaseHTTPMiddleware. Middleware order matters: the last added is the outermost.

Code Example

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

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.middleware("http")
async def add_request_id(request, call_next):
    request_id = request.headers.get("x-request-id", str(uuid.uuid4()))
    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

Key Points

  • CORSMiddleware with explicit origins
  • @app.middleware('http') for simple cases
  • Pure ASGI middleware for performance
  • Order: last added runs first

Deep dive: Request Lifecycle course: FastAPI and Starlette: Middleware, Exceptions and Dependencies

More most-asked FastAPI questions

← All FastAPI questions