Tips and Tricks

FastAPI

FastAPI Middleware


FastAPI tip:

You can add custom middleware to your app to do something before or after each request.

For example, to add a header containing the version of your application for easier debugging:

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def add_version_header(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Version"] = "v1.2.10"
    return response


@app.get("/ping")
def ping():
    return {"message": "pong"}