Abhipsit Srivastava
Abhipsit Srivastava

Reputation: 31

Is there a method to retrieve all tracks from a playlist using Spotipy?

I'm trying to extract all songs from one of my playlists in Spotify. Using the spotipy package in Python to help accomplish this. Below is the current code I have, which only gets 100 tracks. I tried poking around the internet for solutions but nothing appeared to work. Below is the code that I have so far.

#Import Library
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import spotipy
from matplotlib import style
from spotipy import util
from spotipy.oauth2 import SpotifyClientCredentials 

#Set up Connection 
client_id = 'id' #Need to create developer profile
client_secret = 'secret'
username = 'username' #Store username
scope = 'user-library-read playlist-modify-public playlist-read-private'
redirect_uri='uri'
client_credentials_manager = SpotifyClientCredentials(client_id=client_id, 
client_secret=client_secret)#Create manager for ease
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
token = util.prompt_for_user_token(username, scope, client_id, 
client_secret, redirect_uri)

if token:
 sp = spotipy.Spotify(auth=token)
else:
 print("Can't get token for", username)

#Connect to the best playlist, like ever 
playlist_id = 'playlist'
playlist = sp.user_playlist(username,playlist_id)

#Extract list of songs/tracks
tracks = playlist["tracks"];
songs = tracks["items"];

track_ids = []
track_names = []

for i in range(0, len(songs)):
 if songs[i]['track']['id'] != None: # Removes  local tracks, if any
    track_ids.append(songs[i]['track']['id'])
    track_names.append(songs[i]['track']['name'])

Upvotes: 3

Views: 4235

Answers (1)

Rach Sharp
Rach Sharp

Reputation: 2454

You can use offset to collect the results from multiple calls. This function returns a list of track objects.

def user_playlist_tracks_full(spotify_connection, user, playlist_id=None, fields=None, market=None):
    """ Get full details of the tracks of a playlist owned by a user.
        https://developer.spotify.com/documentation/web-api/reference/playlists/get-playlists-tracks/

        Parameters:
            - user - the id of the user
            - playlist_id - the id of the playlist
            - fields - which fields to return
            - market - an ISO 3166-1 alpha-2 country code.
    """

    # first run through also retrieves total no of songs in library
    response = spotify_connection.user_playlist_tracks(user, playlist_id, fields=fields, limit=100, market=market)
    results = response["items"]

    # subsequently runs until it hits the user-defined limit or has read all songs in the library
    while len(results) < response["total"]:
        response = spotify_connection.user_playlist_tracks(
            user, playlist_id, fields=fields, limit=100, offset=len(results), market=market
        )
        results.extend(response["items"])

Upvotes: 2

Related Questions