CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-spotipy

A light weight Python library for the Spotify Web API

Overview
Eval results
Files

user-library.mddocs/

User Library and Profile

Manage the authenticated user's personal library including saved tracks, albums, shows, episodes, followed artists, and profile information. All operations require appropriate OAuth scopes.

Capabilities

User Profile Information

Access current user's profile data and public user information.

def me(self):
    """
    Get detailed profile information about the current user.
    
    Requires scope: user-read-private, user-read-email
    
    Returns:
        dict: User profile with id, display_name, email, followers, images, etc.
    """

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

def user(self, user):
    """
    Get public profile information about any Spotify user.
    
    Args:
        user (str): Spotify user ID
        
    Returns:
        dict: Public user profile with id, display_name, followers, images
    """

Saved Tracks

Manage the user's saved tracks library.

def current_user_saved_tracks(self, limit=20, offset=0, market=None):
    """
    Get user's saved tracks.
    
    Requires scope: user-library-read
    
    Args:
        limit (int): Number of tracks to return (1-50, default: 20)
        offset (int): Index of first track (default: 0)
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Paging object of saved track objects with added_at timestamps
    """

def current_user_saved_tracks_add(self, tracks=None):
    """
    Save tracks to user's library.
    
    Requires scope: user-library-modify
    
    Args:
        tracks (list): List of track IDs or URIs (max 50)
        
    Returns:
        None
    """

def current_user_saved_tracks_delete(self, tracks=None):
    """
    Remove tracks from user's library.
    
    Requires scope: user-library-modify
    
    Args:
        tracks (list): List of track IDs or URIs (max 50)
        
    Returns:
        None
    """

def current_user_saved_tracks_contains(self, tracks=None):
    """
    Check if tracks are saved in user's library.
    
    Requires scope: user-library-read
    
    Args:
        tracks (list): List of track IDs or URIs (max 50)
        
    Returns:
        list: Boolean list indicating which tracks are saved
    """

Saved Albums

Manage the user's saved albums library.

def current_user_saved_albums(self, limit=20, offset=0, market=None):
    """
    Get user's saved albums.
    
    Requires scope: user-library-read
    
    Args:
        limit (int): Number of albums to return (1-50, default: 20)
        offset (int): Index of first album (default: 0)
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Paging object of saved album objects with added_at timestamps
    """

def current_user_saved_albums_add(self, albums=[]):
    """
    Save albums to user's library.
    
    Requires scope: user-library-modify
    
    Args:
        albums (list): List of album IDs or URIs (max 50)
        
    Returns:
        None
    """

def current_user_saved_albums_delete(self, albums=[]):
    """
    Remove albums from user's library.
    
    Requires scope: user-library-modify
    
    Args:
        albums (list): List of album IDs or URIs (max 50)
        
    Returns:
        None
    """

def current_user_saved_albums_contains(self, albums=[]):
    """
    Check if albums are saved in user's library.
    
    Requires scope: user-library-read
    
    Args:
        albums (list): List of album IDs or URIs (max 50)
        
    Returns:
        list: Boolean list indicating which albums are saved
    """

Saved Episodes

Manage the user's saved podcast episodes.

def current_user_saved_episodes(self, limit=20, offset=0, market=None):
    """
    Get user's saved episodes.
    
    Requires scope: user-library-read
    
    Args:
        limit (int): Number of episodes to return (1-50, default: 20)
        offset (int): Index of first episode (default: 0)
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Paging object of saved episode objects with added_at timestamps
    """

def current_user_saved_episodes_add(self, episodes=None):
    """
    Save episodes to user's library.
    
    Requires scope: user-library-modify
    
    Args:
        episodes (list): List of episode IDs or URIs (max 50)
        
    Returns:
        None
    """

def current_user_saved_episodes_delete(self, episodes=None):
    """
    Remove episodes from user's library.
    
    Requires scope: user-library-modify
    
    Args:
        episodes (list): List of episode IDs or URIs (max 50)
        
    Returns:
        None
    """

def current_user_saved_episodes_contains(self, episodes=None):
    """
    Check if episodes are saved in user's library.
    
    Requires scope: user-library-read
    
    Args:
        episodes (list): List of episode IDs or URIs (max 50)
        
    Returns:
        list: Boolean list indicating which episodes are saved
    """

Saved Shows

Manage the user's saved podcast shows.

def current_user_saved_shows(self, limit=20, offset=0, market=None):
    """
    Get user's saved shows.
    
    Requires scope: user-library-read
    
    Args:
        limit (int): Number of shows to return (1-50, default: 20)
        offset (int): Index of first show (default: 0)
        market (str, optional): ISO 3166-1 alpha-2 country code
        
    Returns:
        dict: Paging object of saved show objects with added_at timestamps
    """

def current_user_saved_shows_add(self, shows=[]):
    """
    Save shows to user's library.
    
    Requires scope: user-library-modify
    
    Args:
        shows (list): List of show IDs or URIs (max 50)
        
    Returns:
        None
    """

def current_user_saved_shows_delete(self, shows=[]):
    """
    Remove shows from user's library.
    
    Requires scope: user-library-modify
    
    Args:
        shows (list): List of show IDs or URIs (max 50)
        
    Returns:
        None
    """

def current_user_saved_shows_contains(self, shows=[]):
    """
    Check if shows are saved in user's library.
    
    Requires scope: user-library-read
    
    Args:
        shows (list): List of show IDs or URIs (max 50)
        
    Returns:
        list: Boolean list indicating which shows are saved
    """

Following Artists and Users

Manage following relationships with artists and other users.

def current_user_followed_artists(self, limit=20, after=None):
    """
    Get artists followed by the current user.
    
    Requires scope: user-follow-read
    
    Args:
        limit (int): Number of artists to return (1-50, default: 20)
        after (str, optional): Artist ID for pagination cursor
        
    Returns:
        dict: Cursor-based paging object of artist objects
    """

def current_user_following_artists(self, ids=None):
    """
    Check if current user follows specific artists.
    
    Requires scope: user-follow-read
    
    Args:
        ids (list): List of artist IDs (max 50)
        
    Returns:
        list: Boolean list indicating which artists are followed
    """

def current_user_following_users(self, ids=None):
    """
    Check if current user follows specific users.
    
    Requires scope: user-follow-read
    
    Args:
        ids (list): List of user IDs (max 50)
        
    Returns:
        list: Boolean list indicating which users are followed
    """

def user_follow_artists(self, ids=[]):
    """
    Follow artists.
    
    Requires scope: user-follow-modify
    
    Args:
        ids (list): List of artist IDs to follow (max 50)
        
    Returns:
        None
    """

def user_follow_users(self, ids=[]):
    """
    Follow users.
    
    Requires scope: user-follow-modify
    
    Args:
        ids (list): List of user IDs to follow (max 50)
        
    Returns:
        None
    """

def user_unfollow_artists(self, ids=[]):
    """
    Unfollow artists.
    
    Requires scope: user-follow-modify
    
    Args:
        ids (list): List of artist IDs to unfollow (max 50)
        
    Returns:
        None
    """

def user_unfollow_users(self, ids=[]):
    """
    Unfollow users.
    
    Requires scope: user-follow-modify
    
    Args:
        ids (list): List of user IDs to unfollow (max 50)
        
    Returns:
        None
    """

Top Content

Access user's top artists and tracks based on listening history.

def current_user_top_artists(self, limit=20, offset=0, time_range="medium_term"):
    """
    Get user's top artists.
    
    Requires scope: user-top-read
    
    Args:
        limit (int): Number of artists to return (1-50, default: 20)
        offset (int): Index of first result (default: 0)
        time_range (str): Time period - 'short_term' (4 weeks), 'medium_term' (6 months), 'long_term' (years)
        
    Returns:
        dict: Paging object of artist objects
    """

def current_user_top_tracks(self, limit=20, offset=0, time_range="medium_term"):
    """
    Get user's top tracks.
    
    Requires scope: user-top-read
    
    Args:
        limit (int): Number of tracks to return (1-50, default: 20)
        offset (int): Index of first result (default: 0)
        time_range (str): Time period - 'short_term' (4 weeks), 'medium_term' (6 months), 'long_term' (years)
        
    Returns:
        dict: Paging object of track objects
    """

Recently Played

Access user's recently played tracks with timestamp information.

def current_user_recently_played(self, limit=50, after=None, before=None):
    """
    Get user's recently played tracks.
    
    Requires scope: user-read-recently-played
    
    Args:
        limit (int): Number of items to return (1-50, default: 50)
        after (int, optional): Unix timestamp in milliseconds - returns tracks played after this time
        before (int, optional): Unix timestamp in milliseconds - returns tracks played before this time
        
    Returns:
        dict: Cursor-based paging object of played track objects with context and played_at timestamp
    """

Usage Examples

Managing Saved Tracks

import spotipy
from spotipy.oauth2 import SpotifyOAuth

scope = "user-library-read user-library-modify"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

# Get saved tracks
saved_tracks = sp.current_user_saved_tracks(limit=50)
print(f"You have {saved_tracks['total']} saved tracks")

for item in saved_tracks['items']:
    track = item['track']
    added_at = item['added_at']
    print(f"Added {added_at[:10]}: {track['name']} by {track['artists'][0]['name']}")

# Save new tracks
track_ids = ['4iV5W9uYEdYUVa79Axb7Rh', '1301WleyT98MSxVHPZCA6M']  # Example track IDs
sp.current_user_saved_tracks_add(tracks=track_ids)
print("Tracks saved to library!")

# Check if specific tracks are saved
saved_status = sp.current_user_saved_tracks_contains(tracks=track_ids)
for track_id, is_saved in zip(track_ids, saved_status):
    print(f"Track {track_id}: {'Saved' if is_saved else 'Not saved'}")

Following Artists

scope = "user-follow-read user-follow-modify"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

# Get followed artists
followed = sp.current_user_followed_artists(limit=20)
print(f"Following {followed['artists']['total']} artists:")

for artist in followed['artists']['items']:
    print(f"  {artist['name']} ({artist['followers']['total']} followers)")

# Follow new artists
artist_ids = ['4Z8W4fKeB5YxbusRsdQVPb']  # Radiohead
sp.user_follow_artists(ids=artist_ids)
print("Now following Radiohead!")

# Check following status
following_status = sp.current_user_following_artists(ids=artist_ids)
print(f"Following Radiohead: {following_status[0]}")

User's Top Content

scope = "user-top-read"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

# Get top artists for different time ranges
time_ranges = ['short_term', 'medium_term', 'long_term']
time_labels = ['Last 4 weeks', 'Last 6 months', 'All time']

for time_range, label in zip(time_ranges, time_labels):
    print(f"\\nTop artists - {label}:")
    top_artists = sp.current_user_top_artists(limit=5, time_range=time_range)
    
    for i, artist in enumerate(top_artists['items'], 1):
        print(f"  {i}. {artist['name']} ({', '.join(artist['genres'][:2])})")

# Get top tracks
print("\\nTop tracks - Last 6 months:")
top_tracks = sp.current_user_top_tracks(limit=10, time_range='medium_term')

for i, track in enumerate(top_tracks['items'], 1):
    artist_names = ', '.join([artist['name'] for artist in track['artists']])
    print(f"  {i}. {track['name']} - {artist_names}")

Recently Played Analysis

import datetime
scope = "user-read-recently-played"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

# Get recently played tracks
recently_played = sp.current_user_recently_played(limit=50)

print("Recently played tracks:")
artist_counts = {}

for item in recently_played['items']:
    track = item['track']
    played_at = item['played_at']
    context = item.get('context', {})
    
    # Parse timestamp
    played_time = datetime.datetime.fromisoformat(played_at.replace('Z', '+00:00'))
    
    # Count artists
    artist_name = track['artists'][0]['name']
    artist_counts[artist_name] = artist_counts.get(artist_name, 0) + 1
    
    # Show context if available
    context_info = ""
    if context and context['type'] == 'playlist':
        context_info = f" (from playlist)"
    elif context and context['type'] == 'album':
        context_info = f" (from album)"
    
    print(f"  {played_time.strftime('%m/%d %H:%M')}: {track['name']} - {artist_name}{context_info}")

# Show most played artists
print("\\nMost played artists in recent history:")
for artist, count in sorted(artist_counts.items(), key=lambda x: x[1], reverse=True)[:5]:
    print(f"  {artist}: {count} plays")

User Profile Information

scope = "user-read-private user-read-email"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

# Get current user profile
user = sp.me()

print(f"User Profile:")
print(f"  Display Name: {user.get('display_name', 'Not set')}")
print(f"  Email: {user.get('email', 'Not available')}")
print(f"  Country: {user.get('country', 'Not available')}")
print(f"  Followers: {user['followers']['total']}")
print(f"  Subscription: {user.get('product', 'Not available')}")

if user.get('images'):
    print(f"  Profile Image: {user['images'][0]['url']}")

# Compare with another user's public profile
public_user = sp.user('spotify')  # Spotify's official account
print(f"\\nSpotify Official Account:")
print(f"  Display Name: {public_user['display_name']}")
print(f"  Followers: {public_user['followers']['total']}")

Required Scopes Summary

  • user-read-private: Access private user profile information
  • user-read-email: Access user's email address
  • user-library-read: Read user's saved content
  • user-library-modify: Modify user's saved content
  • user-follow-read: Read user's followed artists and users
  • user-follow-modify: Modify user's followed artists and users
  • user-top-read: Read user's top artists and tracks
  • user-read-recently-played: Read user's recently played tracks

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