Middleware wraps every request and response: code before call_next runs before the endpoint and code after it runs on the response; use it for cross-cutting concerns such as logging, timing, request IDs, CORS and compression.
Use dependencies for logic that applies only to specific routes (authentication, database sessions, validation), because middleware runs on everything and heavy logic slows every request.
import time
from fastapi import Request
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start = time.perf_counter()
response = await call_next(request)
response.headers["X-Process-Time"] = f"{time.perf_counter() - start:.4f}"
return response