[GH-ISSUE #246] How do I get every track of a playlist? #129

Closed
opened 2026-02-27 23:20:58 +03:00 by kerem · 7 comments
Owner

Originally created by @Kurchunk on GitHub (Jan 17, 2018).
Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/246

There are no code samples for this action, and I tried using an example for writing track names to a text file, but I noticed I am sometimes missing tracks if the playlist is over 100 tracks.

i.e. one playlist said the total was 106 tracks, but I only returned 100. But, I was able to get one playlist of over 800 tracks.

Originally created by @Kurchunk on GitHub (Jan 17, 2018). Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/246 There are no code samples for this action, and I tried using an example for writing track names to a text file, but I noticed I am sometimes missing tracks if the playlist is over 100 tracks. i.e. one playlist said the total was 106 tracks, but I only returned 100. But, I was able to get one playlist of over 800 tracks.
kerem closed this issue 2026-02-27 23:20:58 +03:00
Author
Owner

@ritiek commented on GitHub (Jan 18, 2018):

Not sure about your code but I've been using this for a long time and has been working fine for me so far:

import spotipy
import spotipy.oauth2 as oauth2

def generate_token():
    """ Generate the token. Please respect these credentials :) """
    credentials = oauth2.SpotifyClientCredentials(
        client_id=client_id,
        client_secret=client_secret)
    token = credentials.get_access_token()
    return token


def write_tracks(text_file, tracks):
    with open(text_file, 'a') as file_out:
        while True:
            for item in tracks['items']:
                if 'track' in item:
                    track = item['track']
                else:
                    track = item
                try:
                    track_url = track['external_urls']['spotify']
                    file_out.write(track_url + '\n')
                except KeyError:
                    print(u'Skipping track {0} by {1} (local only?)'.format(
                            track['name'], track['artists'][0]['name']))
            # 1 page = 50 results
            # check if there are more pages
            if tracks['next']:
                tracks = spotify.next(tracks)
            else:
                break


def write_playlist(username, playlist_id):
    results = spotify.user_playlist(username, playlist_id,
                                    fields='tracks,next,name')
    text_file = u'{0}.txt'.format(results['name'], ok='-_()[]{}')
    print(u'Writing {0} tracks to {1}'.format(
            results['tracks']['total'], text_file))
    tracks = results['tracks']
    write_tracks(text_file, tracks)


token = generate_token()
spotify = spotipy.Spotify(auth=token)

# example playlist
write_playlist('doldher', '0B4jhlB6QUGHzY8i3rEwTt')
<!-- gh-comment-id:358546616 --> @ritiek commented on GitHub (Jan 18, 2018): Not sure about your code but I've been using this for a long time and has been working fine for me so far: <details> ```python import spotipy import spotipy.oauth2 as oauth2 def generate_token(): """ Generate the token. Please respect these credentials :) """ credentials = oauth2.SpotifyClientCredentials( client_id=client_id, client_secret=client_secret) token = credentials.get_access_token() return token def write_tracks(text_file, tracks): with open(text_file, 'a') as file_out: while True: for item in tracks['items']: if 'track' in item: track = item['track'] else: track = item try: track_url = track['external_urls']['spotify'] file_out.write(track_url + '\n') except KeyError: print(u'Skipping track {0} by {1} (local only?)'.format( track['name'], track['artists'][0]['name'])) # 1 page = 50 results # check if there are more pages if tracks['next']: tracks = spotify.next(tracks) else: break def write_playlist(username, playlist_id): results = spotify.user_playlist(username, playlist_id, fields='tracks,next,name') text_file = u'{0}.txt'.format(results['name'], ok='-_()[]{}') print(u'Writing {0} tracks to {1}'.format( results['tracks']['total'], text_file)) tracks = results['tracks'] write_tracks(text_file, tracks) token = generate_token() spotify = spotipy.Spotify(auth=token) # example playlist write_playlist('doldher', '0B4jhlB6QUGHzY8i3rEwTt') ``` </details>
Author
Owner

@gawaineo commented on GitHub (Jan 19, 2018):

@CiniqueL

I believe the limit for the amount of tracks to be returned is 100 (check out the min and max track limit at the link below).
Source: https://developer.spotify.com/web-api/get-playlists-tracks/

I just wrote some code related to you question, below is an example:

spot = Spotify()
playlist_tracks = spot.user_playlist_tracks(user_id, playlist_id, fields='items,uri,name,id,total', market='fr')

Here's the link to the above method being called: http://spotipy.readthedocs.io/en/latest/#spotipy.client.Spotify.user_playlist_tracks

To get the user_id and playlist_id, I used spot.me() and go into Spotify app and get the URI when you right-click for the "Share" button, respectively. I believe you can use another method in spotipy library to get the playlist's ID once you get the playlist URI.

<!-- gh-comment-id:359051644 --> @gawaineo commented on GitHub (Jan 19, 2018): @CiniqueL I believe the limit for the amount of tracks to be returned is 100 (check out the min and max track limit at the link below). Source: https://developer.spotify.com/web-api/get-playlists-tracks/ I just wrote some code related to you question, below is an example: ``` spot = Spotify() playlist_tracks = spot.user_playlist_tracks(user_id, playlist_id, fields='items,uri,name,id,total', market='fr') ``` Here's the link to the above method being called: http://spotipy.readthedocs.io/en/latest/#spotipy.client.Spotify.user_playlist_tracks To get the `user_id` and `playlist_id`, I used `spot.me()` and go into Spotify app and get the URI when you right-click for the "Share" button, respectively. I believe you can use another method in `spotipy` library to get the playlist's ID once you get the playlist URI.
Author
Owner

@Kurchunk commented on GitHub (Jan 20, 2018):

Thank you both for your answers.

I was able to find what I needed on StackOverflow. I'm still working out some other bugs in my script, but the code I'm using is:

      for uri in pl_ids:

           results = self.sp.user_playlist_tracks(uri.split(':')[2], uri.split(':')[4])
           tracks = results['items']

           # Loops to ensure I get every track of the playlist
           while results['next']:
               results = self.sp.next(results)
               tracks.extend(results['items'])

       return tracks

I think the problem was that I was appending my list instead of extending it.

<!-- gh-comment-id:359128303 --> @Kurchunk commented on GitHub (Jan 20, 2018): Thank you both for your answers. I was able to find what I needed on StackOverflow. I'm still working out some other bugs in my script, but the code I'm using is: ``` for uri in pl_ids: results = self.sp.user_playlist_tracks(uri.split(':')[2], uri.split(':')[4]) tracks = results['items'] # Loops to ensure I get every track of the playlist while results['next']: results = self.sp.next(results) tracks.extend(results['items']) return tracks ``` I think the problem was that I was appending my list instead of extending it.
Author
Owner

@AtomicNess123 commented on GitHub (Jul 1, 2021):

  for uri in pl_ids:

       results = self.sp.user_playlist_tracks(uri.split(':')[2], uri.split(':')[4])
       tracks = results['items']

       # Loops to ensure I get every track of the playlist
       while results['next']:
           results = self.sp.next(results)
           tracks.extend(results['items'])

   return tracks

I think the problem was that I was appending my list instead of extending it.

Thank you! How to modify this to just get the id of the tracks?
I tried tracks = results['items'][0]['track']['id'] unsuccessfully.

<!-- gh-comment-id:872018343 --> @AtomicNess123 commented on GitHub (Jul 1, 2021): > for uri in pl_ids: > > results = self.sp.user_playlist_tracks(uri.split(':')[2], uri.split(':')[4]) > tracks = results['items'] > > # Loops to ensure I get every track of the playlist > while results['next']: > results = self.sp.next(results) > tracks.extend(results['items']) > > return tracks > ``` > > I think the problem was that I was appending my list instead of extending it. Thank you! How to modify this to just get the id of the tracks? I tried `tracks = results['items'][0]['track']['id'] `unsuccessfully.
Author
Owner

@marcraft2 commented on GitHub (Aug 3, 2021):

With that no limit!

username => user id, in profile link
playlist id => in playlist link

def get_playlist_ids(username,playlist_id):
    r = sp.user_playlist_tracks(username,playlist_id)
    t = r['items']
    ids = []
    while r['next']:
        r = sp.next(r)
        t.extend(r['items'])
    for s in t: ids.append(s["track"]["id"])
    return ids

<!-- gh-comment-id:891805828 --> @marcraft2 commented on GitHub (Aug 3, 2021): With that no limit! username => user id, in profile link playlist id => in playlist link ``` def get_playlist_ids(username,playlist_id): r = sp.user_playlist_tracks(username,playlist_id) t = r['items'] ids = [] while r['next']: r = sp.next(r) t.extend(r['items']) for s in t: ids.append(s["track"]["id"]) return ids
Author
Owner

@kunal-jangid commented on GitHub (Apr 11, 2023):

With that no limit!

username => user id, in profile link playlist id => in playlist link

def get_playlist_ids(username,playlist_id):
    r = sp.user_playlist_tracks(username,playlist_id)
    t = r['items']
    ids = []
    while r['next']:
        r = sp.next(r)
        t.extend(r['items'])
    for s in t: ids.append(s["track"]["id"])
    return ids

I got a doubt, what's username here? Like let's say I want to use random playlist as playlist id. Then what would I use as a username? Would it be mine or would it the creator of the playlist?

<!-- gh-comment-id:1503912615 --> @kunal-jangid commented on GitHub (Apr 11, 2023): > With that no limit! > > username => user id, in profile link playlist id => in playlist link > > ``` > def get_playlist_ids(username,playlist_id): > r = sp.user_playlist_tracks(username,playlist_id) > t = r['items'] > ids = [] > while r['next']: > r = sp.next(r) > t.extend(r['items']) > for s in t: ids.append(s["track"]["id"]) > return ids > ``` I got a doubt, what's username here? Like let's say I want to use random playlist as playlist id. Then what would I use as a username? Would it be mine or would it the creator of the playlist?
Author
Owner

@stephanebruckert commented on GitHub (Apr 11, 2023):

user_playlist_tracks is deprecated, you need to use playlist_tracks (without username)

<!-- gh-comment-id:1503924784 --> @stephanebruckert commented on GitHub (Apr 11, 2023): `user_playlist_tracks` is deprecated, you need to use `playlist_tracks` (without username)
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/spotipy#129
No description provided.