How do you implement middleware in FastAPI?
Answer
FastAPI (via Starlette) supports ASGI middleware. Built-in middleware: app.add_middleware(CORSMiddleware, ...), app.add_middleware(HTTPSRedirectMiddleware), app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com"]). Custom middleware using Starlette's BaseHTTPMiddleware: class LoggingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): start = time.time(); response = await call_next(request); print(f"Request took {time.time()-start:.3f}s"); return response. Register: app.add_middleware(LoggingMiddleware). For pure ASGI middleware (lower level, more performant): wrap the app directly using the @app.middleware("http") decorator. Note: middleware wraps all requests including the auto-generated docs. Use dependency injection instead of middleware for route-specific concerns — it is more targeted and testable.
Previous
What is Pydantic v2 and what changed from v1?
Next
What is Alembic and how does it work with FastAPI?
More FastAPI / Flask Questions
View all →- Intermediate How do you implement JWT authentication in FastAPI?
- Intermediate How does SQLAlchemy async work with FastAPI?
- Intermediate What is Flask's application factory pattern?
- Intermediate How do you implement background tasks in FastAPI?
- Intermediate What is Pydantic v2 and what changed from v1?