import base64 import requests class CredentialError(Exception): pass class Spotify: def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret self.access_token = "" self.token_type = "" self.expiration_time = 0 self.scope = "" def request_token(self): b64_encoded = base64.b64encode( "{}:{}".format(self.client_id, self.client_secret).encode() ) headers = {"Authorization": "Basic {}".format(b64_encoded.decode("ascii"))} data = {"grant_type": "client_credentials"} post = requests.post( "https://accounts.spotify.com/api/token", headers=headers, data=data ) status_code = post.status_code if status_code == 401: raise CredentialError("Provided credentials are not correct.") if status_code == 200: self.access_token = post.json()["access_token"] self.token_type = post.json()["token_type"] self.expiration_time = post.json()["expires_in"] self.scope = post.json()["scope"] def search(self, search_term, types): if not self.access_token: self.request_token() encoded_search_term = urllib.parse.quote(search_term) full_url = "https://api.spotify.com/v1/search?q={}&type={}".format( encoded_search_term, ",".join(types) ) get = requests.get( full_url, headers={"Authorization": "Bearer " + self.access_token} ) results = get.json() return results