Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

Issues with Web API

Issues with Web API

I am using Spotipy, and I am having issues with the API. 
My code worked yesterday while I was developing it, and I have reverted back to that point where I knew it worked, but now, with my code below, the terminal looks like this:
PS C:\Users\tobia\Desktop\Clean\DiscoverSort> & C:/Users/tobia/AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users/tobia/Desktop/Clean/DiscoverSort/DiscoverSort/DiscoverSort.py
Processing Playlist: Heritage (ID: 0KPrCpOPrbvmd2qf90Uug7)

It's just stuck on the first iteration of my playlist. Before, it would go through my playlists quite rapidly. When I eventually click CTRL + C to exit the program, this shows:
Traceback (most recent call last):
File "c:\Users\tobia\Desktop\Clean\DiscoverSort\DiscoverSort\DiscoverSort.py", line 39, in <module>
artist_info = sp.artist(artist_id)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tobia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\spotipy\client.py", line 396, in artist
return self._get("artists/" + trid)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tobia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\spotipy\client.py", line 327, in _get
return self._internal_call("GET", url, payload, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tobia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\spotipy\client.py", line 270, in _internal_call
response = self._session.request(
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tobia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\requests\sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tobia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\requests\sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tobia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\requests\adapters.py", line 486, in send
resp = conn.urlopen(
^^^^^^^^^^^^^
File "C:\Users\tobia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\urllib3\connectionpool.py", line 943, in urlopen
retries.sleep(response)
File "C:\Users\tobia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\urllib3\util\retry.py", line 355, in sleep
slept = self.sleep_for_retry(response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tobia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\urllib3\util\retry.py", line 334, in sleep_for_retry
time.sleep(retry_after)
KeyboardInterrupt
PS C:\Users\tobia\Desktop\Clean\DiscoverSort>

import
spotipy
from spotipy.oauth2 import SpotifyOAuth
from collections import defaultdict

scope = "user-library-read playlist-read-private playlist-modify-private playlist-modify-public"
# Authentication
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
    client_id="",
    client_secret="",
    redirect_uri="http://localhost:8888/callback",
    scope=scope))

playlist_top_genres = {}

# Dictionary to store genre frequencies for each playlist
playlist_genre_frequencies = {}

# Fetch all playlists of the current user
playlists = sp.current_user_playlists(limit=10)

# Get current user's Spotify ID (this is necessary to check playlist ownership)
current_user_id = sp.current_user()['id']

# Loop through each playlist and calculate top 3 genres
for playlist in playlists['items']:
    print(f"Processing Playlist: {playlist['name']} (ID: {playlist['id']})")
   
    # Fetch the tracks from the playlist
    tracks = sp.playlist_tracks(playlist_id=playlist['id'])
   
    # Use a defaultdict to count genres for the current playlist
    genre_count = defaultdict(int)
   
    for idx, item in enumerate(tracks['items']):
        track = item['track']
        artist_id = track['artists'][0]['id']
       
        # Get artist details to fetch genres
        artist_info = sp.artist(artist_id)
        genres = artist_info['genres']  # List of genres associated with the artist
       
        # Add genres to the count
        for genre in genres:
            genre_count[genre] += 1
   
    # Sort the genres by their frequency in descending order
    sorted_genres = sorted(genre_count.items(), key=lambda x: x[1], reverse=True)
   
    # Select the top 3 genres (or fewer if there are not enough genres)
    top_3_genres = [genre for genre, count in sorted_genres[:3]]
   
    # Store the top 3 genres for this playlist
    playlist_top_genres[playlist['name']] = top_3_genres

# Print the top 3 genres for each playlist
for playlist_name, top_genres in playlist_top_genres.items():
    print(f"\nPlaylist: {playlist_name}")
    print(f"Top 3 Genres: {', '.join(top_genres) if top_genres else 'No genres found'}")


# Step 2: Find the Discover Weekly playlist
discover_weekly_playlist = None
for playlist in playlists['items']:
    if playlist['name'].lower() == 'discover weekly':
        discover_weekly_playlist = playlist
        break

if discover_weekly_playlist:
    print(f"Found 'Discover Weekly' playlist: {discover_weekly_playlist['name']} (ID: {discover_weekly_playlist['id']})")
   
    # Fetch the tracks from Discover Weekly
    discover_weekly_tracks = sp.playlist_tracks(playlist_id=discover_weekly_playlist['id'])
   
    # Step 3: Match Discover Weekly tracks to playlists based on genres
    for item in discover_weekly_tracks['items']:
        track = item['track']
        track_id = track['id']
        track_name = track['name']
        artist_id = track['artists'][0]['id']
       
        # Get the genres for the artist of the Discover Weekly track
        artist_info = sp.artist(artist_id)
        track_genres = artist_info['genres']
       
        print(f"Analyzing track '{track_name}' with genres: {', '.join(track_genres)}")
       
        # Compare genres with each playlist's top 3 genres
        for playlist in playlists['items']:
            # Only add tracks to playlists owned by the current user
            if playlist['owner']['id'] == current_user_id:
                top_genres = playlist_top_genres.get(playlist['name'], [])
                if any(genre in top_genres for genre in track_genres😞
                    # Add the track to the matching playlist
                    sp.playlist_add_items(playlist['id'], [track_id])
                    print(f"Added '{track_name}' to playlist '{playlist['name']}'")
else:
    print("Discover Weekly playlist not found.")

Please help! : (
Reply
1 Reply

Hi Tobynatoren,

 

Thanks so much for sharing your code with the Community!

 

I took a look and noticed you're using `sp.artist(id)` instead of `sp.artists([id_list])`. Spotify offers batch APIs, like the "Get Several Artists" endpoint, which allows you to fetch data for multiple artists in a single request. This is a great way to cut down on the number of API requests, especially when you need data for several artists at once.

 

I’d recommend trying this out—it’ll help you reduce the number of requests significantly!

 

Feel free to reach out if you have any questions or need further assistance. 😊

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

Suggested posts