[GH-ISSUE #694] Key Error ['items'] #412

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

Originally created by @Srijha09 on GitHub (Jun 23, 2021).
Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/694

Hi, since I'm new to APIs, I'm trying to get accustomed to using Spotify API for creating a Flask Application. I got a key error when i was trying to extract a user's recently played tracks.
Screenshot (4)
I am not able to identify why this error occured. Could you please let me the the cause of the error?
Below is the code

'def get_user_last_played_tracks(self, auth_header, user_id, limit=25):
        """Get the last n tracks played by a user who logins
        :param auth_header: the authentication header
        :param user_id: the Spotify User ID when a user gets authenticated in Spotify
        :param limit: Number of tracks to get. Limit should be <= 50
        :return : List of last played n tracks from the user
        """
        last_played_api_endpoint = f"https://api.spotify.com/v1/users/{user_id}/player/recently-played?limit={limit}"
        tracks = json.loads(requests.get(last_played_api_endpoint, headers=auth_header).text)

        return [
             {
                'track_artist': track["track"]["artists"][0]["name"],
                'track_name': track["track"]["name"],
                'track_image': track["track"]["album"]["images"][0]["url"],
                'track_url': track["track"]["external_urls"]["spotify"],
                'track_id': track["track"]["id"]
             } for track in tracks["items"]
        ]`

Flask app

@app.route("/select_tracks", methods=['GET', 'POST'])
def select_tracks():
    authorization_header = session['authorization_header']

    def extract_letters(string):
        return ''.join([letter for letter in string if not letter.isdigit()])

    if request.method == 'GET':
        # -------- Get user's name, id, and set session --------
        profile_data = spotify_client.get_user_profile_data(authorization_header)
        user_display_name, user_id = profile_data['display_name'], profile_data['id']
        session['user_id'], session['user_display_name'] = user_id, user_display_name

        # -------- Get user recently played tracks data --------
        tracks_data = spotify_client.get_user_last_played_tracks(authorization_header, user_id, limit=25)

        return render_template('playlist_select_tracks.html',
                               user_display_name=user_display_name,
                               tracks=tracks_data,
                               func=extract_letters)

    return render_template('playlist_select_tracks.html')
Originally created by @Srijha09 on GitHub (Jun 23, 2021). Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/694 Hi, since I'm new to APIs, I'm trying to get accustomed to using Spotify API for creating a Flask Application. I got a key error when i was trying to extract a user's recently played tracks. ![Screenshot (4)](https://user-images.githubusercontent.com/50697493/123059657-a9e83780-d412-11eb-84d1-269cc35aaf69.png) I am not able to identify why this error occured. Could you please let me the the cause of the error? Below is the code ``` 'def get_user_last_played_tracks(self, auth_header, user_id, limit=25): """Get the last n tracks played by a user who logins :param auth_header: the authentication header :param user_id: the Spotify User ID when a user gets authenticated in Spotify :param limit: Number of tracks to get. Limit should be <= 50 :return : List of last played n tracks from the user """ last_played_api_endpoint = f"https://api.spotify.com/v1/users/{user_id}/player/recently-played?limit={limit}" tracks = json.loads(requests.get(last_played_api_endpoint, headers=auth_header).text) return [ { 'track_artist': track["track"]["artists"][0]["name"], 'track_name': track["track"]["name"], 'track_image': track["track"]["album"]["images"][0]["url"], 'track_url': track["track"]["external_urls"]["spotify"], 'track_id': track["track"]["id"] } for track in tracks["items"] ]` ``` Flask app ``` @app.route("/select_tracks", methods=['GET', 'POST']) def select_tracks(): authorization_header = session['authorization_header'] def extract_letters(string): return ''.join([letter for letter in string if not letter.isdigit()]) if request.method == 'GET': # -------- Get user's name, id, and set session -------- profile_data = spotify_client.get_user_profile_data(authorization_header) user_display_name, user_id = profile_data['display_name'], profile_data['id'] session['user_id'], session['user_display_name'] = user_id, user_display_name # -------- Get user recently played tracks data -------- tracks_data = spotify_client.get_user_last_played_tracks(authorization_header, user_id, limit=25) return render_template('playlist_select_tracks.html', user_display_name=user_display_name, tracks=tracks_data, func=extract_letters) return render_template('playlist_select_tracks.html') ```
kerem closed this issue 2026-02-27 23:22:29 +03:00
Author
Owner

@Peter-Schorn commented on GitHub (Jun 23, 2021):

https://api.spotify.com/v1/users/{user_id}/player/recently-played?limit={limit}

This endpoint does not exist. That's your first problem. Why don't you use the spotipy library instead of making the requests manually?

:param user_id: the Spotify User ID when a user gets authenticated in Spotify

Spotify does not return the user id during the authentication process.

<!-- gh-comment-id:866995438 --> @Peter-Schorn commented on GitHub (Jun 23, 2021): > https://api.spotify.com/v1/users/{user_id}/player/recently-played?limit={limit} This endpoint does not exist. That's your first problem. Why don't you use the spotipy library instead of making the requests manually? > :param user_id: the Spotify User ID when a user gets authenticated in Spotify Spotify does not return the user id during the authentication process.
Author
Owner

@Srijha09 commented on GitHub (Jun 23, 2021):

Oh okay. Yes sure, i'll do that. Also, is there a way where I can retrieve any user's recently played songs when they login through my Flask application?

<!-- gh-comment-id:867009960 --> @Srijha09 commented on GitHub (Jun 23, 2021): Oh okay. Yes sure, i'll do that. Also, is there a way where I can retrieve any user's recently played songs when they login through my Flask application?
Author
Owner

@Peter-Schorn commented on GitHub (Jun 23, 2021):

Use this method to retrieve the user's recently played tracks:
github.com/plamere/spotipy@06551cd055/spotipy/client.py (L1432)

See this example for how to use spotipy with flask.

<!-- gh-comment-id:867015513 --> @Peter-Schorn commented on GitHub (Jun 23, 2021): Use this method to retrieve the user's recently played tracks: https://github.com/plamere/spotipy/blob/06551cd0553d6e030f3f4ee7da5fac12c424bac7/spotipy/client.py#L1432 See this [example](https://github.com/plamere/spotipy/blob/master/examples/app.py) for how to use spotipy with flask.
Author
Owner

@Srijha09 commented on GitHub (Jun 23, 2021):

Thanks alot!

<!-- gh-comment-id:867015912 --> @Srijha09 commented on GitHub (Jun 23, 2021): Thanks alot!
Author
Owner

@Srijha09 commented on GitHub (Jun 24, 2021):

Hi, is it possible to get recently played tracks from other user by using their user id when the login through my application?
Since this API endpoint is only for the current user https://api.spotify.com/v1/me/player/recently-played?limit={limit} ?

<!-- gh-comment-id:867428244 --> @Srijha09 commented on GitHub (Jun 24, 2021): Hi, is it possible to get recently played tracks from other user by using their user id when the login through my application? Since this API endpoint is only for the current user https://api.spotify.com/v1/me/player/recently-played?limit={limit} ?
Author
Owner

@Peter-Schorn commented on GitHub (Jun 24, 2021):

No, you can only get the recently played tracks for the current user. The spotipy documentation describes all of the available endpoints. You should also read the Spotify web API reference. If you don't see what you're looking for on those pages, then it's not possible.

<!-- gh-comment-id:867758406 --> @Peter-Schorn commented on GitHub (Jun 24, 2021): No, you can only get the recently played tracks for the current user. The [spotipy documentation](https://spotipy.readthedocs.io/en/2.18.0/#api-reference) describes all of the available endpoints. You should also read the [Spotify web API reference](https://developer.spotify.com/documentation/web-api/reference/). If you don't see what you're looking for on those pages, then it's not possible.
Author
Owner

@Srijha09 commented on GitHub (Jun 24, 2021):

Oh okay. Thanks

<!-- gh-comment-id:867882423 --> @Srijha09 commented on GitHub (Jun 24, 2021): Oh okay. Thanks
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#412
No description provided.