Getting started with Authorisation Code Flow and Spotipy

I recently wrote a post on how we can use Client Credentials Flow with Spotipy to retrieve publicly available data. Here, I describe how to use Authorisation Code Flow which will enable you to do things like update or remove tracks from a given playlist.

The first thing to do, in your terminal or command prompt, is type these commands, replacing each string with your client ID and secret generated when the initial app was created, and the redirect URL specified in the set-up.

export SPOTIPY_CLIENT_ID='your_client_ID'
export SPOTIPY_CLIENT_SECRET='your_client_Secret'
export SPOTIPY_REDIRECT_URI='the redirect URL you set'

This will pass these arguments to Spotipy’s utility class.

You should now be in a position to use Authorisation Code Flow. The script below is the Authorisation Code Flow equivalent of the program outlined here.

import sys
import spotipy
import spotipy.util as util

if len(sys.argv) > 1:
    username = sys.argv[1]
    print "Usage: %s username" % (sys.argv[0],)

token = util.prompt_for_user_token(username, redirect_uri = 'http://localhost/')

if token:
    sp = spotipy.Spotify(auth=token)
    playlists = sp.user_playlists(username)
    while playlists:
        for i, playlist in enumerate(playlists['items']):
            print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['uri'],  playlist['name']))
        if playlists['next']:
            playlists =
            playlists = None

To run the script, in terminal or a command line, type:

python <path/to/file> your_username

This should automatically open a browser window (if it doesn’t, copy and paste the URL generated in the terminal) which will let you login, in the familiar environment we’re used to, generating a token granting you authorisation to run the script.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s