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 :
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.
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
See documentation below for details.