Skip to content

Instantly share code, notes, and snippets.

@mosdevly
Last active November 8, 2018 01:26
Show Gist options
  • Save mosdevly/c0c49df33ced7e16903cb1e168c72547 to your computer and use it in GitHub Desktop.
Save mosdevly/c0c49df33ced7e16903cb1e168c72547 to your computer and use it in GitHub Desktop.
Spotify Auth Snippet
import requests
import base64
# STEP 1: Get authorization token
SPOTIFY_AUTH_URL = 'https://accounts.spotify.com/api/token'
SPOTIFY_CLIENT_ID = 'your_client_id'
SPOTIFY_CLIENT_SECRET = 'your_client_secret'
client_string = f"{SPOTIFY_CLIENT_ID}:{SPOTIFY_CLIENT_SECRET}"
credentials = base64.b64encode(client_string.encode('ascii'))
def get_spotify_access_tokens():
headers = {'Authorization': ("Basic %s" % credentials.decode('ascii'))}
grant = {'grant_type': 'client_credentials'}
try:
response = requests.post(SPOTIFY_AUTH_URL, data=grant, headers=headers)
except:
# Some error with *your* request, not Spotify
current_app.logger.error("Spotify client failed.")
raise
else:
results = response.json()
return results
# STEP 2: Use access token to make requests to the API
def spotify_search(query, category):
"""
Search spotify
The API requires that a query and its type be sent. For example:
>>> 'q=queen&type=artist'
:params query: A query string which includes q and type
:params category: String containing the search type such as artist or track
"""
search_url = 'https://api.spotify.com/v1'
results = get_spotify_access_tokens()
headers = {'Authorization': f"Bearer {results['access_token']}"}
url_query = f"{search_url}/search?q={query}type={category}"
response = requests.get(url_query, headers=headers)
return response
@mosdevly
Copy link
Author

mosdevly commented Nov 8, 2018

# This could be stored in a session since its encrypted
spotify_token_data = {
    'access_token': 'lllll',
    'expiry': datetime.datetime.now() - old_expiry
}

if spotify_token_data.get('expiry') < 60:
    # make new auth request and get fresh token.
else:
    # continue with the search query

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment