I have a Flask application connecting to Spotify’s API using the authorization code flow. The process runs smoothly when I redirect users to the authorization URL with the necessary parameters.
from flask import Flask, request, redirect, jsonify
import requests
import base64
import urllib.parse
app = Flask(__name__)
app.secret_key = 'my_secret_key'
SPOTIFY_AUTH_ENDPOINT = 'https://accounts.spotify.com/authorize'
SPOTIFY_TOKEN_ENDPOINT = 'https://accounts.spotify.com/api/token'
APP_ID = 'your_client_id'
APP_SECRET = 'your_client_secret'
CALLBACK_URL = 'http://localhost:5000/auth_callback'
@app.route('/')
def index():
return "<a href='/authenticate'>Connect Spotify</a>"
@app.route('/authenticate')
def authenticate():
permissions = 'user-read-private user-read-email'
query_params = {
'client_id': APP_ID,
'response_type': 'code',
'redirect_uri': CALLBACK_URL,
'scope': permissions,
'show_dialog': True
}
spotify_auth_url = f"{SPOTIFY_AUTH_ENDPOINT}?{urllib.parse.urlencode(query_params)}"
return redirect(spotify_auth_url)
@app.route('/auth_callback')
def auth_callback():
if 'error' in request.args:
return jsonify({'error': request.args['error']})
auth_code = request.args.get('code')
if not auth_code:
return jsonify({'error': 'Authorization code missing'})
credentials = base64.b64encode(
f"{APP_ID}:{APP_SECRET}".encode()
).decode()
request_headers = {
'Authorization': f'Basic {credentials}',
'Content-Type': 'application/x-www-form-urlencoded'
}
token_data = {
'grant_type': 'authorization_code',
'code': auth_code,
'redirect_uri': CALLBACK_URL
}
try:
token_response = requests.post(SPOTIFY_TOKEN_ENDPOINT, headers=request_headers, data=token_data)
token_response.raise_for_status()
return jsonify(token_response.json())
except requests.exceptions.RequestException as error:
return jsonify({
'error': 'Token request failed',
'message': str(error)
}), 500
if __name__ == '__main__':
app.run(port=5000, debug=True)
My issue is that I want to skip the redirect and make a direct GET request for authorization. However, when I attempt this, I can’t seem to obtain the necessary authorization for the POST request to retrieve the access token. Is this something Spotify has intentionally restricted? I’m curious to know if there’s a workaround or if the redirect is essential for the authorization code flow to function correctly.