Middleware
noun
say it: “MID-ul-wair” /ˈmɪdəlwɛr/
In FastAPI, code that runs around every request, before the route and after it, for jobs such as logging, timing or adding headers.
What is Middleware?
Middleware is code that runs around every request, before and after your endpoint, for things like timing, logging or headers.
@app.middleware('http')
async def add_timing(request, call_next):
start = time.perf_counter()
response = await call_next(request)
response.headers['X-Time'] = f'{time.perf_counter() - start:.3f}'
return response
In a sentence
- “A middleware logs each request's method, path and time.”
- “The security headers come from one middleware, not from each route.”
Level: Journeyman · More FastAPI terms at this level
Updated