Skip to content

Instantly share code, notes, and snippets.

@lfzawacki
Created October 8, 2025 02:03
Show Gist options
  • Select an option

  • Save lfzawacki/f43c39a9b0046c8175c21c8231d0bfd2 to your computer and use it in GitHub Desktop.

Select an option

Save lfzawacki/f43c39a9b0046c8175c21c8231d0bfd2 to your computer and use it in GitHub Desktop.
Download playlist metadata from spotify
import os
import json
import spotipy
from spotipy.oauth2 import SpotifyOAuth
# ---------- CONFIG ----------
CLIENT_ID = os.environ["SPOTIFY_CLIENT_ID"]
CLIENT_SECRET = os.environ["SPOTIFY_CLIENT_SECRET"]
REDIRECT_URI = os.environ.get("SPOTIFY_REDIRECT_URL", "http://localhost:8888/callback")
PLAYLIST_ID = "spotify:playlist:0Acu6f3Pcr0cJRUVqXTQ8b" # or just the ID part
OUTPUT_FILE = "playlist_albums.json"
# ----------------------------
scope = "playlist-read-private playlist-read-collaborative"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=scope,
))
def get_playlist_tracks(playlist_id):
"""Fetch every track from a playlist (handles pagination)."""
results = sp.playlist_items(playlist_id, additional_types=["track"])
tracks = results["items"]
while results["next"]:
results = sp.next(results)
tracks.extend(results["items"])
return tracks
def extract_album_metadata(tracks):
"""
Given a list of playlist tracks, extract album and track metadata.
Skips any entries where album info is missing or album_type is None.
"""
albums = []
for item in tracks:
track = item.get("track")
if not track:
continue
album = track.get("album")
if not album or album.get("album_type") is None:
# Skip tracks without a proper album entry
continue
albums.append({
"album_name": album.get("name"),
"album_id": album.get("id"),
"album_type": album.get("album_type"),
"release_date": album.get("release_date"),
"total_tracks": album.get("total_tracks"),
"artists": [a["name"] for a in album.get("artists", [])],
"spotify_url": album.get("external_urls", {}).get("spotify"),
"track_name": track.get("name"),
"track_id": track.get("id"),
"track_number": track.get("track_number"),
"duration_ms": track.get("duration_ms"),
})
return albums
def main():
tracks = get_playlist_tracks(PLAYLIST_ID)
albums = extract_album_metadata(tracks)
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
json.dump(albums, f, indent=2, ensure_ascii=False)
print(f"✅ Saved {len(albums)} entries to {OUTPUT_FILE}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment