Skip to content

Instantly share code, notes, and snippets.

@ndamulelonemakh
Last active October 14, 2020 07:11
Show Gist options
  • Select an option

  • Save ndamulelonemakh/250f3514c7e2f81e11c1a02f2c8653ce to your computer and use it in GitHub Desktop.

Select an option

Save ndamulelonemakh/250f3514c7e2f81e11c1a02f2c8653ce to your computer and use it in GitHub Desktop.
Test the Spotify Web API in a flask application
import os
import uuid
import webbrowser
import urllib.parse as urllib
# You need to install these modules using pip
import flask
import requests
__author__ = '@NdamuleloNemakh'
__vesion__ = '0.0.1'
__python_version = '3.8.6'
HOST_IP_ADDRESS = '127.0.0.1'
HOST_PORT = 9000
# Create a flask application
app = flask.Flask('YOUR_APP_NAME')
# Create a default route
@app.route('/')
def index():
return 'It works!'
def _get_access_token(authorization_code: str):
spotify__request_access_token_url = 'https://accounts.spotify.com/api/token/?'
body = {'grant_type': 'authorization_code',
'code': authorization_code,
'client_id': os.getenv('CLIENT_ID'),
'client_secret': os.getenv('CLIENT_SECRET'),
'redirect_uri': os.getenv('REDIRECT_URI')
}
response: requests.Response = requests.post(spotify__request_access_token_url, data=body)
if response.status_code == 200:
return response.json()
raise Exception(f'Failed to obtain Access token.Response: {response.text}')
"""Callback route
$ This is the url that the user will be REDIRECTED to after the spotify login screen
$ NB: The URL must match the REDIRECT_URI setting on your spotify developer dashboard e.g. http://127.0.0.1:9000
$ Spotify will send bac a code which can be used to request an access token via a 'back-channel'
"""
@app.route('/callback')
def callback():
code = flask.request.args.get('code')
credentials = _get_access_token(authorization_code=code)
os.environ['token'] = credentials['access_token']
return f"Authentication successful. Access token: {credentials['access_token']}"
@app.route('/top-tracks')
def top_tracks():
root_url = 'https://api.spotify.com/v1/me/top/tracks/?'
# NB: Add the access token to the request header
headers = {
'Authorization': f'Bearer {os.getenv("token")}'
}
request_params = {
'time_range': 'medium_term',
'limit': 20,
'offset': 0
}
# NOTE: This requires the scope 'user-top-read'
full_url = root_url + urllib.urlencode(request_params)
response = requests.get(full_url,
headers=headers,
params=request_params)
if response.status_code == 200:
return response.json()
print(response.status_code)
raise Exception(f'API call to {full_url} failed. {response.text}')
"""
$ This will initiate the process of obtaing an access token from the Spotify Oauth server
$ Make sure to specify the required SCOPES for the services you intend to use
$ Reference: https://developer.spotify.com/documentation/general/guides/authorization-guide/authorization-code-flow
"""
@app.route('/login')
def login():
authentication_request_params = {
'response_type': 'code',
'client_id': os.getenv('CLIENT_ID'),
'redirect_uri': os.getenv('REDIRECT_URI'),
'scope': 'user-read-email user-read-private user-top-read',
'state': str(uuid.uuid4()),
'show_dialog': 'true'
}
auth_url = 'https://accounts.spotify.com/authorize/?' + urllib.urlencode(authentication_request_params)
webbrowser.open(auth_url)
return 'Redirect to Spotify Login Page...'
# Usage:
# 1. Add your client configuration environment variables(CLIENT_ID. CLIENT_SECRET and REDIRECT_URI)
# e.g. export CLIENT_SECRET='your secret' [On windows use set CLIENT_SECRET='your-secret']
# 2. Get the access token by navigating to: http://127.0.0.1:9000/login
# 3. Once the authentication process is done,try http://127.0.0.1:9000/top-tracks
# This should return a json object with the list of your top traks
if __name__ == '__main__':
app.run(HOST_IP_ADDRESS, HOST_PORT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment