CatGirl19
CatGirl19

Reputation: 209

Post Request to retrieve bearer token in Python

Im having trouble doing a post request call to get the bearer token in Python.

This is my current Python code with the hard coded bearer token.

url = 'https://someURL'
headers = {'Authorization' : 'Bearer <MyToken>'} # I'm hard coding it here from a postman call I'm doing

r = requests.get(url, headers=headers)

#This part prints entire response content in a text like format [{'x':'' ,'y':'', ...etc},{'x':'' ,'y':'', ...etc},...etc]

jsonResponse = r.json()
print("Entire JSON response")
print(jsonResponse)

print("Print each key-value pair from JSON response")
for d in jsonResponse:
    for key, value in d.items():
        if(key == 'groupId'):
            print(key, ":", value)

I've previously been able to do post request in JavaScript like so:

var options = {
    method: 'POST',
    url: 'https://myurl',
    qs:
    {
      grant_type: 'client_credentials',
      scope: 'api',
      client_id: 'xyz',
      client_secret: '123456abc'
    },
    headers:
    {
      'cache-control': 'no-cache',
    }
  };

How can I get a bearer token post request working in Python?

Upvotes: 2

Views: 7700

Answers (1)

David Silveiro
David Silveiro

Reputation: 1602

You can create a simple post request like so and then retrieve the json with response.json() which you were already doing :)

data = {
  grant_type: 'client_credentials',
  scope: 'api',
  client_id: 'xyz',
  client_secret: '123456abc'
}

response = requests.post(url, data=data)
jsonResponse = response.json

Upvotes: 1

Related Questions