Last active
November 8, 2018 01:26
-
-
Save mosdevly/c0c49df33ced7e16903cb1e168c72547 to your computer and use it in GitHub Desktop.
Spotify Auth Snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
mosdevly
commented
Nov 8, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment