Spotify Refresh Token Python
Question:
I have a python program that returns whatever song I’m currently listening to. The Access Token I get from Spotify API only lasts an hour and I’m having trouble finding an easy way to implement a refresh token into my code.
SPOTIFY_GET_CURRENT_TRACK_URL = 'https://api.spotify.com/v1/me/player'
SPOTIFY_ACCESS_TOKEN = 'BQBQMLkkLb6az9TRv-PDXFFcm4KHrofc67H12Uzs3FXaPWHETy4ivnC-WGu2Jg5wlZ_yhggGypiO0Gnv_QkNGkefTuCjNR_Tzjw4pv2W9f_9_D7-LfD2W5KVPzh2DxMmf9TNPpSn200D_Xd4AD8F_MeJc-DIlA'
#Method to return the info for the currently playing track
def get_current_track():
response = requests.get(
SPOTIFY_GET_CURRENT_TRACK_URL,
headers = {
"Authorization": f"Bearer {SPOTIFY_ACCESS_TOKEN}"
}
)
resp_json = response.json()
track_id = resp_json['item']['id']
track_name = resp_json['item']['name']
artists = resp_json['item']['artists']
artists_name = ', '.join(
[artist['name'] for artist in artists]
)
link = resp_json['item']['external_urls']['spotify']
current_track_info = {
"id" : track_id,
"name" : track_name,
"artists" : artists_name,
"link" : link
}
return current_track_info
Answers:
How about using a class to keep the token and then request again if it’s stale? Something like this:
class SpotifyTracker:
TRACK_URL = 'https://api.spotify.com/v1/me/player'
def __init__(self):
self._token = self._set_token()
def _set_token(self):
# ... logic to set token
def _request_track_data(self):
return requests.get(
self.TRACK_URL,
headers={
"Authorization": f"Bearer {self._token}"
}
)
def get_current_track(self):
response = self._request_track_data()
if response.code == 401:
self._set_token()
response = self._request_track_data()
resp_json = response.json()
...
return current_track_info
This is a great youtube tutorial that answered all my questions
https://youtu.be/-FsFT6OwE1A
This code is assuming you already have an access token and just need to refresh it:
import base64
import requests
def refesh_the_token():
auth_client = client_id + ":" + client_secret
auth_encode = 'Basic ' + base64.b64encode(auth_client.encode()).decode()
headers = {
'Authorization': auth_encode,
}
data = {
'grant_type' : 'refresh_token',
'refresh_token' : refresh_token
}
response = requests.post('https://accounts.spotify.com/api/token', data=data, headers=headers) #sends request off to spotify
if(response.status_code == 200): #checks if request was valid
print(pgrm_signature + "The request to went through we got a status 200; Spotify token refreshed")
response_json = response.json()
new_expire = response_json['expires_in']
print(pgrm_signature + "the time left on new token is: "+ str(new_expire / 60) + "min") #says how long
return response_json["access_token"]
else:
print(pgrm_signature + "ERROR! The response we got was: "+ str(response))
I have a python program that returns whatever song I’m currently listening to. The Access Token I get from Spotify API only lasts an hour and I’m having trouble finding an easy way to implement a refresh token into my code.
SPOTIFY_GET_CURRENT_TRACK_URL = 'https://api.spotify.com/v1/me/player'
SPOTIFY_ACCESS_TOKEN = 'BQBQMLkkLb6az9TRv-PDXFFcm4KHrofc67H12Uzs3FXaPWHETy4ivnC-WGu2Jg5wlZ_yhggGypiO0Gnv_QkNGkefTuCjNR_Tzjw4pv2W9f_9_D7-LfD2W5KVPzh2DxMmf9TNPpSn200D_Xd4AD8F_MeJc-DIlA'
#Method to return the info for the currently playing track
def get_current_track():
response = requests.get(
SPOTIFY_GET_CURRENT_TRACK_URL,
headers = {
"Authorization": f"Bearer {SPOTIFY_ACCESS_TOKEN}"
}
)
resp_json = response.json()
track_id = resp_json['item']['id']
track_name = resp_json['item']['name']
artists = resp_json['item']['artists']
artists_name = ', '.join(
[artist['name'] for artist in artists]
)
link = resp_json['item']['external_urls']['spotify']
current_track_info = {
"id" : track_id,
"name" : track_name,
"artists" : artists_name,
"link" : link
}
return current_track_info
How about using a class to keep the token and then request again if it’s stale? Something like this:
class SpotifyTracker:
TRACK_URL = 'https://api.spotify.com/v1/me/player'
def __init__(self):
self._token = self._set_token()
def _set_token(self):
# ... logic to set token
def _request_track_data(self):
return requests.get(
self.TRACK_URL,
headers={
"Authorization": f"Bearer {self._token}"
}
)
def get_current_track(self):
response = self._request_track_data()
if response.code == 401:
self._set_token()
response = self._request_track_data()
resp_json = response.json()
...
return current_track_info
This is a great youtube tutorial that answered all my questions
https://youtu.be/-FsFT6OwE1A
This code is assuming you already have an access token and just need to refresh it:
import base64
import requests
def refesh_the_token():
auth_client = client_id + ":" + client_secret
auth_encode = 'Basic ' + base64.b64encode(auth_client.encode()).decode()
headers = {
'Authorization': auth_encode,
}
data = {
'grant_type' : 'refresh_token',
'refresh_token' : refresh_token
}
response = requests.post('https://accounts.spotify.com/api/token', data=data, headers=headers) #sends request off to spotify
if(response.status_code == 200): #checks if request was valid
print(pgrm_signature + "The request to went through we got a status 200; Spotify token refreshed")
response_json = response.json()
new_expire = response_json['expires_in']
print(pgrm_signature + "the time left on new token is: "+ str(new_expire / 60) + "min") #says how long
return response_json["access_token"]
else:
print(pgrm_signature + "ERROR! The response we got was: "+ str(response))