Authorization Reference

Authorization methods

class AuthCodeFlowManager(auth_settings: AuthSettings, access_token_info: AccessTokenInfo | None = None, allow_lazy_refresh: bool = False)

Bases: RefreshableAuthManager

Manager for Spotify OAuth2 Authorization Code Flow.

The authorization code flow is suitable for long-running applications (e.g. web and mobile apps) where the user grants permission only once.

This flow requires user interaction to grant permission and returns both an access token and a refresh token for long-term access. For more information refer to: Authorization Code Flow.

async authorize() None

Authorize using the Authorization Code Flow.

Initiates the authorization process by redirecting the user to Spotify’s authorization endpoint. The user grants permission, and the authorization code is exchanged for an access token and refresh token.

Returns:

None

Raises:

ValueError – If any required settings (client_id, client_secret, redirect_uri, scope) are not set.

async refresh() None

Refresh an expired access token.

Uses the stored refresh token to obtain a new access token without requiring the user to re-authenticate.

Returns:

None

Raises:

ValueError – If client_id or client_secret is not set or an access token data is not set.

class AuthCodePKCEFlowManager(auth_settings: AuthSettings, access_token_info: AccessTokenInfo | None = None, allow_lazy_refresh: bool = False)

Bases: RefreshableAuthManager

Manager for Spotify OAuth2 Authorization Code Flow with PKCE.

The Authorization Code Flow with PKCE (Proof Key for Code Exchange) is designed for public clients such as mobile and single-page applications where the client secret cannot be securely stored.

PKCE adds an extra layer of security by using dynamically generated code verifiers and challenges instead of relying on a static client secret. For more information refer to: Authorization Code with PKCE Flow.

async authorize() None

Authorize using the Authorization Code Flow with PKCE.

Initiates the authorization process by: 1. Generating a code verifier and challenge 2. Redirecting the user to Spotify’s authorization endpoint 3. Exchanging the authorization code for an access token

Returns:

None

Raises:

ValueError – If any required settings (client_id, redirect_uri, scope) are not set.

async refresh() None

Refresh an expired access token.

Uses the stored refresh token to obtain a new access token without requiring the user to re-authenticate.

Returns:

None

Raises:

ValueError – If client_id or an access token data is not set.

class ClientCredentialsFlowManager(auth_settings: AuthSettings, access_token_info: AccessTokenInfo | None = None)

Bases: AuthManagerBase

Manager for Spotify OAuth2 Client Credentials Flow.

The Client Credentials Flow is used by applications that need access to protected resources without user interaction. This flow is suitable for server-to-server interactions where user authentication is not required. For more information refer to: Client Credentials Flow.

async authorize() None

Authorize using the Client Credentials Flow.

Retrieves an access token using the application’s client ID and client secret. The access token can be used to make authenticated requests to the Spotify API.

Returns:

Object containing the access token and its metadata.

Raises:

ValueError – If client_id or client_secret is not set.

Authorization related models

class AccessTokenInfo(*, access_token: SecretStr, token_type: Literal['Bearer'], scope: str | None = None, expires_in: int, refresh_token: SecretStr | None = None, expires_at: datetime | None = None)

Bases: BaseModel

Model representing information about an access token.

classmethod load_token(file_path: Path) AccessTokenInfo

Loads the access token info from a file.

Parameters:

file_path – File location to load the access token from.

Returns:

Validated model instance.

dump_secret_value(secret_val: SecretStr) str

Dumps a secret value to plain str.

Parameters:

secret_val – Secret string.

Returns:

The same string in the plain-text form.

get_authorization_header() dict[str, str]

Return the Authorization header.

The header value is constructed as “{token_type} {access_token}”.

Returns:

Authorization header for API calls.

is_expired() bool

Checks if the token is expired.

Returns:

True if the token is expired, False otherwise.

Raises:

ValueError – If expires_at is not set.

model_post_init(context: Any, /) None

Set expires_at when not provided, assuming this is a new access token.

Parameters:

context – Model context.

Returns:

None

store_token(file_path: Path) None

Dumps the access token info into a file.

Parameters:

file_path – File location to save the access token at.

Returns:

None

access_token: SecretStr

An access token that can be provided in subsequent calls, for example to Spotify Web API services.

expires_at: datetime | None

Datetime object informing when the token expires.

expires_in: int

The time period (in seconds) for which the access token is valid.

refresh_token: SecretStr | None

A security credential that allows client applications to obtain new access tokens without requiring users to reauthorize the application.

scope: str | None

A space-separated list of scopes which have been granted for this access_token.

token_type: Literal['Bearer']

How the access token may be used (always Bearer).

class AccessTokenRequestBody(*, grant_type: str, code: str | None = None, redirect_uri: HttpUrl | None = None, client_id: SecretStr | None = None, code_verifier: str | None = None, refresh_token: SecretStr | None = None)

Bases: BaseModel

Body model for obtaining/refreshing an access token.

dump_secret_value(secret_val: SecretStr) str

Dumps a secret value to plain str.

Parameters:

secret_val – Secret string.

Returns:

The same string in the plain-text form.

client_id: SecretStr | None

The Client ID generated after registering your application.

code: str | None

The authorization code returned from the User Authorization request.

code_verifier: str | None

A code verifier matching the code challenge used to obtain the code

grant_type: str

A grant type.

redirect_uri: HttpUrl | None

This parameter is used for validation only.

refresh_token: SecretStr | None

The refresh token returned from the authorization token request.

class AuthCodeRequestParams(*, client_id: SecretStr, response_type: str, redirect_uri: HttpUrl, scope: str, code_challenge_method: str | None = None, code_challenge: str | None = None)

Bases: BaseModel

Params model for the User Authorization Request.

dump_secret_value(secret_val: SecretStr) str

Dumps a secret value to plain str.

Parameters:

secret_val – Secret string.

Returns:

The same string in the plain-text form.

client_id: SecretStr

The Client ID generated after registering your application.

code_challenge: str | None

Set to the code challenge that your app calculated based on the code verifier.

code_challenge_method: str | None

A code challenge method.

redirect_uri: HttpUrl

The URI to redirect to after the user grants or denies permission.

response_type: str

A response type.

scope: str

A space-separated list of scopes which have been granted for this access_token.

class AuthSettings(_case_sensitive: bool | None = None, _nested_model_default_partial_update: bool | None = None, _env_prefix: str | None = None, _env_prefix_target: EnvPrefixTarget | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_nested_max_split: int | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _cli_flag_prefix_char: str | None = None, _cli_implicit_flags: bool | Literal['dual', 'toggle'] | None = None, _cli_ignore_unknown_args: bool | None = None, _cli_kebab_case: bool | Literal['all', 'no_enums'] | None = None, _cli_shortcuts: Mapping[str, str | list[str]] | None = None, _secrets_dir: PathType | None = None, _build_sources: tuple[tuple[PydanticBaseSettingsSource, ...], dict[str, Any]] | None = None, *, client_id: SecretStr | None = None, client_secret: SecretStr | None = None, redirect_uri: HttpUrl | None = None, scope: str | None = None, store_access_token: bool = False, access_token_file_path: Annotated[Path, PathType(path_type=file)] | Annotated[Path, PathType(path_type=new)] = PosixPath('.token_info_cache'))

Bases: BaseSettings

Model representing the authorization settings based on contents of .env file or env variables.

The env variables shall start with spotantic_auth_. Mandatory variables depends on the authorization method.

get_basic_auth() BasicAuth

Create BasicAuth object for the current credentials.

Returns:

BasicAuth instance for current client_id and client_secret.

Raises:

ValueError – If client_id or client_secret is unknown.

access_token_file_path: Annotated[Path, PathType(path_type=file)] | Annotated[Path, PathType(path_type=new)]

File location to save the access token at.

client_id: SecretStr | None

The Client ID generated after registering your application.

client_secret: SecretStr | None

The Client Secret generated after registering your application.

redirect_uri: HttpUrl | None

The URI to redirect to after the user grants or denies permission.

scope: str | None

A space-separated list of scopes which have been granted for this access_token.

store_access_token: bool

If True, the access token information will be saved to access_token_file_path every time it is obtained.