How to use middleware's in Fastapi app


A "middleware"
is a function that works with every request before it is processed by any specific path operation. And also with every response before returning it.
It takes each request that comes to your application.
It can then do something to that request or run any needed code.
Then it passes the request to be processed by the rest of the application (by some path operation).
It then takes the response generated by the application (by some path operation).
It can do something to that response or run any needed code.
Then it returns the response.
Create a middleware
To create a middleware you use the decorator @app.middleware("http")
on top of a function.
The middleware function receives:
The
request
.A function
call_next
that will receive therequest
as a parameter.This function will pass the
request
to the corresponding path operation.Then it returns the
response
generated by the corresponding path operation.
You can then further modify the
response
before returning it.
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.perf_counter()
response = await call_next(request)
process_time = time.perf_counter() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
Subscribe to my newsletter
Read articles from Dumidu Lakshan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
