Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

Chapter 4: Middleware and the ASGI Pipeline

ASP.NET Core middleware wraps the request delegate. ASGI middleware does the same conceptual job: inspect or modify requests and responses around downstream handling.

Common Python middleware:

Example:

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

app = FastAPI()

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


@app.middleware("http")
async def add_request_id(request: Request, call_next):
    request_id = request.headers.get("x-request-id", "generated-later")
    response = await call_next(request)
    response.headers["x-request-id"] = request_id
    return response

Best practice: