'How to Pass Authorization Header from Swagger Doc in Python Fast API

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.



Solution 1:[1]

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 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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1