As per the FastAPI docs, the way to create and add custom middlewares is
@app.middleware("http")
async def add_my_middlware(request: Request, call_next):
response = await call_next(request)
return response
Seems simple enough. Before the await, you can do something with the request. After the await, you can do something with the response.
But if you run benchmark, you will find something very surprising.