pythonflaskspotipy

Spotipy exception raised status 403; reason: none


I am trying to learn how to work with API's for the first time and I took up spotipy. I was following the tutorial here for this task. I followed the tutorial until he called current_user_saved_tracks(limit=50, offset=0) and everything is working fine. However, when I try to switch this to a different call current_user_top_tracks(limit=20, offset=0, time_range='medium_term') it throws an error:

spotipy.exceptions.SpotifyException: http status: 403, code:-1 - https://api.spotify.com/v1/me/top/tracks?time_range=medium_term&limit=20&offset=0: error, reason: None

I am referring to the spotipy docs for these calls. This is the code I have till now. For reference, the call was made in the function getTracks at line 40:

import time
from flask import Flask, request, url_for, redirect, session
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from git_ignore.config import *

app = Flask(__name__)

TOKEN_INFO = "token_info"


@app.route('/')
def login():
    sp_oauth = create_spotify_ouath()
    auth_url = sp_oauth.get_authorize_url()
    return redirect(auth_url)


@app.route('/redirect')
def redirectPage():
    sp_oauth = create_spotify_ouath()
    session.clear()
    code = request.args.get('code')
    token_info = sp_oauth.get_access_token(code)
    session[TOKEN_INFO] = token_info
    return redirect(url_for('getTracks', _external=True))


@app.route('/getTracks')
def getTracks():
    try:
        token_info = get_token()
    except:
        print("user not logged in")
        return redirect('/')
    sp = spotipy.Spotify(auth=token_info['access_token'])
    return sp.current_user_top_tracks(time_range='medium_term', limit=20, offset=0)
    # return sp.current_user_saved_tracks(limit=20, offset=0)
    # The commented line above seems to work but the one with top_tracks throws an error.



def get_token():
    token_info = session.get(TOKEN_INFO, None)
    if not token_info:
        raise "exception"
    now = int(time.time())
    is_expired = token_info['expires_at'] - now < 60
    if (is_expired):
        sp_oauth = create_spotify_ouath()
        token_info = sp_oauth.refresh_access_token(token_info['refresh_token'])
    return token_info


def create_spotify_ouath():
    return SpotifyOAuth(
        client_id=client_id,
        client_secret=client_secret,
        # Where to come back to
        redirect_uri=url_for('redirectPage', _external=True),
        scope="user-library-read")


if __name__ == "__main__":
    app.run(debug=True)

Solution

  • Update: So I took a break from this problem for a few hours and came back to debug it. I went to the Spotify Dashboard - deleted my app and created a new one. Then, I replaced my Client ID and Client Secret and ran the file again. It seems to work now! Not sure what the issue was exactly (probably a bug?) but creating a new app and replacing your credentials works!