Plan
Premium
Country
United Kingdom
Device
Windows 10 Laptop
My Question or Issue
When trying to access users liked songs via the Spotify API, I can generate an access code, however when trying to use the access code to the
"https://api.spotify.com/v1/me/tracks" endpoint, I just get a 401 error.
I have attached my code here in case there is a mistake I'm not seeing.
Thanks!
import requests
import base64
import datetime
from urllib.parse import urlencode
client_id = 'CLIENT_ID'
client_secret = 'CLIENT_SECRET'
client_creds = f'{client_id}:{client_secret}'
client_creds_b64 = base64.b64encode(client_creds.encode())
token_url = 'https://accounts.spotify.com/api/token'
token_data = {
'grant_type':'client_credentials'
}
token_headers = {
'Authorization':f'Basic {client_creds_b64.decode()}',
'Content-Type':'application/x-www-form-urlencoded'
}
r = requests.post(token_url, data=token_data, headers=token_headers)
if r.status_code in range(200,299) :
token_response_data = r.json()
now = datetime.datetime.now()
access_token = token_response_data['access_token']
expires_in = token_response_data['expires_in']
expires = now + datetime.timedelta(seconds=expires_in)
did_expire = expires < now
headers = {
'Authorization':f'Bearer {access_token}'
}
endpoint = 'https://api.spotify.com/v1/me/tracks'
data = urlencode({'market':'UK', 'limit':10, 'offset':5})
lookup_url = f'{endpoint}?{data}'
r = requests.get(lookup_url, headers=headers)
You can't access user data and can't use scopes with client credentials. Use this instead:
token_data = {
'grant_type':'authorization_code'
}
Hey there you, Yeah, you! 😁 Welcome - we're glad you joined the Spotify Community! While you here, let's have a fun game…