from spotify_sdk.models.playlist import Playlist, PlaylistTrackfrom datetime import datetime# Parse a playlist from the API responseplaylist = Playlist(**api_response)print(f"Playlist: {playlist.name}")print(f"Owner: {playlist.owner.display_name}")print(f"Total tracks: {playlist.tracks.total}")print(f"Public: {'Yes' if playlist.public else 'No'}")print(f"Collaborative: {'Yes' if playlist.collaborative else 'No'}")# Iterate through tracksfor item in playlist.tracks.items: if item.track: # Track might be None if unavailable track = item.track print(f"\n{track.name} - {track.artists[0].name}") if item.added_at: print(f" Added: {item.added_at.strftime('%Y-%m-%d')}") if item.added_by: print(f" Added by: {item.added_by.display_name}")# Calculate total durationtotal_ms = sum( item.track.duration_ms for item in playlist.tracks.items if item.track)total_hours = total_ms / (1000 * 60 * 60)print(f"\nTotal duration: {total_hours:.1f} hours")
The snapshot_id is a version identifier that changes whenever the playlist is modified:
Adding or removing tracks changes the snapshot
Reordering tracks changes the snapshot
Changing playlist details (name, description) changes the snapshot
Use snapshot IDs to detect if a playlist has been modified:
# Store the snapshot IDold_snapshot = playlist.snapshot_id# Later, fetch the playlist againnew_playlist = Playlist(**api_response)if new_playlist.snapshot_id != old_snapshot: print("Playlist has been modified")
Show Handling Unavailable Tracks
Tracks in a playlist can become unavailable (removed from Spotify, region restrictions, etc.). In this case, track will be None:
Collaborative playlists allow multiple users to add and remove tracks:
collaborative = True: Multiple users can edit
collaborative = False: Only the owner can edit
Track who added what in collaborative playlists:
from collections import Countercontributors = Counter( item.added_by.display_name for item in playlist.tracks.items if item.added_by and item.added_by.display_name)print("Top contributors:")for user, count in contributors.most_common(5): print(f" {user}: {count} tracks")