I'm trying to obtain the currently played song using the Spotify API. I read the documentation and it looks like you first have to authorize. As you can see, I'm opening the authorize page in the browser, and once I successfully authorize, I'm sending a POST request to the endpoint in order to obtain the access token which I later pass to another endpoint using a GET request. However, I'm getting Invalid username in return. What have I done wrong?
import requests
import webbrowser
import urllib
SPOTIFY_CLIENT_ID = 'spam'
SPOTIFY_CLIENT_SECRET = 'eggs'
def get_currently_played_song():
webbrowser.open(
'https://accounts.spotify.com/authorize?' +
urllib.parse.urlencode(
{
'client_id': SPOTIFY_CLIENT_ID,
'response_type': 'code',
'scope': 'user-read-currently-playing',
'redirect_uri': 'https://www.spotify.com/us/'
}
)
)
response = requests.post(
'https://accounts.spotify.com/api/token',
data={
'grant_type': 'client_credentials',
},
auth=(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)
)
access_token = response.json()['access_token']
current_song = requests.get(
'https://api.spotify.com/v1/me/player/currently-playing',
headers={
'Authorization': f'Bearer {access_token}',
}
)
print(current_song.json())
if __name__ == '__main__':
get_currently_played_song()
...prints:
{'error': {'status': 404, 'message': 'Invalid username'}}