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:

def token_required(f):
    @wraps(f)
    def decorator(*args, **kwargs):
        CONFIG = settings.read_config()
        token = None
        headers = Request.headers
        if "Authorization" in headers:
            auth_header = Request.headers
            token = auth_header
        elif not token:
            return {"Error": "Token is missing or incorrect header name"}, 401

        try:
            public_key = CONFIG["APPLICATION"]["PUBLIC_KEY"]
            claim = jwt.decode(token, public_key)
            claim.validate()
        except UnicodeDecodeError as err:
            return {"Error": f"An error occurred -> {err} check your token"}, 401

        return f(*args, **kwargs)

    return decorator

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

Advertisement

Answer

It’s pretty similar, you can do

from fastapi import FastAPI, Request


@app.get("/")
async def root(request: Request):
    my_header = request.headers.get('header-name')
    ...

NOTE: that it’s lowercased

Example:

from fastapi import FastAPI, Request

app = FastAPI()


@app.get("/")
async def root(request: Request):
    my_header = request.headers.get('my-header')
    return {"message": my_header}

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

def token_required(func):
    @wraps(func)
    async def wrapper(*args, request: Request, **kwargs):
        my_header = request.headers.get('my-header')
        # my_header will be now available in decorator
        return await func(*args, request, **kwargs)
    return wrapper


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