Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass Authorization Header from Swagger Doc in Python Fast API [duplicate]

I am trying to pass authorization header using Documentation page, similar to this page:

enter image description here

Since, the documentations are automatic generated in Fast API, I am having hard time trying to figure this out. I followed this page https://fastapi.tiangolo.com/tutorial/security/ but couldn't find any info about passing the bearer token. Please note, I am not looking for validating the token, I am just looking for a way to pass bearer token through documentation page.

Can anyone please refer to some relevant documentation or with help.

like image 890
kaounKaoun Avatar asked Dec 17 '25 12:12

kaounKaoun


1 Answers

Authorization header cannot be asked by using Header().

You need a SecurityBase based Depends like HTTPBearer to tell swagger your api endpoint needs an Authorization header.

from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

auth_scheme = HTTPBearer()
@app.get("/me")
async def echo_me(token: HTTPAuthorizationCredentials = Depends(auth_scheme))
    ...

You can write a class inherits HTTPBearer or other security class if you want the credential be optional.

from fastapi import Depends, HTTPException, Request

class OptionalHTTPBearer(HTTPBearer):
    async def __call__(self, request: Request) -> Optional[str]:
        from fastapi import status
        try:
            r = await super().__call__(request)
            token = r.credentials
        except HTTPException as ex:
            assert ex.status_code == status.HTTP_403_FORBIDDEN, ex
            token = None
        return token

auth_scheme = OptionalHTTPBearer()
@app.get("/test")
async def test(token = Depends(auth_scheme)):
    return dict(token=token)
like image 87
Li-chih Wu Avatar answered Dec 20 '25 08:12

Li-chih Wu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!