Getting a no access token error on the Spotify API using it flask

209 Views Asked by At

This is the error code https://api.spotify.com/v1/me/top/tracks?time_range=short_term&limit=10&offset=0:

None, reason: None

This is the code where the issue comes from:

@app.route('/top-songs')
def top_songs():
    token_info = get_token()
    if not token_info:
        return "Not work"

    print("Access Token:", token_info['access_token'])
    access_token = token_info['access_token']
    sp = spotipy.Spotify(auth=access_token)
    try:
        top_tracks = sp.current_user_top_tracks(limit=10, offset=0, time_range='short_term')['items']
    except spotipy.SpotifyException as e:
        print("Spotify API Error:", e)

    # Extract relevant information from top_tracks
    # Example: track_names = [track['name'] for track in top_tracks['items']]

    return render_template('index.html')

I am trying to print the top songs from the Spotify API and display it on a HTML file. The error seems to be coming up at the line:

top_tracks = sp.current_user_top_tracks(limit=10, offset=0, time_range='short_term')['items']

because I don't get the error if that is removed. Anyone have any idea?

1

There are 1 best solutions below

6
On

You are getting an HTTP Status code 403 Forbidden (The server understands the request but refuses to authorize it.).

If you check Spotify Web API documentation about Authorization you'll see a table below that says if you are using Client credentials (access_token) then you don't have access to user resources, which in this case you are trying to access spotipy.Spotify.current_user_top_tracks() which is why the API is raising an exception with HTTP status code 403.

To access user resources then you are going to need to authenticate using Authorization code as described in spotipy documentation. In this case you need the scope user-top-read:

import spotipy
from spotipy.oauth2 import SpotifyOAuth

# You also need CLIENT_ID and CLIENT_SECRET to create the Spotify client
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope="user-top-read"))
top_tracks = sp.current_user_top_tracks()["items"]
print(top_tracks)