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
x
23
23
1
def token_required(f):
2
@wraps(f)
3
def decorator(*args, **kwargs):
4
CONFIG = settings.read_config()
5
token = None
6
headers = Request.headers
7
if "Authorization" in headers:
8
auth_header = Request.headers
9
token = auth_header
10
elif not token:
11
return {"Error": "Token is missing or incorrect header name"}, 401
12
13
try:
14
public_key = CONFIG["APPLICATION"]["PUBLIC_KEY"]
15
claim = jwt.decode(token, public_key)
16
claim.validate()
17
except UnicodeDecodeError as err:
18
return {"Error": f"An error occurred -> {err} check your token"}, 401
19
20
return f(*args, **kwargs)
21
22
return decorator
23
I need to read ‘Authorization’ header to check if exist or not.
Advertisement
Answer
It’s pretty similar, you can do
JavaScript
1
8
1
from fastapi import FastAPI, Request
2
3
4
@app.get("/")
5
async def root(request: Request):
6
my_header = request.headers.get('header-name')
7
8
NOTE: that it’s lowercased
Example:
JavaScript
1
10
10
1
from fastapi import FastAPI, Request
2
3
app = FastAPI()
4
5
6
@app.get("/")
7
async def root(request: Request):
8
my_header = request.headers.get('my-header')
9
return {"message": my_header}
10
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
1
10
10
1
def token_required(func):
2
@wraps(func)
3
async def wrapper(*args, request: Request, **kwargs):
4
my_header = request.headers.get('my-header')
5
# my_header will be now available in decorator
6
return await func(*args, request, **kwargs)
7
return wrapper
8
9
10