Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

401 error when accessing user liked/saved songs

401 error when accessing user liked/saved songs

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)
Reply
1 Reply

You can't access user data and can't use scopes with client credentials. Use this instead:

token_data = {

    'grant_type':'authorization_code'

}

 

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

Suggested posts