Middleware in FastAPI

Difficulty: Intermediate

Question

What is middleware in FastAPI and how do you add it? Give an example use case.

Answer

Middleware is code that runs on every request before it reaches the route handler, and on every response before it's returned to the client. It wraps the entire request/response cycle.

Add middleware using `@app.middleware('http')` decorator or `app.add_middleware(MiddlewareClass, options)`.

Common use cases: - Request timing and logging - CORS (Cross-Origin Resource Sharing) - Authentication token extraction - Rate limiting - Request ID injection - GZip compression

Code examples

Custom middleware and CORS

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

app = FastAPI()

# Built-in CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://example.com", "http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Custom timing middleware
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)  # call the route handler
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

Key points

Concepts covered

middleware, CORS, request/response cycle, BaseHTTPMiddleware