Nov 202014
 

So you use Spotify and want a list of all of your playlists so you can come up with your #AOTY (album of the year). I’m sure there are other ways of doing this, but my rudimentary google searches produced no results, so here goes…

Requirements:

  • Spotify account
  • python
  • internets

First, sign up as a Spotify developer and create an application, here:

https://developer.spotify.com/my-applications/

Once you’ve created an application, make note of the Client ID and Client Secret, and add a new Redirect URIs to some working website.

Make sure to hit SAVE! If you don’t, this won’t work!!!

Now onto the code part…

First we need to put our Client ID Client Secret and Redirect URI into environment variables to be read later:

$ export SPOTIPY_CLIENT_ID='your-client-id-here'
$ export SPOTIPY_CLIENT_SECRET='your-client-secret-here'
$ export SPOTIPY_REDIRECT_URI='http://samsandberg.com'

Now we need an access token – here’s Spotify’s full formal auth guide:

https://developer.spotify.com/web-api/authorization-guide/

but for this exercise we’ll be using Spotipy (docs)

Install spotipy:

$ pip install spotipy

Next we need to determine our scope. Here’s a list of the available scopes:

https://developer.spotify.com/web-api/using-scopes/

For this exercise, we’ll be using playlist-read-private.

Now let’s use this to get our scope. My username is loisaidasam, so that’s the username you’ll see me use throughout this post:

>>> import spotipy.util as util
>>> util.prompt_for_user_token('loisaidasam', scope='user-library-read')

This should open a browser window and trigger you to authenticate against your newly made application. When you say yes, it’ll redirect you to your redirect uri, which you copy and paste back here:

Enter the URL you were redirected to: 

The next string it gives you is your token. Copy and paste that into a variable called token

Now, for getting your playlists…

Here’s the Spotify documentation describing how to read a user’s playlists:

https://developer.spotify.com/web-api/get-list-users-playlists/

but for this exercise we’ll be using Spotipy’s user_playlists() method:

We have to use limit/offset to get all of the results, so try this code:

>>> import spotipy
>>> s = spotipy.Spotify(token)
>>> offset = 0
>>> while True:
>>>     playlists = s.user_playlists('loisaidasam', offset=offset, limit=50)
>>>     if not playlists['items']:
>>>         break
>>>     for item in playlists['items']:
>>>         print item['name']
>>>     offset += len(playlists['items'])

Running this should print out all of your playlist names one by one.

Voila!