After playing around with exportify, I decided to find out how the Spotify API works. Of course, a Python module already exists called Spotipy that helps you connect to the Web API.

This can easily be installed with pip install spotipy and has good documentation here

I wanted to see if I could get a list of songs in my followed playlists using the Spotify Web API and Spotipy. The first thing to do was to create an app on the Spotify developers Dashboard. After creating your app you can get the Client ID and Client Secret which are needed to authenticate with the Spotify API. You will also need to click on Edit Settings for your app to add a Redirect URI. This URI doesn't need to actually exist so you can just use https://localhost/ if you don't care about the results of user logins. Whatever URL you use, you need to use the same one in the Spotipy OAuth call.

You will also need to decide on what Authorization Scopes your app will need. Since I won't be modifying anything and just want to read my playlists I only need the playlist-read-collaborative and playlist-read-private scopes. This will allow me to read all of my own playlists, even the private ones. You can actually read any users playlist if it is public without specifying any scopes.

To get a list of playlists for a specified user, and to get a list of the songs in that playlist, the following Python script can be used

playlist-test.py

#!/usr/bin/env python3

import sys
import os
import spotipy
from spotipy.oauth2 import SpotifyOAuth

SPOTIPY_CLIENT_ID='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
SPOTIPY_CLIENT_SECRET='YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY'
SPOTIPY_REDIRECT_URI='https://localhost/'

if len(sys.argv) == 1:
    print("Usage: " + sys.argv[0] + " <username> [playlist name]")
    sys.exit()

if(len(sys.argv) >= 2):
    user = sys.argv[1]

if(len(sys.argv) >= 3):
    playlist_name = sys.argv[2]
else:
    playlist_name = None

playlist_id = None

# request full read only access to your own library and playlists
scope = "user-library-read playlist-read-collaborative playlist-read-private"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
                                               client_secret=SPOTIPY_CLIENT_SECRET,
                                               redirect_uri=SPOTIPY_REDIRECT_URI, scope=scope))

# get the list of playlists by the given user
results = sp.user_playlists(user)

# if a playlist name was given too, try and get its ID
# otherwise just print a list of playlists and how many songs
for i in results['items']:
    if(playlist_name):
        if(i['name'] == playlist_name):
            playlist_id = i['id']
    else:
        print(i['name'] + " - " + str(i['tracks']['total']) + " songs")
if(len(sys.argv) == 2):
        sys.exit(0)

print("ID: " + playlist_id)
if(playlist_id == None):
    sys.exit(1)

# if the playlist ID was found get the list of songs in it
items = sp.playlist_items(playlist_id)
songs = list()

# extract the song info and the data it was added and store 
# them in a list
for item in items['items']:
    # sometimes track doesn't exist, maybe country restrictions?
    if(item['track'] == None):
        continue

    if(item['track']['artists']):
        artist = item['track']['artists'][0]['name']

    if(item['track']['album']):
        album = item['track']['album']['name']

    song_name = item['track']['name']
    added_date = item['added_at']

    songs.append([artist, album, song_name, added_date])

for song in songs:
    print(song)

Obviously enter your own Client ID and Client Secret, and also your Redirect URI if you didn't use localhost. You can then run the script with a username as the argument to get a list of playlists for that user. The first time you run it, Spotipy should open up an authentication request page in your default web browser where you can login and allow access to your playlists and whatever else you specified in the scopes.

Once you accept the request you will be sent to your redirect URI which will probably display an error if you are using localhost, but the thing you need is the full URL from the address bar. You then paste this URL into the terminal that you ran the Python script from and Spotipy will be authenticated.

Running the script as ./playlist-test.py username will show you a list of all the playlists that user has available to you. Username can be your own user or any other spotify user. Once you get the list of playlists you can run the command again, this time specifying a playlist name too like ./playlist-test.py username 'playlist name' and you will get a list of the songs and their artist and album. Remember to chmod +x playlist-test.py if you want to run it directly like that.

There is actually a lot more information returned by the playlist_items function, such as links to the artists pages and album art pictures. You can just print(items) to get the full list of data and see what is in there.

Previous Post Next Post