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.

Authorising Your First Spotipy App with Client Credentials Flow

A playlist I have on Spotify has collected a good number of followers over the years, which has attracted feature requests from artists, their managements and record labels. Keeping a playlist active so your follower count keeps growing can be a bit annoying, but Spotify’s Web API can make the automation of this easy. It also lets you do lots of other interesting things too, but getting started, especially for new beginners can be a bit daunting.

Here’s how you can get started quickly using the “Client Credentials Flow” (more on that later).

Using Spotipy, a python library that lets you interact with Spotify’s Web API, we can quickly write a program that will display a given user’s public playlists.

To use Spotipy (after installing it, instructions on how in the link above) you’ll need to make an app on and get your client ID and client secret. We will need these for authorisation. Spotify updated their API earlier this year to bring it inline with other web APIs meaning you need to have authorisation to use it. To get publicly available data from Spotify, “Client Credentials Flow” authorisation will suffice, if you want a user’s private information, you will need to use “Authorisation Code Flow” which will prompt that user to log-in. More info on this here.

The code to retrieve a given user’s public playlists can be seen here:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

client_credentials_manager = SpotifyClientCredentials(client_id='Your_Client_ID', client_secret='Your_Client_Secret')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

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

By passing your client_ID and client_Secret as arguments (keep them as strings) in SpotifyClientCredential() you utilise Client Credentials Flow, and by replacing playlists = sp.user_playlists('Username') ‘username’ with your username of interest, running the program will, hopefully, list that user’s public playlists.

If you want to know how to use Authorisation Code Flow, let me know and I will write a separate post. Good luck!

So you want to learn Python? Insights from a newbie

Too long; didn’t read:

  • Get a Raspberry Pi
  • Sign-up to codecademy (free)
  • Have a project and end-goal in mind
  • Have patience
  • Get a nice integrated development environment (IDE) AKA a program that makes your code readable and nice
  • Have a crack!

Programming has been my escape for the past year and a half. Seriously. I have pretty much done nothing but. I absolutely love it. I love the feeling of getting something to work the way I want it to, having tinkered, edited and debugged until my head hurts. It’s a weird feeling. You know that cliché saying “It’s not the destination that counts, it’s the journey”? I think that holds very true for coding. It’s a journey, man.

I dipped into HTML and CSS way back when, but that introductory front-end stuff just wasn’t doing it for me and I gave up pursuing it. It was the moment when I saw a friend’s array of Raspberry Pis that made me want to dive back in; all of the components I didn’t understand and wires and flashing LEDs and motors and cogs and “AHHHHH!”. I felt like a 3 year old child on Christmas morning and I wanted a slice of that pie (pun definitely intended).

Anyway – to cut a long story short – I bought a Raspberry Pi. It wasn’t a hard choice given how unbelievably cheap they are. I mean… £4?! Four British pound sterling. I’ve bought beers more expensive than that.

“What is a Raspberry Pi?” I hear you ask. A Raspberry Pi (RPi) is a delicious little computer. Just like whatever it is you’re using to read this. Only this one bridges the world of software and hardware so well that it becomes a seamless and inviting portal. You can pretty much do anything you can think of with an RPi. Home automation? No problem. TweetBots? Easy, son.

So that’s how I got started with programming. I had a project in mind, and I wanted something that’ll help me get there. I think that’s the first step in your programming journey.

Have a project in mind…

The reason I say this is because it makes the learning experience less abstract. There’s tonnes of tutorials and resources available online that’ll teach you the syntax and walk you through basic programming projects that’ll add numbers or capitalise letters in a command line environment. But that quickly gets boring. Having a project in mind will keep your brain ticking through those tutorials (I recommend this one very highly), you’ll start thinking of ways you can apply the knowledge you acquire to the project you want to work on.

Have patience

I think patience is a requirement for most things in life but MY GOD is it a requirement of programming. Especially when you’re learning. Everything will look foreign, bold red errors will scream at you “SYNTAX ERROR, DO YOUR WRITING BETTER”, nothing will work and you will want to give up. By all means, give up… for 1 or 2 days, recalibrate and take stock, then return. Always return and keep doing so. One day it’ll all just start clicking, you’ll be able to problem solve purely in python and you’ll genuinely start thinking in a different way.

Download a nice IDE

If you do wind up buying a Raspberry Pi, you’ll probably spend a lot of time editing code in a console/command terminal. Terminals are handy for many a reason but coding here can be annoying. So is coding with TextEdit and Notepad. Download PyCharm and get cracking with that. It’s free and it’ll make your code look so much prettier. The whole debugging process (which you’ll come to get to know very well) will get a lot quicker and easier too.

Steal, copy and annotate

If there’s anything that truly stands out about the Raspberry Pi is its community. There are endless YouTube how-tos, forum posts and code in GitHub repositories. Don’t be afraid to copy and paste that stuff, guys and girls! Tinker with it and make it your own, try and understand it, annotate your work and share it with the world! We’re in this together.


And finally, just keep going. If you can’t think of anything useful to build, build something useless, just build anything. Write your own story, be the next big thing, don’t worry about any of the other teams in your league, just win your own games and everything will take care of itself.

To finish, I’ll leave you with one of the most inspiring things I’ve heard from my favourite film-maker, Casey Neistat (which I’m probably about to badly paraphrase):

“There’s two things in life every person needs to ask themselves and figure out: 1. What do I like to do the most? and 2. How do I get paid doing that?”

Could coding be your ‘thing’?