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
CORSMiddlewarewith 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
- How does dependency injection with `Depends` work in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?