DEV Community

Cover image for Solved: Backup Spotify Playlists to a JSON File using Python
Darian Vance
Darian Vance

Posted on • Originally published at wp.me

Solved: Backup Spotify Playlists to a JSON File using Python

🚀 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 spotipy library, combined with python-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/callback Redirect 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 spotipy library: This is the key Python library for interacting with the Spotify API. I’ll skip the standard virtualenv setup since you likely have your own workflow for that. Just make sure to install the necessary libraries in your environment. You’ll need spotipy and python-dotenv. You can typically install them by running pip install spotipy python-dotenv in 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.

  1. Navigate to the Spotify Developer Dashboard and log in.
  2. Click “Create App”.
  3. Give your app a name (e.g., “My Playlist Backup Script”) and a brief description.
  4. 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.
  5. 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.
  6. 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'
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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\_uri in your config.env file 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-private is 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


Darian Vance

👉 Read the original article on TechResolve.blog


☕ Support my work

If this article helped you, you can buy me a coffee:

👉 https://buymeacoffee.com/darianvance

Top comments (0)