Hugo Torres
Hugo Torres

Reputation: 328

Is there a way to retrieve more than 50 recently played tracks using spotipy?

I've been playing around with spotipy and the spotify API and I wanted to create a dashboard where I present some metrics about my main playlist and my recently played songs. As it happens, in most functions, there's an imposed limit of 50 results. When I extarcted the contents of my playlist, I was able to circumvent this using next and susequently fetching the following results until there are none. However, with the recently played tracks this is not working, although there's a next URL, that URL contains nothing. I'm not sure if it's actually possible to retrieve more than 50 rows of data or there's something I'm doing wrong, but help would be appreciated.

Current code:

recently_played = sp_login.current_user_recently_played()

def get_recent_tracks(sp_login, n_tracks):
    results = sp_login.current_user_recently_played()
    
    tracks = get_tracks_id(results['items'])
    dates = get_date_played(results['items'])

    while results['next'] and len(tracks) < n_tracks:
        results = sp_login.next(results)
        tracks.extend(get_tracks_id(results['items']))
        dates.extend(get_date_played(results['items']))
    return tracks, dates

def get_tracks_id(tracks):
  
  track_ids = []
  
  for item in tracks:
    track_ids.append(item['track']['id'])

  return track_ids

def get_date_played(tracks):
  
  dates_played = []
  
  for item in tracks:
    dates_played.append(item['played_at'])

  return dates_played

all_tracks, dates_played = get_recent_tracks(sp_login, 300)

If I just run this:

results = sp_login.current_user_recently_played()
sp_login.next(results)

I get this as an output:

{'items': [], 'next': None, 'cursors': None, 'limit': 50, 'href': 'https://api.spotify.com/v1/me/player/recently-played?before=1659536402173&limit=50'}

Upvotes: 2

Views: 1908

Answers (1)

rob_med
rob_med

Reputation: 546

Unfortunately as per documentation the maximum limit for that endpoint is indeed 50, so the "next" field will always be null.

Upvotes: 1

Related Questions