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?
2 Answers 2
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-urlencodedinstead ofjson. To do so, use thedataparameter ofrequest.post()instead ofjson - The
grant_typevalue must beclient_credentialsinstead ofclientcredentials
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())
answered Jun 6, 2018 at 8:26
Guillaume
6,1293 gold badges28 silver badges48 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
jack
Traceback (most recent call last): File "import.py", line 13, in <module> if response.is_ok: AttributeError: 'Response' object has no attribute 'is_ok'
Guillaume
typo, fixed now
jack
Awesome! it works. How do I access the info inside the response.json?
Guillaume
response.json() returns a standard Python dict (which is the result of parsing the JSON response), so you can read it just like a dict (e.g: to get the access token: at = response.json()['access_token'])jack
BTW - say respond.ok is not True. What try catch I should use here? What exception will it raise?
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)
answered Jun 6, 2018 at 7:48
ScottMcC
4,5201 gold badge32 silver badges39 bronze badges
2 Comments
Guillaume
requests will take care of that for you when you use json={"your":"data"} parameter to requests.post()ScottMcC
Didn't know that. From: docs.python-requests.org/en/master/user/quickstart
Using the json parameter in the request will change the Content-Type in the header to application/json.lang-py
json=datatojson=json.dumps(data)but callimport jsonfirst.