Search code examples
pythonflaskflask-restful

How to read a bearer token from postman into Python code?


I am trying to create an API that receives arguments from postman. The body of the api contains two arguments:

{
    "db":"EUR",
    "env":"test"
}

I parsed these two arguments in the code as below:

parser = reqparse.RequestParser()
parser.add_argument('fab', type=str, required=True, help='Fab name must be provided.')
parser.add_argument('env', type=str, required=False, help='Env is an optional parameter.')

Lately I was asked to add a token validation in the code. The token is passed from Authorization-> Type(Bearer Token) -> Token value: eeb867bd2bcca05

enter image description here

But I don't know how can I read the bearer token from postman into Python code. Could anyone let me know how to read the token value that is being passed from Postman's bearer token into my Python code ? Any help is much appreciated.


Solution

  • The Bearer token is sent in the headers of the request as 'Authorization' header, so you can get it in python flask as follows:

    headers = flask.request.headers
    bearer = headers.get('Authorization')    # Bearer YourTokenHere
    token = bearer.split()[1]  # YourTokenHere