Skip to content
Advertisement

How can I get headers or a specific header from my backend API?

I want to retrieve a specific header from my API inside a function with fastAPI, but I can’t found a solution for this.

In flask was simply: request.headers['your-header-name']

Why the hell with fastAPI is so complicated to do a simple thing like this?

Anyone know a solution to retrieve a header? Thanks :)

The decorator:

JavaScript

I need to read ‘Authorization’ header to check if exist or not.

Advertisement

Answer

It’s pretty similar, you can do

JavaScript

NOTE: that it’s lowercased

Example:

JavaScript

Now if you run this app with uvicorn on your localhost, you can try out sending a curl

curl -H "My-Header: test" -X GET http://localhost:8000

This will result in

{"message":"test"}

UPD:

if you need to access it in decorator you can use following

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement