0

i have a code that creates a dataframe of the songs from a playlist. I tried to change it so it will ignore the 100 limit and i will recieve all the songs from the playlist, but it doesnt work.. can you help me please?

i tried this code: import pandas as pd import spotipy from spotipy.oauth2 import SpotifyClientCredentials

def analyze_playlist100(creator, playlist_id): # Initialize Spotify client client_credentials_manager = SpotifyClientCredentials(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

# Create empty dataframe
playlist_features_list = ["artist", "album", "track_name", "track_id", "release_date", "popularity",
                          "danceability", "energy", "key", "loudness",
                          "mode", "speechiness", "instrumentalness", "liveness",
                          "valence", "tempo", "duration_ms", "time_signature"]

playlist_df = pd.DataFrame(columns=playlist_features_list)

# Initialize offset and limit
offset = 0
limit = 100

while True:
    # Make API call with current offset
    playlist = sp.user_playlist_tracks(creator, playlist_id, offset=offset, limit=limit)["items"]

    if len(playlist) == 0:
        # No more tracks, break the loop
        break

    for track in playlist:
        # Create empty dict
        playlist_features = {}

        # Get metadata
        playlist_features["artist"] = track["track"]["album"]["artists"][0]["name"]
        playlist_features["album"] = track["track"]["album"]["name"]
        playlist_features["track_name"] = track["track"]["name"]
        playlist_features["track_id"] = track["track"]["id"]
        playlist_features["release_date"] = track["track"]["album"]["release_date"]
        playlist_features["popularity"] = track["track"]["popularity"]

        # Get audio features
        audio_features = sp.audio_features(playlist_features["track_id"])[0]
        for feature in playlist_features_list[6:]:
            playlist_features[feature] = audio_features[feature]

        # Concatenate the dfs
        track_df = pd.DataFrame(playlist_features, index=[0])
        playlist_df = pd.concat([playlist_df, track_df], ignore_index=True)

    # Increment offset by the limit for the next API call
    offset += limit

return playlist_df
  • Does this answer your question? [Spotipy: How to read more than 100 tracks from a playlist](https://stackoverflow.com/questions/39086287/spotipy-how-to-read-more-than-100-tracks-from-a-playlist) – Ximzend Jun 10 '23 at 10:26

1 Answers1

0

From Spotify documentation in here

Track's next data indicate more data or not. It is none, no more data.

I add that logic from your code.

enter image description here

This code is demo

import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd

SCOPE = [
    'user-library-read',
    'user-follow-read',
    'user-top-read',
    'playlist-read-private',
    'playlist-read-collaborative'
    ]
USER_ID = '<your user id>'
REDIRECT_URI = '<your redirect uri>'
CLIENT_ID = '<your client id>'
CLIENT_SECRET = '<your client secret>'
PLAYLIST_ID = '<your playlist id>'

auth_manager = SpotifyOAuth(
    scope=SCOPE,
    username=USER_ID,
    redirect_uri=REDIRECT_URI,
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET)

def get_playlist():
    try:
        playlist_features_list = [
            "artist", "album", "track_name", "track_id", "release_date", "popularity",
            "danceability", "energy", "key", "loudness",
            "mode", "speechiness", "instrumentalness", "liveness",
            "valence", "tempo", "duration_ms", "time_signature"]
        playlist_df = pd.DataFrame(columns=playlist_features_list)
        sp = spotipy.Spotify(auth_manager=auth_manager)
        creator = USER_ID
        playlist_id = PLAYLIST_ID
        offset = 0
        limit = 100
        while True:
            results = sp.user_playlist_tracks(user=creator, playlist_id=playlist_id, offset=offset, limit=limit)
            for track in results['items']:
                # Create empty dict
                playlist_features = {}
                # Get metadata
                playlist_features["artist"] = track["track"]["album"]["artists"][0]["name"]
                playlist_features["album"] = track["track"]["album"]["name"]
                playlist_features["track_name"] = track["track"]["name"]
                playlist_features["track_id"] = track["track"]["id"]
                playlist_features["release_date"] = track["track"]["album"]["release_date"]
                playlist_features["popularity"] = track["track"]["popularity"]
                # Get audio features
                audio_features = sp.audio_features(playlist_features["track_id"])[0]
                for feature in playlist_features_list[6:]:
                    playlist_features[feature] = audio_features[feature]
                # Concatenate the dfs
                track_df = pd.DataFrame(playlist_features, index=[0])
                playlist_df = pd.concat([playlist_df, track_df], ignore_index=True)
            # Increment offset by the limit for the next API call
            offset += limit
            next = results['next']
            if next is None:
                break
        return playlist_df
    except Exception as e:
        print('Failed to upload to call get_playlist(): '+ str(e))

playlists = get_playlist()
print(playlists)

Result

enter image description here

Similar question in here

Bench Vue
  • 5,257
  • 2
  • 10
  • 14
  • thank you ! and what do i need to put in the REDIRECT_URI? – Rom Meltzer Jun 11 '23 at 22:05
  • Detail information in [here](https://stackoverflow.com/questions/75419872/spotify-api-getting-404-as-a-response-trying-to-find-current-song/75424917#75424917) at step 2 – Bench Vue Jun 12 '23 at 00:26