I'm building a simple application to learn Python 3 and Flask. The goal is to consume data from the Spotify API and for that I need to authenticate using OAuth 2.0.
I'm able to provide my credentials to Spotify Accounts however during the callback the following error is happening:
File "app.py", line 59, in callback
access_token = response_data["access_token"]
KeyError: 'access_token'
Code sample:
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)
response_data = json.loads(post_request.text)
access_token = response_data["access_token"]
token_type = response_data["token_type"]
expires_in = response_data["expires_in"]
refresh_token = response_data["refresh_token"]
This is the request response sample from the API documentation:
{
"access_token": "NgCXRK...MzYjw",
"token_type": "Bearer",
"scope": "user-read-private user-read-email",
"expires_in": 3600,
"refresh_token": "NgAagA...Um_SHo"
}
I'm quite lost. Not sure if it's something related to the API response content or how the application is parsing it with json.loads(post_request.text).
EDIT: After getting the HTTP status code I'm able to have an idea of the problem:
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.spotify.com/api/token
However I still can't figure it out what is wrong with my request:
authentication_token = request.args['code']
code_payload = {
"grant_type": "authorization_code",
"code": str(authentication_token),
"redirect_uri": REDIRECT_URI
}
encoded_oauth2_tokens = base64.b64encode('{}:{}'.format(CLIENT_ID, CLIENT_SECRET).encode())
headers = {"Authorization": "Basic {}".format(encoded_oauth2_tokens)}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)
post_request.raise_for_status()