Skip to content

Instantly share code, notes, and snippets.

@julian-west
Last active December 20, 2024 08:29
Show Gist options
  • Save julian-west/b465261758198308a5262a40ed2cb78e to your computer and use it in GitHub Desktop.
Save julian-west/b465261758198308a5262a40ed2cb78e to your computer and use it in GitHub Desktop.
Extract track name and artist from a Spotify playlist to a csv file
"""Get song titles and artists from Spotify playlist"""
import csv
import os
import re
import spotipy
from dotenv import load_dotenv
from spotipy.oauth2 import SpotifyClientCredentials
# load credentials from .env file
load_dotenv()
CLIENT_ID = os.getenv("CLIENT_ID", "")
CLIENT_SECRET = os.getenv("CLIENT_SECRET", "")
OUTPUT_FILE_NAME = "track_info.csv"
# change for your target playlist
PLAYLIST_LINK = "https://open.spotify.com/playlist/6jAarBZaMmBLnSIeltPzkz?si=d42be5c6ec194bb9"
# authenticate
client_credentials_manager = SpotifyClientCredentials(
client_id=CLIENT_ID, client_secret=CLIENT_SECRET
)
# create spotify session object
session = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
# get uri from https link
if match := re.match(r"https://open.spotify.com/playlist/(.*)\?", PLAYLIST_LINK):
playlist_uri = match.groups()[0]
else:
raise ValueError("Expected format: https://open.spotify.com/playlist/...")
# get list of tracks in a given playlist (note: max playlist length 100)
tracks = session.playlist_tracks(playlist_uri)["items"]
# create csv file
with open(OUTPUT_FILE_NAME, "w", encoding="utf-8") as file:
writer = csv.writer(file)
# write header column names
writer.writerow(["track", "artist"])
# extract name and artist
for track in tracks:
name = track["track"]["name"]
artists = ", ".join(
[artist["name"] for artist in track["track"]["artists"]]
)
# write to csv
writer.writerow([name, artists])
@julian-west
Copy link
Author

I've just tested the script with the latest version of spotipy (2.24.0) and the script is working fine.

Your error suggests the the CLIENT_ID and CLIENT_SECRET variable values are being overwritten with an empty string.

You don't necessarily need to use a .env file but it is considered best practice as it avoids hard coding sensitive credentials in your python file.

But, if you have added CLIENT_ID and CLIENT_SECRET directly as hard coded values to the script, then make sure you have deleted lines 14 and 15 in the original script as these will overwrite the variables with an empty string if there is no environment variable present.

@cisko99za
Copy link

cisko99za commented Dec 17, 2024

i don't understand, sorry. i've replace on line 14 and 15 CLIENT_ID and CLIENT_SECRET with my value but get error:
spotipy.oauth2.SpotifyOauthError: No client_id. Pass it or set a SPOTIPY_CLIENT_ID environment variable
and i have latest spotipy 2.24.0 installed

@julian-west
Copy link
Author

It's kind of hard to debug without seeing your changes.

I would recommend deleting lines 14 and 15 and replacing with:

CLIENT_ID = 'your-value'
CLIENT_SECRET='your-secret-value'

Or look at the documentation for os.getenv to understand how that function works. You should put your value in the empty string (not replacing CLIENT_ID):

CLIENT_ID = os.getenv('CLIENT_ID', 'your-value')
CLIENT_SECRET = os.getenv('CLIENT_SECRET ', 'your-secret-value')

@cisko99za
Copy link

cisko99za commented Dec 17, 2024

work with first method CLIENT_ID = 'my-value' and CLIENT_SECRET='my-secret-value' on line 14-15
but work only with plist link into script. edit line 19 with my plist link get error:

spotipy.exceptions.SpotifyException: http status: 404, code:-1 - https://api.spotify.com/v1/playlists/37i9dQZF1E4kvm1VQNlpP6/tracks?limit=100&offset=0&additional_types=track:
Resource not found, reason: None

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment