import requests
import base64
# Request an access token
def request_access_token():
AUTH_URL = 'https://accounts.spotify.com/api/token'
# POST
auth_response = requests.post(AUTH_URL, {
'grant_type': 'client_credentials',
'client_id': "<client ID>",
'client_secret': "<client Secret>",
})
# convert the response to JSON
auth_response_data = auth_response.json()
# save the access token
print(auth_response_data)
access_token = auth_response_data['access_token']
return access_token
# Check if the access token is valid
def check_access_token_validity(access_token):
headers = {
"Authorization": f"Bearer {access_token}"
}
response = requests.get("https://api.spotify.com/v1/me", headers=headers)
print(response)
if response.status_code == 200:
return True
else:
return False
# Run the code
access_token = request_access_token()
if access_token:
if check_access_token_validity(access_token):
print("Access token is valid.")
else:
print("Access token is not valid.")
else:
print("Could not request access token.")
I get a "access_token" but it doesn't work. It gives Error 401. I also got the same issue in javascript. I tried everything and I dont know what is wrong. Here's the output:
Which shows that I did recieve a token. But when I try to check it's validity, it is [Invalid 401]. I have also rotated my client secret and same issue. Both Client ID and Client Secret are correct.
As mentioned in the docs, your access token request is different
Try this
import requests
import base64
client_id = 'CLIENT_ID';
client_secret = 'CLIENT_SECRET';
response = requests.post(
'https://accounts.spotify.com/api/token',
data={'grant_type':'client_credentials'},
headers={'Authorization': 'Basic ' + base64.urlsafe_b64encode((CLIENT_ID + ':' + CLIENT_SECRET).encode())},
)