Python & FastAPI•Part 4: Web Frameworks, APIs & FastAPI (41 - 55)
FastAPI Middleware:
In Simple Words: Intercepts incoming HTTP requests before reaching endpoints and inspects outgoing responses (e.g. adding request timings or correlation IDs).
python
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)
duration = time.perf_counter() - start
response.headers["X-Process-Time"] = f"{duration:.4f}s"
return response