Search code examples
pythonpython-requestsspotifyspotipy

Python Get Code from redirected Spotify User Authentication


Trying to get the code which arises from the redirected URL when a user approves my application to read their data from the spotify API. The issue is that I need the code to either receive the url that contains the code when the user authenticates the application. I haven't been able to do that through Python yet. I think I need to do this through requests but I don't 1. know what to use 2. know where I should look for what to use.

The code I have so far:

import spotipy
from spotipy.oauth2 import SpotifyOAuth
import os
from pathlib import Path
import requests

client_id = os.environ['']
client_secret = os.environ['']
redirect_uri = 'http://www.example.xyz/'
scope = 'user-read-recently-played user-read-currently-playing user-top-read user-read-private'
cache = Path("cache/")
username = ''

oauth = SpotifyOAuth(client_id, client_secret, redirect_uri, scope=scope, cache_path=cache/f".cache-{username}",username=username)

url = oauth.get_authorize_url()
req = requests.get(url)
red = req.url
print(red)
# code = oauth.parse_response_code(red)
# token = oauth.get_access_token(code=code,as_dict=False)

This is just a test that i'm doing before I attempt to implement this in my larger code (a discord bot) and what I do is that in this code I manually get the redirected url, paste it into the browser and then authenticate the app from there: the page then continues to the redirected page having the authorisation code affixed to the end.

What I want to know is how to get that authorisation code or send it to my script in some way with Python.


Solution

  • You should create a local web server that listens for the Spotify OAuth callback and receives the token there.

    This can be achieved using minimal HTTP servers such as Flask.

    Find an arbitrary port to listen to (make it unique enough, don't use 8080 since it may conflict with user already existing servers).

    Then, before opening the authentication window, start your tiny server, then open the user browser for authentication, having the callback URL set as http://localhost:port/callback or something like that.

    You can then handle the token from the Flask endpoint, you could then send the token back to your app using threads or IPC, or for a simpler implementation, since the token is maybe the first step in the app, you can make Flask call the main method of your script with the obtained credentials.