Created
October 14, 2018 17:04
-
-
Save kiwidamien/f1f310f81c48c57a531b8464b877bf9c to your computer and use it in GitHub Desktop.
Showing how to use OAuth2 using Spotify as an example
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 | |
import pprint | |
# 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' | |
# This is the spotify OAuth 2.0 Authorization workflow | |
# Original document here: | |
# https://developer.spotify.com/documentation/web-api/quick-start/ | |
def base64_encode_string(s): | |
return base64.b64encode(s.encode()).decode() | |
def get_base64_auth(client_id=CLIENTID, client_secret=CLIENTSECRET): | |
""" | |
Takes the client_id and client_secret, and returns the base64 encoded string | |
""" | |
combined_string = client_id + ':' + client_secret | |
return base64_encode_string(combined_string) | |
def get_token(client_id=CLIENTID, client_secret=CLIENTSECRET, verbose=False): | |
auth_url = 'https://accounts.spotify.com/api/token' | |
headers = { | |
'Authorization': 'Basic ' + get_base64_auth(), | |
'Content-Type': 'application/x-www-form-urlencoded', | |
} | |
params = { | |
'grant_type': 'client_credentials', | |
} | |
r = requests.post(auth_url, headers=headers, params=params) | |
if verbose: | |
print("This is the JSON object returned from {auth_url}".format(auth_url=auth_url)) | |
pprint.pprint(r.json()) | |
return r.json()['access_token'] | |
ENQUIRE_API = 'https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V' | |
TOKEN = get_token(verbose=True) | |
headers = { | |
'Authorization': 'Bearer ' + TOKEN | |
} | |
r = requests.get(ENQUIRE_API, headers=headers) | |
pprint.pprint(r.json()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment