jack
jack

Reputation: 861

Python Requests POST - error 400

I have this code:

import requests
import json 

data={"client_id" : "a", "client_secret" : "thisissecret", "grant_type" : "clientcredentials", "scope" : "PublicApi"}

url = 'http://MYURL/connect/token'
response = requests.post(url, json=data, verify=False)
print(response)
print response.reason
print(response.json())

I'm trying to test connection to a new auth service in test environment (which is why verify is FALSE) This should give me the access token and the token type and with them I can POST to the API.

But I always get:

<Response [400]>  Bad Request   {u'error': u'invalid_request'}

I'm not sure what is the problem? Why is it a bad request?

Upvotes: 1

Views: 14941

Answers (2)

Guillaume
Guillaume

Reputation: 6029

Looks like you are trying to obtain an OAuth 2.0 access token using the client_credientials grant. This is described in RFC6749

I see 2 problems here:

  • You must post your fields as application/x-www-form-urlencoded instead of json. To do so, use the data parameter of request.post() instead of json
  • The grant_type value must be client_credentials instead of clientcredentials

Which gives:

import requests

data = {"client_id" : "a", "client_secret" : "thisissecret", 
        "grant_type" : "client_credentials", "scope" : "PublicApi"}

url = 'http://MYURL/connect/token'
response = requests.post(url, data=data, verify=False)
if response.ok:
    print(response.json())

Upvotes: 2

ScottMcC
ScottMcC

Reputation: 4460

Perhaps you need to set the content type of the header?

import requests
import json 

data={"client_id" : "a", "client_secret" : "thisissecret", "grant_type" : "clientcredentials", "scope" : "PublicApi"}
headers = {'content-type': 'application/json'}

url = 'http://MYURL/connect/token'
response = requests.post(url, json=data, verify=False, headers=headers)

Upvotes: 0

Related Questions