spotipy-dev / spotipy

A light weight Python library for the Spotify Web API
http://spotipy.readthedocs.org
MIT License
5.03k stars 957 forks source link

Querying Spotify for song details is not returning with the 'Track ID'. #1033

Closed Artholos closed 6 months ago

Artholos commented 1 year ago

Describe the bug Querying Spotify for song details is not returning with the 'Track ID'. Here's my code to search for popular songs in various genres. I need three details about each track: Name, artist, and track ID. But the track ID is not being returned. According to the documentation on https://developer.spotify.com/documentation/web-api/reference/search shows that the track ID located in: 'tracks > items > id'

Here's my function that returns list of top 10 songs in a genre:

def find_popular_song(The_G = 'any', The_C = 'US', EyeLimit = 10):
    print("Finding a popular song...")
    # Get a list of songs from Spotify
    if The_G == 'any':
        playlist_id = '37i9dQZEVXbMDoHDwVN2tF'
    else:
        playlists = sp.category_playlists(category_id=The_G, country=The_C, limit=1)
        playlist_id = playlists["playlists"]["items"][0]["id"]
    results = sp.playlist(playlist_id, fields="tracks.items(track(name, artists(name)))")
    print(f"Results found: \n\n{results}")
    print(f"Building Arrays...")
    song_names = []
    song_ids = []
    artist_names = []
    for i in range(EyeLimit):
        song_names.append(results["tracks"]["items"][i]["track"]["name"])
        song_ids.append(results["tracks"]["items"][i]["id"])
        artist_names.append(results["tracks"]["items"][i]["track"]["artists"][0]["name"])

    # Query the database for matching songs
    print(f"Checking the database for any matches...")
    TheEye = 0
    for sn in song_names:
        if not is_song_in_database(song_names[sn], artist_names[sn]) and tempo_check(song_ids[sn]):
            The_Song = [song_names[sn], song_ids[sn], artist_names[sn]]
            print(f"{song_names[sn]} by {artist_names[sn]} is ready going to get the BSP Treatment! Congriggles!")
            return The_Song
        if TheEye >= EyeLimit:
            print(f"No songs found in the top {EyeLimit} for the genre: {The_G}")
            return 'no songs'
        TheEye += 1

Expected behavior I expect that the track ID would be returned so it can be used later in other Spotify API calls.

Output

Exception has occurred: KeyError
'id'
  File "D:\My-Program-Files\ICBS\Spotify-Functions.py", line 72, in find_popular_song
    song_ids.append(results["tracks"]["items"][i]["id"])
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "D:\My-Program-Files\ICBS\Spotify-Functions.py", line 122, in <module>
    The_Goods = find_popular_song()
                ^^^^^^^^^^^^^^^^^^^
KeyError: 'id'

image

Environment:

dieser-niko commented 1 year ago

Generally a good idea. I think it would be best to use JSON schemas and have them as python objects.

But I'm not sure if the OpenAPI definition from Spotify is actually representing the API correctly. If I'm not mistaken, there is/was actually a flaw in the definition, but I'll have to check that again sometime.

Edit: found a related issue: https://github.com/spotipy-dev/spotipy/issues/975

dieser-niko commented 6 months ago

I'm currently going through some issues and I'm realizing that I probably commented on the wrong issue. Do you still need help or can we close this here?

Artholos commented 6 months ago

Oh heyo, I'm so sorry, I totally forgot. I couldn't find a work around to the issue so I gave up and went to do something else. It looks like you found the related problem, so I think we're good to close this issue.

Thanks so much!

dieser-niko commented 6 months ago

It looks like you found the related problem

Yeah no, that's the thing. The related issue doesn't seem to be related to your issue.

Artholos commented 6 months ago

Alright then, I've dug up the program and the issue is still happening, probably because I haven't changed anything yet. What do you suggest?

dieser-niko commented 6 months ago

I've spotted two issues. The first one is here:

...
    if The_G == 'any':
        playlist_id = '37i9dQZEVXbMDoHDwVN2tF'
    else:
        playlists = sp.category_playlists(category_id=The_G, country=The_C, limit=1)
        playlist_id = playlists["playlists"]["items"][0]["id"]
-    results = sp.playlist(playlist_id, fields="tracks.items(track(name, artists(name)))")
+    results = sp.playlist(playlist_id, fields="tracks.items(track(id, name, artists(name)))")
    print(f"Results found: \n\n{results}")
    print(f"Building Arrays...")
...

It seems that you've filtered out the ID.

The second one here:

...
   for i in range(EyeLimit):
        song_names.append(results["tracks"]["items"][i]["track"]["name"])
-        song_ids.append(results["tracks"]["items"][i]["id"])
+        song_ids.append(results["tracks"]["items"][i]["track"]["id"])
        artist_names.append(results["tracks"]["items"][i]["track"]["artists"][0]["name"])
...

I think that one's self explanatory.

Artholos commented 6 months ago

おh thank you! I can't believe I missed those haha! I suppose a second set of eyes really makes all the difference. I'm getting a completely new error now down in the database part. Looks like I have a project again! Thank you so much for your help :D