Skip to main content

Overview

The Client Credentials flow is an OAuth 2.0 authentication method for server-to-server applications. It provides automatic token management and refresh, making it ideal for:
  • Backend services and APIs
  • Automated data pipelines
  • Applications that don’t require user-specific data
  • Long-running production applications
The Client Credentials flow provides app-level access only. It cannot access user-specific endpoints like playlists, library, or playback. For user authentication, use the Authorization Code flow.

Class: ClientCredentials

The ClientCredentials class implements the OAuth 2.0 client credentials grant type with automatic token caching and refresh.

Constructor

from spotify_sdk.auth import ClientCredentials

auth = ClientCredentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
    token_cache=None,
    timeout=30.0,
    max_retries=3,
    skew_seconds=30,
    http_client=None,
)

Parameters

client_id
str | None
default:"None"
Spotify application client ID. If not provided, reads from SPOTIFY_SDK_CLIENT_ID environment variable.
client_secret
str | None
default:"None"
Spotify application client secret. If not provided, reads from SPOTIFY_SDK_CLIENT_SECRET environment variable.
token_cache
TokenCache | None
default:"None"
Optional token cache for storing access tokens between requests. Defaults to InMemoryTokenCache(). Use FileTokenCache for persistent storage.
timeout
float
default:"30.0"
HTTP request timeout in seconds for token requests.
max_retries
int | None
default:"3"
Maximum number of retry attempts for failed token requests. Retries use exponential backoff with jitter.
skew_seconds
int
default:"30"
Number of seconds before token expiry to proactively refresh. Prevents requests with nearly-expired tokens.
http_client
httpx.Client | None
default:"None"
Optional custom HTTP client. If not provided, a new client is created and managed internally.

Methods

get_access_token()

Returns a valid access token, automatically fetching or refreshing as needed.
token = auth.get_access_token()
Returns: str - A valid access token

close()

Closes the HTTP client and releases resources.
auth.close()

Basic Usage

Using SpotifyClient.from_client_credentials()

The simplest way to use client credentials authentication:
from spotify_sdk import SpotifyClient

client = SpotifyClient.from_client_credentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
)

# Tokens are automatically managed
album = client.albums.get("5K79FLRUCSysQnVESLcTdb")
print(f"{album.name} by {album.artists[0].name}")

client.close()

Using Environment Variables

export SPOTIFY_SDK_CLIENT_ID="your-client-id"
export SPOTIFY_SDK_CLIENT_SECRET="your-client-secret"
from spotify_sdk import SpotifyClient

# Credentials automatically loaded from environment
client = SpotifyClient.from_client_credentials()

album = client.albums.get("4aawyAB9vmqN3uQ7FjRGTy")
print(album.name)

client.close()

Using Context Managers

from spotify_sdk import SpotifyClient

with SpotifyClient.from_client_credentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
) as client:
    albums = client.albums.get_several(["album_id_1", "album_id_2"])
    for album in albums:
        print(album.name)

Advanced Usage

Custom Auth Provider

For more control, create a ClientCredentials instance directly:
from spotify_sdk import SpotifyClient
from spotify_sdk.auth import ClientCredentials, FileTokenCache

auth = ClientCredentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
    token_cache=FileTokenCache(".cache/spotify-token.json"),
    timeout=60.0,
    max_retries=5,
)

client = SpotifyClient(auth_provider=auth)

try:
    album = client.albums.get("album_id_123")
    print(album.name)
finally:
    client.close()
    auth.close()

Persistent Token Caching

Use FileTokenCache to persist tokens across application restarts:
from spotify_sdk import SpotifyClient
from spotify_sdk.auth import ClientCredentials, FileTokenCache

auth = ClientCredentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
    token_cache=FileTokenCache(".cache/spotify-sdk/token.json"),
)

client = SpotifyClient(auth_provider=auth)

# First run: fetches new token
# Subsequent runs: uses cached token if not expired
album = client.albums.get("album_id_123")

client.close()
auth.close()

Async Support

import asyncio
from spotify_sdk import AsyncSpotifyClient

async def main():
    async with AsyncSpotifyClient.from_client_credentials(
        client_id="your-client-id",
        client_secret="your-client-secret",
    ) as client:
        album = await client.albums.get("4Uv86qWpGTxf7fU7lG5X6F")
        print(f"{album.name} by {album.artists[0].name}")

asyncio.run(main())

Token Refresh Behavior

The ClientCredentials class automatically handles token lifecycle:
1

Token Request

On first get_access_token() call, requests a new token from Spotify.
2

Caching

Stores the token and expiration time in the configured cache (in-memory by default).
3

Reuse

Subsequent calls return the cached token if it hasn’t expired.
4

Proactive Refresh

When the token is within skew_seconds (default 30) of expiring, automatically fetches a new token.

Retry Logic

Token requests automatically retry with exponential backoff on:
  • Connection errors and timeouts
  • Server errors (5xx status codes)
Retry configuration:
  • Initial delay: 0.5 seconds
  • Maximum delay: 8.0 seconds
  • Multiplier: 2x per retry
  • Jitter: Random 0.5-1.0x variation

Error Handling

from spotify_sdk import SpotifyClient
from spotify_sdk import AuthenticationError, SpotifyError

try:
    client = SpotifyClient.from_client_credentials(
        client_id="invalid-id",
        client_secret="invalid-secret",
    )
    album = client.albums.get("album_id_123")
except AuthenticationError as e:
    print(f"Authentication failed: {e.message}")
    print(f"Status code: {e.status_code}")
except SpotifyError as e:
    print(f"Request failed: {e.message}")
finally:
    if client:
        client.close()

When to Use Client Credentials

Use client credentials when:
  • Building backend services or APIs
  • Accessing public catalog data (albums, artists, tracks, etc.)
  • Running automated scripts or data pipelines
  • You don’t need user-specific data
  • You need automatic token refresh
Avoid client credentials when:
  • You need to access user-specific endpoints (playlists, library, playback, etc.)
  • Building user-facing applications that require user consent
  • You need user scopes or permissions
For user-specific endpoints, use the Authorization Code flow instead.

Environment Variables

The SDK recognizes these environment variables:
VariableDescription
SPOTIFY_SDK_CLIENT_IDSpotify application client ID
SPOTIFY_SDK_CLIENT_SECRETSpotify application client secret

InMemoryTokenCache

Simple in-memory token cache (default).
from spotify_sdk.auth import InMemoryTokenCache

cache = InMemoryTokenCache()

FileTokenCache

JSON file-based token cache for persistence.
from spotify_sdk.auth import FileTokenCache

cache = FileTokenCache(".cache/spotify-token.json")
Parameters:
  • path (str): File path for storing the token. Defaults to .spotify_sdk_token.json. The file is created with 0600 permissions.

Build docs developers (and LLMs) love