Help Wizard

Step 1

NEXT STEP

Who Me Too'd this topic

Unable to get access token using authorization code flow

Plan

Free

Country

USA

Device

Macbook Pro late 2017

Operating System

MacOS

 

My Question or Issue

 I am trying to do the authorization code flow using Spotify's API to ultimately add songs to a playlist. I am building this from scratch, and not using any libraries such as Spotipy.

I am able to successfully hit the authorize endpoint, but I am having some issues with the token endpoint. Here is the code I have so far:

 

# URLS
AUTH_URL = 'https://accounts.spotify.com/authorize'
TOKEN_URL = 'https://accounts.spotify.com/api/token'
BASE_URL = 'https://api.spotify.com/v1/'


# Make a request to the /authorize endpoint to get an authorization code
auth_code = requests.get(AUTH_URL, {
    'client_id': CLIENT_ID,
    'response_type': 'code',
    'redirect_uri': 'https://open.spotify.com/collection/playlists',
    'scope': 'playlist-modify-private',
})
print(auth_code)

auth_header = base64.urlsafe_b64encode((CLIENT_ID + ':' + CLIENT_SECRET).encode('ascii'))
headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Basic %s' % auth_header.decode('ascii')
}

payload = {
    'grant_type': 'authorization_code',
    'code': auth_code,
    'redirect_uri': 'https://open.spotify.com/collection/playlists',
    #'client_id': CLIENT_ID,
    #'client_secret': CLIENT_SECRET,
}


# Make a request to the /token endpoint to get an access token
access_token_request = requests.post(url=TOKEN_URL, data=payload, headers=headers)

# convert the response to JSON
access_token_response_data = access_token_request.json()

print(access_token_response_data)

# save the access token
access_token = access_token_response_data['access_token']

When I run my script, I get this output in Terminal:

{'error': 'invalid_grant', 'error_description': 'Invalid authorization code'}
Traceback (most recent call last):
  File "auth.py", line 48, in <module>
    access_token = access_token_response_data['access_token']
KeyError: 'access_token'```

Can anyone explain to me what I might be doing incorrectly?

Who Me Too'd this topic