pythontoken

How to retrieve a token from an API and send to another


I have one API that's dependent on the authentication of another. The Auth API returns a token which is the necessary parameter to get a response from the second.

import requests
import json

url_auth = 'https://api.com/token'

payload_auth = {'grant_type': 'client'} 

username = "username"
password = "password"
  
response_auth = requests.post(url_auth, auth=(username, password), data=payload_auth)

data = response_auth.json()

print(data["access_token"])

url_ref = 'https://api.com/api/operation/consult'

payload_ref = json.dumps([
  {
    "operation": "1",
    "Reference": "DDD",
    "Status": "1"
  }
])

data_ref = data["access_token"]

response_ref = requests.get(url_ref, auth=data_ref, data=payload_ref)    

But whenever I try executing I get an error: TypeError: 'str' object is not callable

Since I can only get this token from the previous authentication, what can I do to pass this parameter to the API ?


Solution

  • Try using headers!

    Like so:

    header = {"Authorization": f"Bearer {access_token}"}
    
    response_ref = requests.get(url_ref, headers=header, data=payload_ref)  
    

    Of course, it depends on what type of Authentication it has. In this case, it's a Bearer token only because it's the most common. You can check through Postman how to create an header based on the token you need!