[GH-ISSUE #599] "Invalid access token, reason: None" with access token from OAuth #356

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

Originally created by @alansberman on GitHub (Oct 28, 2020).
Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/599

I'm new to both Django and spotipy, and am trying to get my currently playing track.

This is what I have thus far:

def home(request):
	sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="<my_token>",
                                               client_secret="<my_secret>",
                                               redirect_uri="http://localhost:8000/callback/",
                                               scope="user-library-read user-read-currently-playing"))
	results = sp.search(q='weezer', limit=20)
	return render(request, 'overview/dashboard.html')

def overview(request):
	code = request.GET.urlencode().split("=")[1]
	print(code, 'is code') # code (token) is returned
	if code:
		songs = []
		sp = spotipy.Spotify(auth=code)
		results = sp.current_user_saved_tracks()
		print(results)
		for idx, item in enumerate(results['items']):
			track = item['track']
			songs.append(track['artists'][0]['name'])
			return render(request, 'overview/dashboard.html', {'songs': songs})
	else:
		return 200

it appears I have to include the line results = sp.search(q='weezer', limit=20) or nothing happens.

Anyway, when I click allow on Spotify's popup and get to the callback, with a token, I get the following error

SpotifyException at /callback/
http status: 401, code:-1 -https://api.spotify.com/v1/me/tracks?limit=20&offset=0:
 Invalid access token, reason: None

What exactly is going wrong here? Any help would be appreciated, and apologies for the ugly code!

Originally created by @alansberman on GitHub (Oct 28, 2020). Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/599 I'm new to both Django and spotipy, and am trying to get my currently playing track. This is what I have thus far: ``` def home(request): sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="<my_token>", client_secret="<my_secret>", redirect_uri="http://localhost:8000/callback/", scope="user-library-read user-read-currently-playing")) results = sp.search(q='weezer', limit=20) return render(request, 'overview/dashboard.html') def overview(request): code = request.GET.urlencode().split("=")[1] print(code, 'is code') # code (token) is returned if code: songs = [] sp = spotipy.Spotify(auth=code) results = sp.current_user_saved_tracks() print(results) for idx, item in enumerate(results['items']): track = item['track'] songs.append(track['artists'][0]['name']) return render(request, 'overview/dashboard.html', {'songs': songs}) else: return 200 ``` it appears I have to include the line ```results = sp.search(q='weezer', limit=20)``` or nothing happens. Anyway, when I click allow on Spotify's popup and get to the callback, with a token, I get the following error ``` SpotifyException at /callback/ http status: 401, code:-1 -https://api.spotify.com/v1/me/tracks?limit=20&offset=0: Invalid access token, reason: None ``` What exactly is going wrong here? Any help would be appreciated, and apologies for the ugly code!
kerem 2026-02-27 23:22:10 +03:00
  • closed this issue
  • added the
    question
    label
Author
Owner

@Peter-Schorn commented on GitHub (Oct 29, 2020):

The variable code in def overview(request) is probably the authorization code, as described in the authorization guide, not the access token, which is what the auth parameter of Spotify expects.

More importantly, though, why are you trying to implement the authorization process yourself? spotipy already has authorization managers that do that for you: SpotifyClientCredentials, SpotifyOAuth, SpotifyPKCE, and SpotifyImplicitGrant. You're making things more complicated than they need to be. All you need to do is the following:

from spotipy import Spotify, SpotifyOAuth

spotify = Spotify(
    auth_manager=SpotifyOAuth(
        client_id="client_id",
        client_secret="client_secret",
        redirect_uri="http://localhost:8080/callback/",
        scope="user-library-read user-read-currently-playing"
    )
)

results = spotify.current_user_saved_tracks()
print(results)
songs = []
for idx, item in enumerate(results['items']):
    track = item['track']
    songs.append(track['artists'][0]['name'])

Do not create a new instance of Spotify for each request, which is what you appear to be doing; that doesn't make sense, because then you will have to go through the authorization process again.
Instead, create an instance of Spotify as a global variable and use it in each request. If you need more help, you need to post more code. It's hard for me to figure out what exactly you're trying to do, especially given the fact that the functions you posted don't call each other and I have no idea what the request parameter of the overview function is.

<!-- gh-comment-id:718301008 --> @Peter-Schorn commented on GitHub (Oct 29, 2020): The variable `code` in `def overview(request)` is probably the authorization code, as described in [the authorization guide][1], not the access token, which is what the `auth` parameter of `Spotify` expects. More importantly, though, why are you trying to implement the authorization process yourself? spotipy already has authorization managers that do that for you: `SpotifyClientCredentials`, `SpotifyOAuth`, `SpotifyPKCE`, and `SpotifyImplicitGrant`. You're making things more complicated than they need to be. All you need to do is the following: ``` from spotipy import Spotify, SpotifyOAuth spotify = Spotify( auth_manager=SpotifyOAuth( client_id="client_id", client_secret="client_secret", redirect_uri="http://localhost:8080/callback/", scope="user-library-read user-read-currently-playing" ) ) results = spotify.current_user_saved_tracks() print(results) songs = [] for idx, item in enumerate(results['items']): track = item['track'] songs.append(track['artists'][0]['name']) ``` Do not create a new instance of `Spotify` for each request, which is what you appear to be doing; that doesn't make sense, because then you will have to go through the authorization process again. Instead, create an instance of `Spotify` as a global variable and use it in each request. If you need more help, you need to post more code. It's hard for me to figure out what exactly you're trying to do, especially given the fact that the functions you posted don't call each other and I have no idea what the `request` parameter of the `overview` function is. [1]: https://developer.spotify.com/documentation/general/guides/authorization-guide/#example-1:~:text=If%20the%20user%20accepts%20your%20request%2C,be%20exchanged%20for%20an%20access%20token.
Author
Owner

@alansberman commented on GitHub (Oct 29, 2020):

Thanks @Peter-Schorn! Much appreciated.

Everything you're saying makes total sense, and it now works just fine.

<!-- gh-comment-id:718550647 --> @alansberman commented on GitHub (Oct 29, 2020): Thanks @Peter-Schorn! Much appreciated. Everything you're saying makes total sense, and it now works just fine.
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#356
No description provided.