Middleware acts like a gatekeeper or helper that runs for every request. This lets it add or check things like authentication, logging, or headers consistently across all routes.
Middleware can change the request, such as adding headers or data. Route handlers then see this updated request, allowing middleware to influence behavior globally.
Middleware wraps around route handlers. When a request comes in, middleware runs in order before the handler. After the handler returns a response, middleware runs in reverse order to process the response.
FastAPI middleware is designed for HTTP request/response cycles. WebSocket connections use a different protocol and lifecycle, so middleware does not run for them.
from fastapi import FastAPI, Request app = FastAPI()
The correct middleware syntax uses @app.middleware("http") decorator. The function must be async and accept (request, call_next) in that order.