In this tutorial you will learn:

  • How to authenticate with Spotify’s API
  • How to fetch playlists, tracks, and user data
  • Common errors & how to handle them
  • Example code snippets in Node / Python

What Are the Spotify API Use Cases?

The Spotify API is really powerful, letting us access tons of info about any song or artist on Spotify. This includes details about how the music sounds, like if it’s live, acoustic, or energetic, and even info about how popular the song or artist is. We can also dig deeper and get things like where each beat falls in a song, which could be very useful for advanced analysis.

Also, we can explore other awesome features of Spotify, like the recommendation system and search function, using the API. If you’re interested in learning more about Spotify’s Web API, you can visit their website. They even offer a console where you can test out the API’s functions, which can be really helpful if you’re having any difficulties with your own projects.

Step 1: Setting Up Your Spotify Developer Account

To start using the Spotify API, you need to have a developer account. If you don’t already have one, sign up for a Spotify account at spotify.com.

Register Your Application: Before you can authenticate with the Spotify API, you need to register your application on the Spotify Developer Dashboard. This process involves providing details about your application and receiving client credentials (Client ID and Client Secret).

For this purpose, go to the Spotify Developer Dashboard and log in with your Spotify credentials. It doesn’t matter if you have a free or paid account; navigate to Spotify for Developers and access your Dashboard.

For each project, you can create an app, and that makes it very easy to distinguish between different projects. Let’s create an app; let’s name it Rojyar. Rojyar in Kurdish means sun. I love sun because you know it’s warm and nice!

Step 2: Credentials

After creating the app, if you click on it, you’ll see “Client ID” and “Client Secret” on the left side. These details are all we need to focus on. It’s crucial to keep credentials information secret and safe. Because if anyone gains access to them, they can easily manipulate your app, and they might do just that.

Step 3: Authentication

Authentication with the Spotify API usually follows the OAuth 2.0 protocol, a common standard for authorization. It can be a bit tricky because you need to obtain an access token before you can explore the APIs. However, if you use the Spotipy package, it handles the token in the background, which is why we highly recommend using it to simplify the process. In this article, I’ll explain both methods briefly.

Open a Python file in vscode or any other code editor to start. I’m going to name my file Rojyar.py. As I said earlier, I’ll first show you how authentication works without the Spotipy package. I’ll explain it with some code and then show you how it works using Spotipy.

Getting Authentication Directly (Without Using Spotipy)

First thing first, let’s import request and base64 library. In order to get access to the token, we need a client ID and a secret ID to make a request to the Spotify account verifying the URL. Because in order to access the various endpoints of the Spotify API, we need to pass this access token.

In other words, if you want to make a request manually, this is our golden ticket to access the API.


Find client ID and secret ID in app settings:

import requests
import json
import base64

CLIENT_ID = "xxxxxxxxxxxxxxx"
CLIENT_SECRET = "xxxxxxxxxxxxxxxxxx"

def get_token():
   auth_string = CLIENT_ID + ":" + CLIENT_SECRET 
   auth_bytes = auth_string.encode("utf-8")
   auth_base64 = str(base64.b64encode(auth_bytes),"utf-8" )
   url= "https://accounts.spotify.com/api/token"
  
   headers = {
    "Authorization": "Basic " + auth_base64,
    "Content-Type": "application/x-www-form-urlencoded" 
    }
   data = {"grant_type": "client_credentials"}
   result = requests.post(url, headers=headers,data=data)
   json_result = json.loads(result.content) 
   token= json_result["access_token"]
   return token


def get_auth_token(token):
    return {"Authorization": "Bearer " + token}
  
token = get_token()

Output of the Search API

After running the code, Spotify sends us a JSON containing this data:

{
  "artists": {
    "href": "https://api.spotify.com/v1/search?query=tupac&type=artist&offset=0&limit=1",
    "items": [
      {
        "external_urls": {
          "spotify": "https://open.spotify.com/artist/1ZwdS5xdxEREPySFridCfh"
        },
        "followers": {
          "href": null,
          "total": 17657804
        },
        "genres": [
          "g funk",
          "gangster rap",
          "hip hop",
          "rap",
          "west coast rap"
        ],
        "href": "https://api.spotify.com/v1/artists/1ZwdS5xdxEREPySFridCfh",
        "id": "1ZwdS5xdxEREPySFridCfh",
        "images": [
          {
            "height": 640,
            "url": "https://i.scdn.co/image/ab6761610000e5eb7f5cc432c9c109248ebec1ac",
            "width": 640
          },
          {
            "height": 320,
            "url": "https://i.scdn.co/image/ab676161000051747f5cc432c9c109248ebec1ac",
            "width": 320
          },
          {
            "height": 160,
            "url": "https://i.scdn.co/image/ab6761610000f1787f5cc432c9c109248ebec1ac",
            "width": 160
          }
        ],
        "name": "2Pac",
        "popularity": 75,
        "type": "artist",
        "uri": "spotify:artist:1ZwdS5xdxEREPySFridCfh"
      }
    ],
    "limit": 1,
    "next": null,
    "offset": 0,
    "previous": null,
    "total": 1
  }
}

Spotipy Package

Spotipy is a simple Python library that lets you access and interact with the Spotify Web API. With it, you can search for songs, albums, and artists, manage playlists, and get details about your favorite tracks using just a few lines of code. It makes it easy to add Spotify features to your Python projects.

spotify api - spotipy

My plan is to create a playlist for dancing. I love dancing, especially while working, which makes it a bit challenging to use public spaces for work :). I’m going to name it “biatooqer,” which means “Get the shaking vibe!” in Farsi. So let’s go!


We want our playlist to include Persian dance songs. It will follow these four steps:
1. Authentication
2. Search for the songs
3. Create a playlist
4. Add songs to the playlist

Searching for the Songs

After authentication, the next step is searching for the songs that we want to add to our playlist. For this purpose, we need to specify our search criteria in our query:

query = "genre:persian year:1980-2010"

results = sp.search(q=query, limit=50)

Create a Playlist

In this part, we created a playlist on Spotify.

playlist_name = "biatouqer"
playlist_description = "A playlist of Persian pop songs for dancing while working!"
playlist = sp.user_playlist_create(sp.me()['id'], playlist_name, public=True, description=playlist_description)

track_titles = [track['name'] for track in results['tracks']['items']]

def get_track_id(title):
    result = sp.search(q=title, limit=20)
    if result['tracks']['items']:
        return result['tracks']['items'][0]['id']
    else:
        print(f"No track found for title: {title}")
        return None