'Spotify API Authorization Code Flow with Python

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 wrong here?


Solution 1:[1]

By now, you probably have figure out what the problem was, but I am answering for future readers as well. When you encode the auth_header, you should encode it to bytes not ascii. The str.encode() does this by default, so you can call it without arguments. Your code changes to this:

auth_header = base64.urlsafe_b64encode((CLIENT_ID + ':' + CLIENT_SECRET).encode()).

Now you must have a working example.

Solution 2:[2]

You're missing the CLIENT_ID and CLIENT_SECRET set within the code if I'm not mistaken.

This means Spotify will return invalid access token, which results in you not being able to continue.

You can also use Spotipy library for Python to make things easier. https://spotipy.readthedocs.io/en/2.16.1/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 exch_cmmnt_memb
Solution 2 tomatoj