Skip to content

Instantly share code, notes, and snippets.

@SamL98
Last active August 18, 2022 19:15
Show Gist options
  • Save SamL98/ff1448aa1f92bf671a549357449192e5 to your computer and use it in GitHub Desktop.
Save SamL98/ff1448aa1f92bf671a549357449192e5 to your computer and use it in GitHub Desktop.
Core of SPUtil Module
# Partial library I wrote a while ago that is a wrapper for spotipy.
# I'm not particularly proud of the code so I only posted what's needed to understand
# my get_recents.py gist
import os
import spotipy.util as util
base_url = 'https://api.spotify.com/v1/'
auth_header = None
def login(base_url):
client_id = os.environ['SPOTIPY_CLIENT_ID']
client_secret = os.environ['SPOTIPY_CLIENT_SECRET']
redirect_uri = 'http://localhost:8080/callback'
# After being redirected (to a nonexistent localhost page), copy and paste the url containing the auth code
# into the terminal and spotipy will parse the code and get the resulting OAuth token.
token = util.prompt_for_user_token(
'<redacted>',
'user-read-recently-played user-library-read \
user-modify-playback-state playlist-modify-public',
client_id=client_id, client_secret=client_secret,
redirect_uri=redirect_uri)
assert token, 'Token is nil'
auth_header = {'Authorization': 'Bearer ' + token}
return auth_header
def format_track(json, include_duration=False):
def assert_key(key, msg, js=None):
if js is None: js = json
assert key in js, msg
return js[key]
title = assert_key('name', 'No name key in JSON')
artists = assert_key('artists', 'No artists key in JSON')
assert len(artists) > 0, 'Artists length 0'
artist = artists[0]
name = assert_key('name', 'No name for artist', js=artist)
id = assert_key('id', 'No id for track')
d = { 'title': '\'' + title + '\'',
'artist': '\'' + name + '\'',
'id': id }
if include_duration:
duration = assert_key('duration_ms', 'No duration for track')
d['duration'] = duration
return d
if auth_header is None:
auth_header = login(base_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment