Skip to main content
This guide will walk you through creating a Spotify client, authenticating, and making your first API request.

Prerequisites

Before you begin, make sure you have:
  1. Installed the SDK - See the installation guide if you haven’t already
  2. A Spotify access token - You’ll need credentials from the Spotify Developer Dashboard

Get your credentials

1

Create a Spotify app

Go to the Spotify Developer Dashboard and create a new app. This will give you a Client ID and Client Secret.
2

Choose an authentication method

The SDK supports multiple authentication methods:
  • Access token - Use an existing token (simplest for testing)
  • Client credentials - Automatic token management for app-only access
  • Authorization code - User-scoped access with refresh tokens
We’ll start with client credentials, which is the easiest for getting started.

Your first request

Let’s fetch an album from Spotify’s catalog:
1

Import the client

from spotify_sdk import SpotifyClient
2

Create a client with credentials

client = SpotifyClient.from_client_credentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
)
Store your credentials in environment variables instead of hardcoding them:
import os

client = SpotifyClient.from_client_credentials(
    client_id=os.getenv("SPOTIFY_CLIENT_ID"),
    client_secret=os.getenv("SPOTIFY_CLIENT_SECRET"),
)
3

Make your first API call

# Get an album
album = client.albums.get("4aawyAB9vmqN3uQ7FjRGTy")
print(f"{album.name} by {album.artists[0].name}")
# Output: "Global Warming by Pitbull"

# Access typed attributes
print(f"Released: {album.release_date}")
print(f"Total tracks: {album.total_tracks}")
All responses are fully typed Pydantic models, so you get autocomplete and type checking in your IDE.
4

Clean up resources

client.close()
Always close the client when you’re done to release network resources.

Using context managers

The recommended way to use the client is with a context manager, which automatically handles cleanup:
from spotify_sdk import SpotifyClient

with SpotifyClient.from_client_credentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
) as client:
    album = client.albums.get("4aawyAB9vmqN3uQ7FjRGTy")
    print(f"{album.name} by {album.artists[0].name}")

# Client is automatically closed when exiting the with block

Alternative authentication methods

Using an access token

If you already have an access token:
from spotify_sdk import SpotifyClient

client = SpotifyClient(access_token="your-access-token")

Using authorization code flow

For user-scoped endpoints that require specific permissions:
from spotify_sdk import SpotifyClient
from spotify_sdk.auth import AuthorizationCode, FileTokenCache

auth = AuthorizationCode(
    client_id="your-client-id",
    client_secret="your-client-secret",
    redirect_uri="http://127.0.0.1:8080/callback",
    scope=["user-read-private", "user-library-read"],
    token_cache=FileTokenCache(".cache/spotify-sdk/token.json"),
)

# Opens browser for authorization
auth.authorize_local()

client = SpotifyClient(auth_provider=auth)

Exploring album tracks

Let’s extend our example to fetch and display album tracks:
from spotify_sdk import SpotifyClient

with SpotifyClient.from_client_credentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
) as client:
    # Get album details
    album = client.albums.get("5K79FLRUCSysQnVESLcTdb")
    print(f"Album: {album.name}")
    print(f"Artist: {album.artists[0].name}")
    print(f"Release date: {album.release_date}\n")

    # Get album tracks
    tracks = client.albums.get_tracks(album.id, limit=10)
    print("Tracks:")
    for track in tracks.items:
        duration_min = track.duration_ms // 60000
        duration_sec = (track.duration_ms % 60000) // 1000
        print(f"{track.track_number}. {track.name} ({duration_min}:{duration_sec:02d})")

Error handling

The SDK provides specific exceptions for different error types:
from spotify_sdk import (
    SpotifyClient,
    NotFoundError,
    AuthenticationError,
    RateLimitError,
)

with SpotifyClient.from_client_credentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
) as client:
    try:
        album = client.albums.get("invalid_id")
    except NotFoundError as e:
        print(f"Album not found: {e.message}")
    except AuthenticationError as e:
        print(f"Invalid credentials: {e.message}")
    except RateLimitError as e:
        print(f"Rate limited. Retry after {e.retry_after} seconds")
The SDK automatically retries requests on rate limits (429), connection errors, and server errors (5xx) using exponential backoff with jitter. Most transient errors are handled without manual intervention.

Client configuration

You can customize the client’s behavior:
client = SpotifyClient.from_client_credentials(
    client_id="your-client-id",
    client_secret="your-client-secret",
    timeout=30.0,      # Request timeout in seconds (default: 30.0)
    max_retries=3,     # Maximum retry attempts (default: 3)
)

Next steps

You now know the basics of using the Spotify SDK. Here are some resources to continue learning:

Authentication

Learn about all authentication methods and token management

Albums

Explore the full albums API with examples

Search

Search across Spotify’s entire catalog

Error handling

Handle errors gracefully in production

Build docs developers (and LLMs) love