DEV Community

Mandar Vaze
Mandar Vaze

Posted on • Originally published at

How to Process Headers using FastAPI

This was originally posted on my blog, here.

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 :

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.

from fastapi import FastAPI, Header

app = FastAPI()

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.


Top comments (0)