Skip to content

Instantly share code, notes, and snippets.

@kiwidamien
Created October 14, 2018 17:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiwidamien/09bb2d4a55c9fb3b265697ba12c1ff8e to your computer and use it in GitHub Desktop.
Save kiwidamien/09bb2d4a55c9fb3b265697ba12c1ff8e to your computer and use it in GitHub Desktop.
import requests
import base64
def base64_encode_string(s):
return base64.b64encode(s.encode()).decode()
class MyAPI:
def __init__(self, token_url, client_id, client_secret):
self.token_url = token_url
self.token = None
self.client_id = client_id
self.client_secret = client_secret
def get_token(self):
headers = {
'Authorization': 'Basic ' +
base64_encode_string(self.client_id + ':' + self.client_secret),
'Content-Type': 'application/x-www-form-urlencoded',
}
params = {
'grant_type': 'client_credentials',
}
r = requests.post(self.token_url, headers=headers, params=params)
self.token = r.json()['access_token']
return self.token
def endpoint(self, url):
if self.token is None:
self.get_token()
headers = {'Authorization': 'Bearer ' + self.token}
r = requests.get(url, headers=headers)
if r.status_code == 401:
# status code timed out, refresh token
self.token = None
return self.endpoint(url)
return r.json()
if __name__ == '__main__':
# You need to register an "app" on Spotify and
# go to your dashboard at
# https://developer.spotify.com/dashboard/applications
# to get the client id and client seceret
CLIENTID = 'your_client_id'
CLIENTSECRET = 'your_client_secret'
SpotifyAPI = MyAPI('https://accounts.spotify.com/api/token', CLIENTID, CLIENTSECRET)
print(SpotifyAPI.endpoint('https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment