spotipy-dev / spotipy

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

Key Error ['items'] #694

Closed Srijha09 closed 3 years ago

Srijha09 commented 3 years ago

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')
Peter-Schorn commented 3 years ago

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.

Srijha09 commented 3 years ago

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?

Peter-Schorn commented 3 years ago

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 for how to use spotipy with flask.

Srijha09 commented 3 years ago

Thanks alot!

Srijha09 commented 3 years ago

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} ?

Peter-Schorn commented 3 years ago

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.

Srijha09 commented 3 years ago

Oh okay. Thanks