Overview
The Authorization Code flow is the OAuth 2.0 method for user authentication. It enables:- Access to user-specific endpoints (playlists, library, playback, etc.)
- Fine-grained permission scopes
- Automatic token refresh with refresh tokens
- Long-lived user sessions
The Authorization Code flow requires user interaction to grant permissions. For app-only authentication without user data, use Client Credentials instead.
Class: AuthorizationCode
TheAuthorizationCode class implements the OAuth 2.0 authorization code grant type with automatic token refresh and caching.
Constructor
Parameters
Spotify application client ID. If not provided, reads from
SPOTIFY_SDK_CLIENT_ID environment variable.Spotify application client secret. If not provided, reads from
SPOTIFY_SDK_CLIENT_SECRET environment variable.OAuth callback URL registered in your Spotify app settings. If not provided, reads from
SPOTIFY_SDK_REDIRECT_URI environment variable.OAuth scopes to request. Can be a space-delimited string, list, or tuple. See Spotify Authorization Scopes for available scopes.
Optional refresh token from a previous authorization. If provided, the auth provider can refresh access tokens without requiring user interaction.
Optional token cache for storing access and refresh tokens. Defaults to
InMemoryTokenCache(). Use FileTokenCache for persistent storage across sessions.HTTP request timeout in seconds for token requests.
Maximum number of retry attempts for failed token requests. Retries use exponential backoff with jitter.
Number of seconds before token expiry to proactively refresh. Prevents requests with nearly-expired tokens.
Optional custom HTTP client. If not provided, a new client is created and managed internally.
Methods
get_authorization_url()
Generates the Spotify authorization URL to redirect users for consent.state(str | None): Optional state parameter for CSRF protection. Recommended for security.scope(str | list[str] | tuple[str, …] | None): Optional scope override. Uses instance scope if not provided.show_dialog(bool): IfTrue, forces the user to approve the app even if previously authorized.
str - Authorization URL to redirect the user to
parse_response_url()
Parses the OAuth callback URL to extract the authorization code.url(str): The full callback URL or just the query string.expected_state(str | None): Expected state value for verification. RaisesAuthenticationErrorif mismatch.
str - Authorization code
Raises: AuthenticationError if the response contains an error or state mismatch
exchange_code()
Exchanges an authorization code for access and refresh tokens.code(str): Authorization code from the callback URL.
TokenInfo - Token information with access token, refresh token, and expiry
get_access_token()
Returns a valid access token, automatically refreshing if needed.str - A valid access token
Raises: AuthenticationError if no authorization token is available
close()
Closes the HTTP client and releases resources.Basic Usage with Local Helper
The simplest way to authorize users locally using theauthorize_local() helper:
Local Authorization Helper
authorize_local()
Convenience function for local authorization flows. Opens the user’s browser, runs a temporary callback server, and exchanges the code automatically.auth(AuthorizationCode): The authorization code instance.state(str | None): Optional state for CSRF protection. Auto-generated if not provided.show_dialog(bool): Force user approval dialog.timeout(float): Seconds to wait for callback. Default 300 (5 minutes).open_browser(bool): Automatically open browser. DefaultTrue.authorization_url_handler(Callable[[str], None] | None): Optional callback to handle the authorization URL (e.g., print it).
TokenInfo - Token information
Raises:
RuntimeErrorif called inside an async event loop (useasync_authorize_localinstead)ValueErrorif redirect URI is not a loopback address or missing portAuthenticationErrorif authorization fails or times out
Token Caching with FileTokenCache
Persist tokens across application restarts:Manual Authorization Flow
For web applications, implement the OAuth flow manually:Scopes
Request specific permissions using scopes:| Scope | Description |
|---|---|
user-read-private | Read user profile data |
user-read-email | Read user email address |
user-library-read | Read saved tracks and albums |
user-library-modify | Modify saved tracks and albums |
playlist-read-private | Read private playlists |
playlist-modify-public | Modify public playlists |
playlist-modify-private | Modify private playlists |
user-read-playback-state | Read playback state |
user-modify-playback-state | Control playback |
Async Support
Token Refresh Behavior
TheAuthorizationCode class automatically manages token lifecycle:
Retry Logic
Token requests automatically retry with exponential backoff on:- Connection errors and timeouts
- Server errors (5xx status codes)
- Initial delay: 0.5 seconds
- Maximum delay: 8.0 seconds
- Multiplier: 2x per retry
- Jitter: Random 0.5-1.0x variation
Error Handling
Complete Example from README
Full working example with all best practices:When to Use Authorization Code Flow
Use authorization code flow when:- Building user-facing applications
- Accessing user-specific endpoints (playlists, library, playback, etc.)
- You need to act on behalf of a user
- You require specific permission scopes
- Building web, mobile, or desktop applications
- You only need public catalog data
- Building backend services without user interaction
- You want to avoid user authorization flows
For app-only access without user interaction, use Client Credentials instead.
Environment Variables
The SDK recognizes these environment variables:| Variable | Description |
|---|---|
SPOTIFY_SDK_CLIENT_ID | Spotify application client ID |
SPOTIFY_SDK_CLIENT_SECRET | Spotify application client secret |
SPOTIFY_SDK_REDIRECT_URI | OAuth redirect URI |
Related Classes
TokenInfo
Dataclass representing cached token information.FileTokenCache
JSON file-based token cache for persistence.path(str): File path for storing tokens. Defaults to.spotify_sdk_token.json. The file is created with0600permissions for security.
InMemoryTokenCache
Simple in-memory token cache (default, not persistent).Related
- Access Token Authentication - Simple direct token authentication
- Client Credentials Flow - App-only authentication
- Spotify Authorization Scopes - Available permission scopes
- Error Handling - Handling authentication errors