FastAPI makes processing Headers very easy, just like everything else. There are two ways to process headers with FastAPI.

Via Request Object

When writing middleware we have direct access to the Request, so it is much easier to write as :

1
2
3
4
5
@app.middleware("http")
async def my_middleware(request: Request, call_next):
        headers = request.headers
        if "X-My-Header" in headers:
            # Do something with X-My-Header

As a Function Param

When writing normal endpoints, it is easier to process headers. One of your function parameter could be Header itself. FastAPI will do all the work for you, so that you can focus on the business logic.

See the sample code from FastAPI documentation of this topic.

1
2
3
4
5
6
7
8
from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(*, user_agent: str = Header(None)):
    return {"User-Agent": user_agent}

Important thing to remember that variable name must be in snake_case.

e.g. In the sample code above, we are processing User-Agent header. So variable name must be user_agent. Names with - are invalid in python. So FastAPI will convert the dashes/hyphens to underscore for you.

But wait ..

If you really don't want the auto conversion to underscore. just tell FastAPI that via convert_underscores=False

See documentation below for details.

Resources