Write a FastAPI middleware that adds X-Process-Time header
Tests FastAPI lifecycle and header mutation. Strong answers use the http middleware decorator, await call_next, compute elapsed time, and inject X-Process-Time before returning. Red flag: forgetting to await call_next or mutating headers after the return.
Tests FastAPI middleware contract and response mutation. A complete answer covers four steps: first, register with @app.middleware("http"); second, define an async function taking Request and call_next; third, await call_next(request) to get the downstream response; fourth, calculate elapsed time with time.perf_counter, set response.headers["X-Process-Time"], and return the same response. Red flags include forgetting to await call_next, creating a new Response instead of enriching the original, or setting headers on the request object.
Read the original → fastapi.tiangolo.com
- #fastapi
- #middleware
- #python
- #performance
- #headers
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.