Search code examples
pythonapipython-requestsaccess-token

How to store access_token for more requests on API (Python)


I am making API requests via Python's 'requests'-module. I am getting the access_token, which is a Bearer token. I've put the token into a variable like this:

def get_token():
    url = 'https://myapiurl.com/oauth/token'
    payload = {'username':'myusername', 'password':'mypassword'}
    headers = {'Content-Type': 'application/json', 'origin': 'https://blabla.com'}
    r = requests.post(url, data=json.dumps(payload),headers=headers)
    mytoken = r.json()['token_type']
    mytokentype = r.json()['access_token']
    token_param = str(mytoken) + ' ' + str(mytokentype)
    return token_param

The output is a string that has this structure:

Bearer eyJ0eXAiOiJKV1QiLCJhb.....0sImF6cCI6ImVCOEdI

I need this structure for the following GET requests where this access_token is required. I don't want to get a new token everytime I make a new GET-request.

I have issues in finding out how to:

1: store an access_token

2: check if the access_token is valid

3: use this token to make other GET requests on my API.

I am very thankful for any advice.


Solution

  • My answer:

    I've put the whole output of my POST request into the variable result. The structure of my token has to be like this: "Bearer tokenstring". So I put the type into the variable result_tokentypeand the token string into the variable result_accesstoken. Finally I put them together into the variable accessToken:

    result_tokentype = result["token_type"]
    result_accesstoken = result["access_token"]
    accessToken = str(result_tokentype) + " " + str(result_accesstoken)
    

    Now that I have the complete string in the right structure, I can use this variable for the next requests, e.g.:

    url = "https://myurl.com"
    headers = {"Authorization": accessToken, "key1": "value1", "Content-Type": "application/json" }
    conn.request("GET", url, headers=headers)
    

    This worked the best for me, here.