Use Authorization Code Flow with SpotifyOAuth
masterThe Authorization Code flow is suitable for long-running applications where a user logs in once. It provides a refreshable access token.
Requirements:
- Register your app at the Spotify Developer Dashboard to obtain a
client idandclient secret. - Add a Redirect URI to your application in the Dashboard. The
redirect_uriargument orSPOTIPY_REDIRECT_URIenvironment variable must match this exactly. - If using an
httpscheme with127.0.0.1and a specific port, Spotipy will automatically start a local server to receive the token.
Environment Variables:
SPOTIPY_CLIENT_IDSPOTIPY_CLIENT_SECRETSPOTIPY_REDIRECT_URI
import spotipy
from spotipy.oauth2 import SpotifyOAuth
scope = "user-library-read"
# Uses environment variables for credentials by default
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
results = sp.current_user_saved_tracks()
for idx, item in enumerate(results['items']):
track = item['track']
print(idx, track['artists'][0]['name'], " – ", track['name'])