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

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


Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)