Middleware chạy trước và sau mỗi request.
Dùng @app.middleware("http") cho custom middleware.
python
import time, uuid
from fastapi import Request
@app.middleware("http")
async def logging_middleware(request: Request, call_next):
request_id = str(uuid.uuid4())
start = time.perf_counter()
response = await call_next(request)
duration = time.perf_counter() - start
response.headers["X-Request-ID"] = request_id
response.headers["X-Duration"] = f"{duration:.4f}"
return responseCORS, GZip, TrustedHost — dùng built-in middlewares.
Pitfall: Middleware exception handler không bắt HTTP exceptions từ path operations — dùng exception_handler thay.