How to get all the tracks of a Spotify playlist

Viewed 193

I'm trying to get all the tracks from 2 playlists into a CSV file. However, in both playlists, even though I increase the offset parameter by 100 in each query, the first 100 songs of both playlists are returned. So the page is never changed. What could be the problem?

import spotipy, json, csv
from spotipy.oauth2 import SpotifyClientCredentials

client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)

sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

data_file = open('data.csv', 'w')
writer = csv.writer(data_file)
writer.writerow(['track_num', 'track_id', 'track_name', 'first_artist'] + ['liked'])

playlist_ids = [
    'xxxxxxxxxxxxxxxxxxxxxxx', # playlist 1
    'yyyyyyyyyyyyyyyyyyyyyyy' # playlist 2
]

for playlist_id in playlist_ids:
    offset_n = 0
    total = 100
    while offset_n < total:
        tracks_response = sp.playlist_tracks(playlist_id, offset=offset_n)
        tracks_json = json.dumps(tracks_response)
        tracks_data = json.loads(tracks_json)
        if offset_n == 0:
            total = tracks_data['tracks']['total']
        for track in tracks_data['tracks']['items']:
            track_id = track['track']['id']
            track_name = track['track']['name']
            first_artist = track['track']['artists'][0]['name']
            if playlist_id == playlist_ids[0]:
                writer.writerow([row_num, track_id, track_name, first_artist] + [1])
            else:
                writer.writerow([row_num, track_id, track_name, first_artist] + [0])
        offset_n += 100

data_file.close()
1 Answers

The playlist_tracks method returns a paginated result with details of the tracks of a playlist. So you need to iterate over all pages to get the full data.

You can use this example as a reference:

def get_all_tracks_from_playlist(playlist_id)
    tracks_response = sp.playlist_tracks(playlist_id)
    tracks = tracks_response["items"]
    while tracks_response["next"]:
        tracks_response = sp.next(tracks_response)
        tracks.extend(tracks_response["items"])

    return tracks

Regarding the ReadTimeout exception you have mentioned in the comments:

Spotify client accepts requests_timeout and retries as arguments, according to the documentation the default values are requests_timeout=5, and retries=3 You can extend them as you wish to decrease the chance you will get the ReadTimeout exception.

As a start you can double the request timeout to 10 seconds, and change the retries to 5:

sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager, requests_timeout=10, retries=5)
Related