đ Executive Summary
TL;DR: The article addresses the anxiety of losing Spotify playlists by providing a Python script solution. This script automates the process of fetching all user playlists and their tracks, then saving them into a structured JSON file for peace of mind and easy restoration.
đŻ Key Takeaways
- The
spotipylibrary, combined withpython-dotenv, is fundamental for interacting with the Spotify API and securely managing credentials. - Proper Spotify Developer App setup, including a Client ID, Client Secret, and a correctly configured
http://localhost:8888/callbackRedirect URI, is essential for successful OAuth 2.0 authentication. - Implementing pagination logic using
while results[ânextâ]:is critical to ensure all tracks from large playlists are retrieved, preventing incomplete backups.
Backup Spotify Playlists to a JSON File using Python
Alright, letâs talk about a practical problem that used to be a low-key source of anxiety for me. It wasnât a failing server or a deployment pipeline breaking at 3 AM. It was the thought of losing my meticulously curated âDeep Focus Codingâ playlist. Iâve spent years on that thing. One accidental click, a sync error, or an account issue, and it could all be gone.
Manually copying tracks is a non-starter for anyone with a busy schedule. So, like any good engineer, I automated the solution. I wrote a simple Python script that runs on a schedule, grabs all my playlists and their tracks, and dumps them into a clean JSON file. Itâs a âset it and forget itâ process that gives me total peace of mind. Today, Iâm going to walk you through how to build it.
Prerequisites
Before we dive in, make sure you have the following ready to go. This will save you a ton of time.
- Python 3.x installed on your machine.
- A Spotify Account: A free or premium account will work.
- Spotify Developer App Credentials: Youâll need a Client ID and a Client Secret. Weâll get these in Step 1.
-
The
spotipylibrary: This is the key Python library for interacting with the Spotify API. Iâll skip the standardvirtualenvsetup since you likely have your own workflow for that. Just make sure to install the necessary libraries in your environment. Youâll needspotipyandpython-dotenv. You can typically install them by runningpip install spotipy python-dotenvin your terminal.
The Guide: Step-by-Step
Step 1: Create a Spotify Developer App
First, we need to tell Spotify that our script is a legitimate application.
- Navigate to the Spotify Developer Dashboard and log in.
- Click âCreate Appâ.
- Give your app a name (e.g., âMy Playlist Backup Scriptâ) and a brief description.
- Once created, youâll see your Client ID and a button to show your Client Secret. Keep this page open; weâll need these in a moment.
- Now, click âEdit Settingsâ. In the âRedirect URIsâ section, add
http://localhost:8888/callback. This is critical. Itâs a local address the script will use to complete the authentication handshake. - Click âSaveâ at the bottom of the form.
Step 2: Secure Your Credentials
In my production setups, I never, ever hardcode secrets directly into a script. Itâs a massive security risk. Weâll use a configuration file to store our credentials and load them as environment variables.
Create a new file in your project directory named config.env (I prefer this over .env to avoid issues with some deployment tools). Add your credentials and your Spotify username to this file like so:
SPOTIPY_CLIENT_ID='YOUR_CLIENT_ID_HERE'
SPOTIPY_CLIENT_SECRET='YOUR_CLIENT_SECRET_HERE'
SPOTIPY_REDIRECT_URI='http://localhost:8888/callback'
SPOTIFY_USERNAME='YOUR_SPOTIFY_USERNAME'
Pro Tip: Your Spotify Username is not always your display name. To find it, go to your Spotify account page, and itâs often listed there as âUsernameâ. If you signed up with Facebook, it might be a string of numbers.
Step 3: The Python Script
Now for the fun part. Letâs write the Python code that does all the heavy lifting. Iâve added comments to explain the logic behind each block. The script will authenticate you, fetch all your playlists, loop through them to get every single track, and then save the entire structure to a file.
Create a file named backup\_playlists.py:
import os
import json
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from dotenv import load_dotenv
def backup_spotify_playlists():
# Load credentials from the config.env file
load_dotenv('config.env')
client_id = os.getenv('SPOTIPY_CLIENT_ID')
client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')
redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')
username = os.getenv('SPOTIFY_USERNAME')
# This scope allows us to read a user's private playlists.
scope = 'playlist-read-private'
# Authenticate with Spotify
# The first time you run this, it will open a browser window for you to log in
# and authorize the script. It will create a .cache file to store the token.
try:
auth_manager = SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
username=username
)
sp = spotipy.Spotify(auth_manager=auth_manager)
print("Authentication successful.")
except Exception as e:
print(f"Error during authentication: {e}")
return # Exit the function if authentication fails
# This dictionary will hold all our playlist data
all_playlists_data = {}
# Get the user's playlists
try:
playlists = sp.current_user_playlists()
except Exception as e:
print(f"Error fetching playlists: {e}")
return
# Loop through each playlist
for playlist in playlists['items']:
playlist_name = playlist['name']
playlist_id = playlist['id']
print(f"Processing playlist: '{playlist_name}'...")
# We'll store track information in this list
tracks_data = []
# Fetch tracks from the playlist, handling pagination
results = sp.playlist_tracks(playlist_id)
tracks = results['items']
while results['next']:
results = sp.next(results)
tracks.extend(results['items'])
# Extract relevant information for each track
for item in tracks:
track = item.get('track')
if track: # Check if track data exists
track_name = track['name']
artists = [artist['name'] for artist in track['artists']]
album_name = track['album']['name']
tracks_data.append({
'name': track_name,
'artists': artists,
'album': album_name
})
all_playlists_data[playlist_name] = tracks_data
# Write the final data structure to a JSON file
try:
with open('spotify_playlists_backup.json', 'w', encoding='utf-8') as f:
json.dump(all_playlists_data, f, ensure_ascii=False, indent=4)
print("\nBackup complete! Data saved to spotify_playlists_backup.json")
except IOError as e:
print(f"Error writing to file: {e}")
if __name__ == '__main__':
backup_spotify_playlists()
Pro Tip: The Spotify API returns results in âpages,â usually 100 items at a time. If you have a playlist with 250 songs, you need to make multiple requests to get them all. The
while results[ânextâ]:loop is crucial; it checks if thereâs another page of tracks and fetches it until all tracks are retrieved. Forgetting this is the #1 reason for incomplete backups.
Step 4: Run the Script
Open your terminal in the project directory and run the script: python3 backup\_playlists.py.
The first time you run it, a browser window will open asking you to log in to Spotify and grant permission. After you approve it, youâll be redirected to that localhost address, and the script will continue. It creates a .cache file in your directory so you wonât have to log in every time.
Once it finishes, youâll have a spotify\_playlists\_backup.json file in your directory.
Hereâs Where I Usually Mess Up (Common Pitfalls)
Even simple workflows have tripwires. Here are the ones that have caught me in the past:
-
Redirect URI Mismatch: If your script hangs after you log in or gives you an auth error, itâs almost always because the
redirect\_uriin yourconfig.envfile doesnât exactly match the one you entered in the Spotify Developer Dashboard. Check for typos or an extra/. -
Incorrect Scope: If you can authenticate but the script canât find your private playlists, you probably requested the wrong âscopeâ. For this task,
playlist-read-privateis essential. -
Forgetting Pagination: As mentioned in the Pro Tip, if you just grab
sp.playlist\_tracks(playlist\_id)[âitemsâ]without looping through the pages, youâll only get the first 100 songs of any large playlist.
Conclusion
And there you have it. A solid, automated way to back up your musical history. You can run this script manually whenever you feel like it, or better yet, automate it. For my personal setup, I have a simple cron job that runs it once a week, ensuring my backup is always fresh. A simple entry like 0 2 \* \* 1 python3 backup\_playlists.py is all you need to have it run every Monday at 2 AM.
This script gives you a safety net. Now that you have the data, you can build on itâmaybe create a tool to restore a playlist, analyze your listening habits, or just sleep better knowing your carefully curated playlists are safe.
â Darian Vance, Senior DevOps Engineer, TechResolve
đ Read the original article on TechResolve.blog
â Support my work
If this article helped you, you can buy me a coffee:

Top comments (0)