pythonaccess-tokenbox-api

Box API get access_token through python


I'm getting authorization code through exactly this website on the readme page: https://app.box.com/api/oauth2/authorize?response_type=code&client_id=MY_CLIENT_ID&state=security_token%3DKnhMJatFipTAnM0nHlZA

And POST for access_token through Python, but receive invalid_request error. Same result as I try through postman. Attached my code and the error message, did I understand something wrong?

url = 'https://api.box.com/oauth2/token'
payload = {'grant_type':'authorization_code','code':auth_code,'client_id':'ID','client_secret':'SECRET'}
r = requests.post(url, data=json.dumps(payload))
json_r = r.json()
print json_r

Error message:

{
  "error": "invalid_request",
  "error_description": "Invalid grant_type parameter or parameter missing"
}

Solution

  • The problem is that you encode the POST payload as a JSON-string when the requests.post function's data parameter expects an ordinary dictionary. So just doing it like this should work:

    r = requests.post(url, data=payload)