CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-spotipy

A light weight Python library for the Spotify Web API

Overview
Eval results
Files

client.mddocs/

Core API Client

The Spotify class is the main client providing access to all Spotify Web API endpoints. It handles authentication, rate limiting, pagination, and provides a comprehensive Python interface for all Spotify services.

Capabilities

Client Initialization

Initialize the Spotify client with various authentication and configuration options.

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.
        
        Args:
            auth (str, optional): Bearer token for authentication
            requests_session (bool or requests.Session): HTTP session configuration  
            client_credentials_manager: Deprecated, use auth_manager
            oauth_manager: Deprecated, use auth_manager
            auth_manager: Authentication manager instance
            proxies (dict, optional): Proxy configuration
            requests_timeout (int): Request timeout in seconds (default: 5)
            status_forcelist (list, optional): HTTP status codes to retry
            retries (int): Number of retries (default: 3) 
            status_retries (int): Status-specific retries (default: 3)
            backoff_factor (float): Backoff factor for retries (default: 0.3)
            language (str, optional): Language for responses
        """

Search Operations

Search across all Spotify content types with flexible filtering and pagination.

def search(self, q, limit=10, offset=0, type="track", market=None):
    """
    Search for content on Spotify.
    
    Args:
        q (str): Search query string
        limit (int): Number of results to return (1-50, default: 10)
        offset (int): Index of first result (default: 0)
        type (str): Content type - 'track', 'album', 'artist', 'playlist', 'show', 'episode', 'audiobook'
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Search results with paging information
    """

def search_markets(self, q, limit=10, offset=0, type="track", markets=None, total=None):
    """
    Search across multiple markets.
    
    Args:
        q (str): Search query string
        limit (int): Number of results per market (1-50, default: 10)
        offset (int): Index of first result (default: 0)
        type (str): Content type to search for
        markets (list, optional): List of market codes to search
        total (int, optional): Total number of results to collect
        
    Returns:
        dict: Aggregated search results across markets
    """

Track Operations

Access track information, audio features, and detailed audio analysis.

def track(self, track_id, market=None):
    """
    Get track information.
    
    Args:
        track_id (str): Spotify track ID or URI
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Track object with metadata
    """

def tracks(self, tracks, market=None):
    """
    Get multiple tracks.
    
    Args:
        tracks (list): List of track IDs or URIs (max 50)
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Tracks object containing list of track objects
    """

def audio_features(self, tracks=[]):
    """
    Get audio features for tracks.
    
    Args:
        tracks (list): List of track IDs or URIs (max 100)
        
    Returns:
        dict: Audio features objects with acousticness, danceability, energy, etc.
    """

def audio_analysis(self, track_id):
    """
    Get detailed audio analysis for a track.
    
    Args:
        track_id (str): Spotify track ID or URI
        
    Returns:
        dict: Detailed audio analysis with bars, beats, sections, segments, tatums
    """

Artist Operations

Access artist information, albums, top tracks, and related artists.

def artist(self, artist_id):
    """
    Get artist information.
    
    Args:
        artist_id (str): Spotify artist ID or URI
        
    Returns:
        dict: Artist object with metadata
    """

def artists(self, artists):
    """
    Get multiple artists.
    
    Args:
        artists (list): List of artist IDs or URIs (max 50)
        
    Returns:
        dict: Artists object containing list of artist objects
    """

def artist_albums(self, artist_id, album_type=None, country=None, limit=20, offset=0):
    """
    Get artist's albums.
    
    Args:
        artist_id (str): Spotify artist ID or URI
        album_type (str, optional): Filter by album type - 'album', 'single', 'appears_on', 'compilation'
        country (str, optional): ISO 3166-1 alpha-2 country code
        limit (int): Number of albums to return (1-50, default: 20)
        offset (int): Index of first album (default: 0)
        
    Returns:
        dict: Paging object of simplified album objects
    """

def artist_top_tracks(self, artist_id, country="US"):
    """
    Get artist's top tracks in a country.
    
    Args:
        artist_id (str): Spotify artist ID or URI
        country (str): ISO 3166-1 alpha-2 country code (default: "US")
        
    Returns:
        dict: Object containing list of track objects
    """

def artist_related_artists(self, artist_id):
    """
    Get artists similar to a given artist.
    
    Args:
        artist_id (str): Spotify artist ID or URI
        
    Returns:
        dict: Object containing list of artist objects (max 20)
    """

Album Operations

Access album information and track listings.

def album(self, album_id, market=None):
    """
    Get album information.
    
    Args:
        album_id (str): Spotify album ID or URI
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Album object with metadata and tracks
    """

def albums(self, albums, market=None):
    """
    Get multiple albums.
    
    Args:
        albums (list): List of album IDs or URIs (max 20)
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Albums object containing list of album objects
    """

def album_tracks(self, album_id, limit=50, offset=0, market=None):
    """
    Get tracks from an album.
    
    Args:
        album_id (str): Spotify album ID or URI
        limit (int): Number of tracks to return (1-50, default: 50)
        offset (int): Index of first track (default: 0)
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Paging object of simplified track objects
    """

User Profile Operations

Access user profile information.

def user(self, user):
    """
    Get public profile information about a Spotify user.
    
    Args:
        user (str): Spotify user ID
        
    Returns:
        dict: User profile object
    """

def me(self):
    """
    Get detailed profile information about the current user.
    
    Returns:
        dict: Current user profile object with private information
    """

def current_user(self):
    """
    Alias for me(). Get current user profile.
    
    Returns:
        dict: Current user profile object
    """

Pagination Utilities

Navigate through paginated results from API responses.

def next(self, result):
    """
    Get next page of results.
    
    Args:
        result (dict): Previous result object with paging information
        
    Returns:
        dict: Next page of results, or None if no more pages
    """

def previous(self, result):
    """
    Get previous page of results.
    
    Args:
        result (dict): Current result object with paging information
        
    Returns:
        dict: Previous page of results, or None if at first page
    """

Market Information

Access available markets and country codes.

def available_markets(self):
    """
    Get list of markets where Spotify is available.
    
    Returns:
        dict: Object containing list of available market codes
    """

Usage Examples

Basic Search and Track Information

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())

# Search for tracks
results = sp.search(q='artist:radiohead track:creep', type='track', limit=1)
track = results['tracks']['items'][0]

# Get detailed track information
track_details = sp.track(track['id'])
print(f"Track: {track_details['name']}")
print(f"Album: {track_details['album']['name']}")
print(f"Artists: {', '.join([artist['name'] for artist in track_details['artists']])}")

# Get audio features
features = sp.audio_features([track['id']])[0]
print(f"Danceability: {features['danceability']}")
print(f"Energy: {features['energy']}")
print(f"Valence: {features['valence']}")

Artist Exploration

# Search for artist
results = sp.search(q='radiohead', type='artist', limit=1)
artist = results['artists']['items'][0]

# Get artist's albums
albums = sp.artist_albums(artist['id'], album_type='album', limit=10)
print(f"Albums by {artist['name']}:")
for album in albums['items']:
    print(f"  {album['name']} ({album['release_date'][:4]})")

# Get top tracks
top_tracks = sp.artist_top_tracks(artist['id'], country='US')
print(f"\\nTop tracks:")
for track in top_tracks['tracks'][:5]:
    print(f"  {track['name']}")

# Find related artists
related = sp.artist_related_artists(artist['id'])
print(f"\\nRelated artists:")
for artist in related['artists'][:5]:
    print(f"  {artist['name']}")

Multi-Market Search

# Search across multiple markets
markets = ['US', 'GB', 'CA', 'AU']
results = sp.search_markets(
    q='taylor swift', 
    type='album', 
    markets=markets, 
    limit=5,
    total=20
)

for market, market_results in results.items():
    print(f"Results for {market}:")
    for album in market_results['albums']['items']:
        print(f"  {album['name']} - Available: {market in album['available_markets']}")

Error Handling

The client automatically handles rate limiting with exponential backoff and retry logic. Authentication errors, network issues, and API errors are raised as appropriate exceptions:

from spotipy.exceptions import SpotifyException

try:
    track = sp.track('invalid_track_id')
except SpotifyException as e:
    print(f"Spotify API Error: {e.http_status} - {e.msg}")
    if e.http_status == 429:  # Rate limited
        retry_after = e.headers.get('Retry-After', 1)
        print(f"Rate limited. Retry after {retry_after} seconds")

Install with Tessl CLI

npx tessl i tessl/pypi-spotipy

docs

authentication.md

browse.md

cache.md

client.md

index.md

playback.md

playlists.md

podcasts.md

user-library.md

tile.json