SpotifyWebAPIClient

class minim.api.spotify.SpotifyWebAPIClient(*, auth_flow: str, client_id: str | None = None, client_secret: str | None = None, user_identifier: str | None = None, redirect_uri: str | None = None, scopes: str | Collection[str] = '', access_token: str | None = None, refresh_token: str | None = None, expires_at: str | datetime | None = None, redirect_handler: str | None = None, open_browser: bool = False, enable_cache: bool = True, store_tokens: bool = True, user_agent: str | None = None)[source]

Bases: OAuth2APIClient

Spotify Web API client.

Subscription

Spotify Premium

Use the Spotify Web API with a Development Mode app. Learn more.

Parameters:
auth_flowstr; keyword-only

Authorization flow.

Valid values:

  • "auth_code" – Authorization Code Flow.

  • "pkce" – Authorization Code Flow with Proof Key for Code Exchange (PKCE).

  • "client_credentials" – Client Credentials Flow.

client_idstr; keyword-only; optional

Client ID. Required unless set as system environment variable SPOTIFY_WEB_API_CLIENT_ID or stored in the local token storage.

client_secretstr; keyword-only; optional

Client secret. Required for the Authorization Code and Client Credentials flows unless set as system environment variable SPOTIFY_WEB_API_CLIENT_SECRET or stored in the local token storage.

user_identifierstr; keyword-only; optional

Identifier for the user account. Used when store_tokens=True to distinguish between multiple accounts for the same client ID and authorization flow.

If specified, it is used with the client ID and authorization flow to locate a matching stored token. If none is found, a new token is obtained and stored under this identifier.

If not specified, the most recently accessed token for the client ID and authorization flow is used. If none exists, a new token is obtained and stored using the Spotify user ID acquired from a successful authorization.

Prefixing the identifier with a tilde (~) bypasses token retrieval, forces reauthorization, and stores the new token under the suffix.

redirect_uristr; keyword-only; optional

Redirect URI. Required for the Authorization Code and Authorization Code with PKCE flows.

scopesstr or Collection[str]; keyword-only; optional

Authorization scopes requested by the client to access user resources.

See also

resolve_scopes() – Resolve scope categories and/or substrings into a set of scopes.

access_tokenstr; keyword-only; optional

Access token. If provided, the authorization process is bypassed, and automatic token refresh is enabled when relevant metadata (refresh token, expiry, etc.) is also supplied.

refresh_tokenstr; keyword-only; optional

Refresh token for renewing the access token. If not provided, the user will be reauthorized via the specified authorization flow when the access token expires.

expires_atstr or datetime.datetime; keyword-only; optional

Expiration time of the access token. If a string, it must be in ISO 8601 format (%Y-%m-%dT%H:%M:%SZ).

redirect_handlerstr or None; keyword-only; optional

Backend for handling redirects during the authorization flow. Redirect handling is only available for hosts localhost, 127.0.0.1, or ::1.

Valid values:

  • None – Show authorization URL in and have the user manually paste the redirect URL into the terminal.

  • "http.server" – Run a HTTP server to intercept the redirect after user authorization in any local browser.

  • "playwright" – Use a Playwright Firefox browser to complete the user authorization.

open_browserbool; keyword-only; default: False

Whether to automatically open the authorization URL in the default web browser for the Authorization Code and Authorization Code with PKCE flows. If False, the URL is printed to the terminal.

enable_cachebool; keyword-only; default: True

Whether to enable an in-memory time-to-live (TTL) cache with a least recently used (LRU) eviction policy for this client. If True, responses from semi-static endpoints are cached for one minute to one day, depending on their expected update frequency.

See also

clear_cache() – Clear specific or all cache entries for this client.

store_tokensbool; keyword-only; default: True

Whether to enable the local token storage for this client. If True, existing access tokens are retrieved when found in local storage, and newly acquired tokens and their metadata are stored for future retrieval. If False, the client neither retrieves nor stores access tokens.

See also

get_tokens() – Retrieve specific or all stored access tokens for this client.

remove_tokens() – Remove specific or all stored access tokens for this client.

user_agentstr; keyword-only; optional

User-Agent value to include in the headers of HTTP requests.

Methods

clear_cache

Clear specific or all cache entries for this client.

close

Terminate the underlying HTTP client session.

get_tokens

Retrieve specific or all access tokens and their metadata for this client from local storage.

open

Initialize a new HTTP client session.

remove_tokens

Remove specific or all access tokens and their metadata for this client from local storage.

resolve_scopes

Resolve one or more scope categories or substrings into a set of scopes.

set_access_token

Set or update the access token and its related metadata.

set_auth_flow

Set or update the authorization flow and related parameters.

set_cache_enabled

Enable or disable the in-memory TTL cache for this client.

Attributes

albums

Albums API endpoints for the Spotify Web API.

artists

Artists API endpoints for the Spotify Web API.

audiobooks

Audiobooks API endpoints for the Spotify Web API.

categories

Categories API endpoints for the Spotify Web API.

chapters

Chapters API endpoints for the Spotify Web API.

episodes

Episodes API endpoints for the Spotify Web API.

genres

Genres API endpoints for the Spotify Web API.

library

Library API endpoints for the Spotify Web API.

markets

Markets API endpoints for the Spotify Web API.

player

Player API endpoints for the Spotify Web API.

playlists

Playlists API endpoints for the Spotify Web API.

search

Search API endpoints for the Spotify Web API.

shows

Shows API endpoints for the Spotify Web API.

tracks

Tracks API endpoints for the Spotify Web API.

users

Users API endpoints for the Spotify Web API.

AUTH_URL

Authorization endpoint.

BASE_URL

Base URL for API endpoints.

DEVICE_AUTH_URL

Device authorization endpoint.

TOKEN_URL

Token endpoint.

AUTH_URL = 'https://accounts.spotify.com/authorize'

Authorization endpoint.

BASE_URL = 'https://api.spotify.com/v1'

Base URL for API endpoints.

DEVICE_AUTH_URL = None

Device authorization endpoint.

TOKEN_URL = 'https://accounts.spotify.com/api/token'

Token endpoint.

albums: AlbumsAPI

Albums API endpoints for the Spotify Web API.

artists: ArtistsAPI

Artists API endpoints for the Spotify Web API.

audiobooks: AudiobooksAPI

Audiobooks API endpoints for the Spotify Web API.

categories: CategoriesAPI

Categories API endpoints for the Spotify Web API.

chapters: ChaptersAPI

Chapters API endpoints for the Spotify Web API.

clear_cache(endpoint_methods: str | Callable[..., Any] | Collection[str | Callable[..., Any]] | None = None, /) None

Clear specific or all cache entries for this client.

Warning

If endpoint_methods is not provided, all cache entries are cleared.

Parameters:
endpoint_methodsstr, Callable, or Collection[str | Callable]; positional-only; optional

Endpoint methods whose cache entries should be cleared.

close() None

Terminate the underlying HTTP client session.

episodes: EpisodesAPI

Episodes API endpoints for the Spotify Web API.

genres: GenresAPI

Genres API endpoints for the Spotify Web API.

classmethod get_tokens(*, auth_flows: str | Collection[str] | None = None, client_ids: str | Collection[str] | None = None, user_identifiers: str | Collection[str] | None = None) list[dict[str, Any]] | None

Retrieve specific or all access tokens and their metadata for this client from local storage.

Parameters:
auth_flowsstr or Collection[str]; keyword-only; optional

Authorization flows.

client_idsstr or Collection[str]; keyword-only; optional

Client IDs.

user_identifiersstr or Collection[str]; keyword-only; optional

Identifiers for the user accounts.

library: LibraryAPI

Library API endpoints for the Spotify Web API.

markets: MarketsAPI

Markets API endpoints for the Spotify Web API.

open() None

Initialize a new HTTP client session.

player: PlayerAPI

Player API endpoints for the Spotify Web API.

playlists: PlaylistsAPI

Playlists API endpoints for the Spotify Web API.

classmethod remove_tokens(*, auth_flows: str | Collection[str] | None = None, client_ids: str | Collection[str] | None = None, user_identifiers: str | Collection[str] | None = None) None

Remove specific or all access tokens and their metadata for this client from local storage.

Warning

If none of auth_flows, client_ids, or user_identifiers are provided, all tokens for this client will be removed from local storage.

Parameters:
auth_flowsstr or Collection[str]; keyword-only; optional

Authorization flows.

client_idsstr or Collection[str]; keyword-only; optional

Client IDs.

user_identifiersstr or Collection[str]; keyword-only; optional

Identifiers for the user accounts.

classmethod resolve_scopes(matches: str | Collection[str] | None = None) set[str][source]

Resolve one or more scope categories or substrings into a set of scopes.

Parameters:
matchesstr or Collection[str]; optional

Categories and/or substrings to filter scopes by. If not specified, all available scopes are returned.

Valid values:

  • "images" – Scopes related to custom images, such as ugc-image-upload.

  • "spotify_connect" – Scopes related to Spotify Connect, such as

    • user-read-playback-state,

    • user-modify-playback-state, and

    • user-read-currently-playing.

  • "playback" – Scopes related to playback control, such as app-remote-control and streaming.

  • "playlists" – Scopes related to playlists, such as

    • playlist-read-private,

    • playlist-read-collaborative,

    • playlist-modify-private, and

    • playlist-modify-public.

  • "follow" – Scopes related to followed artists and users, such as user-follow-modify and user-follow-read.

  • "listening_history" – Scopes related to playback history, such as

    • user-read-playback-position,

    • user-top-read, and

    • user-read-recently-played.

  • "library" – Scopes related to saved content, such as user-library-modify and user-library-read.

  • "users" – Scopes related to user information, such as user-read-email and user-read-private.

  • None for all scopes above.

  • A substring to match in the available scopes.

    • "read" – All scopes above that grant read access, i.e., scopes with read in the name.

    • "modify" – All scopes above that grant modify access, i.e., scopes with modify in the name.

    • "user" – All scopes above that grant access to all user-related information, i.e., scopes with user in the name.

Returns:
scopesset[str]

Authorization scopes.

search: SearchAPI

Search API endpoints for the Spotify Web API.

set_access_token(access_token: str | None, /, token_type: str | None = 'Bearer', *, refresh_token: str | None = None, expires_at: str | datetime | None = None) None

Set or update the access token and its related metadata.

Warning

Calling this method replaces all existing values with the provided parameters. Parameters not provided explicitly will be overwritten by their default values.

Parameters:
access_tokenstr or None; positional-only

Access token.

Important

If the access token was acquired via a different authorization flow or client, call set_auth_flow() first to ensure that all other relevant authorization parameters are set correctly.

token_typestr or None; default: "Bearer"

Type of the access token.

refresh_tokenstr; keyword-only; optional

Refresh token for renewing the access token. If not provided, the user will be reauthorized via the current authorization flow when the access token expires.

expires_atstr or datetime.datetime; keyword-only; optional

Expiration time of the access token. If a string, it must be in ISO 8601 format (%Y-%m-%dT%H:%M:%SZ).

set_auth_flow(auth_flow: str | None, /, *, client_id: str | None = None, client_secret: str | None = None, user_identifier: str | None = None, redirect_uri: str | None = None, scopes: str | Collection[str] = '', redirect_handler: str | None = None, open_browser: bool = False, store_tokens: bool = True, authenticate: bool = True) None

Set or update the authorization flow and related parameters.

Warning

Calling this method replaces all existing values with the provided parameters. Parameters not provided explicitly will be overwritten by their default values.

Parameters:
auth_flowstr or None; keyword-only

Authorization flow.

Valid values:

  • None – No authentication.

  • "auth_code" – Authorization Code Flow.

  • "pkce" – Authorization Code Flow with Proof Key for Code Exchange (PKCE).

  • "client_credentials" – Client Credentials Flow.

  • "device" – Device Authorization Flow.

  • "implicit" – Implicit Grant Flow.

client_idstr; keyword-only; optional

Client ID. Required unless set as a system environment variable.

client_secretstr; keyword-only; optional

Client secret. Required for the Authorization Code, Client Credentials, and Resource Owner Password Credential flows unless set as a system environment variable.

user_identifierstr; keyword-only; optional

Identifier for the user account. Used when store_tokens=True to distinguish between multiple accounts for the same client ID and authorization flow.

If specified, it is used with the client ID and authorization flow to locate a matching stored token. If none is found, a new token is obtained and stored under this identifier.

If not specified, the most recently accessed token for the client ID and authorization flow is used. If none exists, a new token is obtained and stored using a user identifier (e.g., user ID) acquired from a successful authorization.

Prefixing the identifier with a tilde (~) bypasses token retrieval, forces reauthorization, and stores the new token under the suffix.

redirect_uristr; keyword-only; optional

Redirect URI. Required for the Authorization Code, Authorization Code with PKCE, and Implicit Grant flows.

scopesstr or Collection[str]; keyword-only; optional

Authorization scopes requested by the client to access user resources.

redirect_handlerstr or None; keyword-only; optional

Backend for handling redirects during the authorization flow. Redirect handling is only available for hosts localhost, 127.0.0.1, or ::1.

Valid values:

  • None – Show authorization URL in and have the user manually paste the redirect URL into the terminal.

  • "http.server" – Run a HTTP server to intercept the redirect after user authorization in any local browser.

  • "playwright" – Use a Playwright Firefox browser to complete the user authorization.

open_browserbool; keyword-only; default: False

Whether to automatically open the authorization URL in the default web browser for the Authorization Code, Authorization Code with PKCE, and Implicit Grant flows. If False, the URL is printed to the terminal.

store_tokensbool; keyword-only; default: True

Whether to enable the local token storage for this client. If True, existing access tokens are retrieved when found in local storage, and newly acquired tokens and their metadata are stored for future retrieval. If False, the client neither retrieves nor stores access tokens.

See also

get_tokens() – Retrieve specific or all stored access tokens for this client.

remove_tokens() – Remove specific or all stored access tokens for this client.

authenticatebool; keyword-only; default: True

Whether to immediately initiate the authorization flow to acquire an access token.

Important

Unless set_access_token() is called immediately after, this should be left as True to ensure the client’s existing token is compatible with the new authorization flow and/or scopes.

set_cache_enabled(enable: bool, /) None

Enable or disable the in-memory TTL cache for this client.

Parameters:
enablebool; positional-only

Whether to enable the cache.

shows: ShowsAPI

Shows API endpoints for the Spotify Web API.

tracks: TracksAPI

Tracks API endpoints for the Spotify Web API.

users: UsersAPI

Users API endpoints for the Spotify Web API.