A light weight Python library for the Spotify Web API
npx @tessl/cli install tessl/pypi-spotipy@2.25.0A lightweight Python library for the Spotify Web API that provides comprehensive access to all Spotify endpoints. Spotipy handles authentication, rate limiting, and provides a clean Pythonic interface for integrating Spotify's music data and services into applications.
pip install spotipyimport spotipy
from spotipy.oauth2 import SpotifyClientCredentials, SpotifyOAuthimport spotipy
from spotipy.oauth2 import SpotifyClientCredentials
# Initialize client
client_credentials_manager = SpotifyClientCredentials(
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET"
)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
# Search for tracks
results = sp.search(q='artist:radiohead', type='track', limit=10)
for track in results['tracks']['items']:
print(track['name'], '-', track['artists'][0]['name'])import spotipy
from spotipy.oauth2 import SpotifyOAuth
# Initialize with user authentication
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET",
redirect_uri="YOUR_REDIRECT_URI",
scope="user-library-read user-read-playback-state"
))
# Access user's saved tracks
results = sp.current_user_saved_tracks(limit=50)
for item in results['items']:
track = item['track']
print(f"{track['name']} by {track['artists'][0]['name']}")Spotipy follows a modular architecture with clear separation of concerns:
The main Spotify client providing access to all Spotify Web API endpoints including search, tracks, albums, artists, playlists, user data, and playback control.
class Spotify:
def __init__(self, auth=None, requests_session=True, client_credentials_manager=None,
oauth_manager=None, auth_manager=None, proxies=None, requests_timeout=5,
status_forcelist=None, retries=3, status_retries=3, backoff_factor=0.3,
language=None):
"""Initialize Spotify client with authentication and configuration."""
def search(self, q, limit=10, offset=0, type="track", market=None):
"""Search for tracks, albums, artists, playlists, shows, episodes, or audiobooks."""
def track(self, track_id, market=None):
"""Get Spotify track information."""
def album(self, album_id, market=None):
"""Get Spotify album information."""
def artist(self, artist_id):
"""Get Spotify artist information."""OAuth2 authentication flows for both app-only and user authentication scenarios, supporting multiple flow types with comprehensive token management.
class SpotifyClientCredentials:
def __init__(self, client_id=None, client_secret=None, proxies=None,
requests_session=True, requests_timeout=None, cache_handler=None):
"""Client Credentials flow for app-only authentication."""
class SpotifyOAuth:
def __init__(self, client_id=None, client_secret=None, redirect_uri=None,
state=None, scope=None, cache_path=None, username=None,
proxies=None, requests_session=True, show_dialog=False,
requests_timeout=None, open_browser=True, cache_handler=None):
"""Authorization Code flow for user authentication."""Manage user's saved content including tracks, albums, shows, episodes, followed artists, and personal profile information.
def current_user_saved_tracks(self, limit=20, offset=0, market=None):
"""Get user's saved tracks."""
def current_user_saved_albums(self, limit=20, offset=0, market=None):
"""Get user's saved albums."""
def current_user_followed_artists(self, limit=20, after=None):
"""Get user's followed artists."""
def me(self):
"""Get current user's profile."""Comprehensive playlist operations including creation, modification, track management, and collaboration features.
def playlist(self, playlist_id, fields=None, market=None, additional_types=("track",)):
"""Get playlist information."""
def playlist_add_items(self, playlist_id, items, position=None):
"""Add tracks or episodes to playlist."""
def playlist_change_details(self, playlist_id, name=None, public=None,
collaborative=None, description=None):
"""Change playlist details."""Control Spotify playback across user's devices including play/pause, track navigation, volume, and queue management.
def current_playback(self, market=None, additional_types=None):
"""Get current playback information."""
def start_playback(self, device_id=None, context_uri=None, uris=None,
offset=None, position_ms=None):
"""Start or resume playback."""
def pause_playback(self, device_id=None):
"""Pause playback."""Discovery features including featured playlists, new releases, categories, recommendations, and audio features analysis.
def featured_playlists(self, country=None, locale=None, timestamp=None,
limit=20, offset=0):
"""Get featured playlists."""
def recommendations(self, seed_artists=None, seed_genres=None, seed_tracks=None,
limit=20, country=None, **kwargs):
"""Get track recommendations."""
def audio_features(self, tracks=[]):
"""Get audio features for tracks."""Access podcast shows, episodes, and audiobook content with comprehensive metadata and user library integration.
def show(self, show_id, market=None):
"""Get show information."""
def episode(self, episode_id, market=None):
"""Get episode information."""
def get_audiobook(self, id, market=None):
"""Get audiobook information."""Token caching strategies and utility functions for efficient session management and scope handling.
class CacheFileHandler:
def __init__(self, cache_path=None, username=None, encoder_cls=None):
"""File-based token caching."""
class RedisCacheHandler:
def __init__(self, redis_instance=None, key=None, encoder_cls=None):
"""Redis-based token caching."""class SpotifyException(Exception):
def __init__(self, http_status, code, msg, reason=None, headers=None):
"""General Spotify API exception with HTTP status and error details."""
class SpotifyOauthError(Exception):
def __init__(self, message, error=None, error_description=None, *args, **kwargs):
"""OAuth-related authentication errors."""Common error scenarios include rate limiting (429), invalid tokens (401), insufficient scope permissions (403), and resource not found (404). All exceptions include detailed error information for debugging.