Skip to main content

Add your description here

Project description

Spotify SDK for Python

PyPI version Python versions Actions status License

A Python SDK for the Spotify Web API.

Note: This is an independent, community-developed library and is not affiliated with or endorsed by Spotify.

Features

  • Type-safe: Full type hints with Pydantic models for all API responses
  • Sync and async: Both synchronous and asynchronous client support
  • Automatic retries: Exponential backoff with jitter for rate limits and transient errors
  • Context managers: Clean resource management with with and async with support

Installation

pip install spotify-sdk

Or with uv:

uv add spotify-sdk

Requirements

  • Python 3.10+

Python version support follows the official Python release cycle. We support all versions that have not reached end-of-life.

Authentication

The SDK currently supports access token authentication. You'll need to obtain an access token through Spotify's authorization flows before using the SDK.

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

Additional authentication methods are planned for future releases.

Quick Start

from spotify_sdk import SpotifyClient

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

# Get an album
album = client.albums.get("4aawyAB9vmqN3uQ7FjRGTy")
print(album.name)  # "Global Warming"

# Get album tracks
tracks = client.albums.get_tracks(album.id)
for track in tracks.items:
    print(f"{track.track_number}. {track.name}")

client.close()

Using Context Managers

from spotify_sdk import SpotifyClient

with SpotifyClient(access_token="your-access-token") as client:
    album = client.albums.get("4aawyAB9vmqN3uQ7FjRGTy")
    print(album.name)

Async Support

import asyncio
from spotify_sdk import SpotifyClient

async def main():
    async with SpotifyClient(access_token="your-access-token") as client:
        album = await client.albums.get_async("4aawyAB9vmqN3uQ7FjRGTy")
        print(album.name)

        # Fetch multiple albums concurrently
        albums = await client.albums.get_several_async([
            "4aawyAB9vmqN3uQ7FjRGTy",
            "2noRn2Aes5aoNVsU6iWThc",
        ])
        for album in albums:
            print(album.name)

asyncio.run(main())

Services

Albums

# Get a single album
album = client.albums.get("album_id")
album = client.albums.get("album_id", market="US")

# Get multiple albums (up to 20)
albums = client.albums.get_several(["album_id_1", "album_id_2"])

# Get album tracks with pagination
tracks = client.albums.get_tracks("album_id", limit=10, offset=0)

Error Handling

The SDK raises specific exceptions for different error types:

from spotify_sdk import (
    SpotifyClient,
    AuthenticationError,
    BadRequestError,
    ForbiddenError,
    NotFoundError,
    RateLimitError,
    ServerError,
)

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 token: {e.message}")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ServerError as e:
    print(f"Spotify server error: {e.message}")

Exception Hierarchy

Exception HTTP Status Description
SpotifyError - Base exception for all SDK errors
AuthenticationError 401 Invalid or expired access token
BadRequestError 400 Invalid request parameters
ForbiddenError 403 Insufficient permissions
NotFoundError 404 Resource not found
RateLimitError 429 Rate limit exceeded
ServerError 5xx Spotify server error

Configuration

Client Options

client = SpotifyClient(
    access_token="your-access-token",
    timeout=30.0,      # Request timeout in seconds (default: 30.0)
    max_retries=3,     # Maximum retry attempts (default: 3)
)

Retry Behavior

The SDK automatically retries requests on:

  • Connection errors and timeouts
  • Rate limit responses (429) - respects Retry-After header
  • Server errors (5xx)

Retries use exponential backoff with jitter:

  • Initial delay: 0.5 seconds
  • Maximum delay: 8.0 seconds
  • Multiplier: 2x per retry

Models

All API responses are returned as Pydantic models with full type hints:

album = client.albums.get("album_id")

# Access typed attributes
print(album.name)           # str
print(album.release_date)   # str
print(album.total_tracks)   # int
print(album.artists)        # list[SimplifiedArtist]
print(album.images)         # list[Image]

# Models support forward compatibility
# Unknown fields from the API are preserved

Development

Clone the repository:

git clone https://github.com/jonathan343/spotify-sdk.git
cd spotify-sdk

Install dependencies with uv:

uv sync

Run tests:

uv run pytest

Run linting:

uv run ruff check .
uv run ruff format --check --preview .

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spotify_sdk-0.1.0.tar.gz (8.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

spotify_sdk-0.1.0-py3-none-any.whl (13.2 kB view details)

Uploaded Python 3

File details

Details for the file spotify_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: spotify_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 8.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for spotify_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d033b24c6be28852183c0932952430628febb6aca97db9b86de26714382501ad
MD5 dbd61c55abe34af8108311a6817b1076
BLAKE2b-256 09948b69e29b40a1f2b3ef6311e620ca1f26b844522baafd76dbd8c47684452e

See more details on using hashes here.

File details

Details for the file spotify_sdk-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: spotify_sdk-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 13.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for spotify_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1fff51b905943388765ca8e10e0a9037a79ae165c86a3ee907d4add80958b183
MD5 de735434ae8573b59e899588c7791ae5
BLAKE2b-256 c28d1431f3a962fed4044981df5b1fd015236dcea868eb20a8776ae68df868b5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page