Spotify API Tutorial

Introduction

The Spotify API uses a framework known as OAuth 2.0, which provides different "flows" or procedures for authorization with a web service.

We will be following the Authorization Code with PKCE Flow, which is what Spotify recommends for this kind of client-side app with no backend. The code snippets provided in this tutorial are taken from the Spotify documentation.

The source code for this tutorial and demo can be found on GitHub.

Here's a brief overview of the steps we'll be taking:

  1. Registering Your App with Spotify
  2. Getting an Authorization Code
  3. Exchanging the Authorization Code for an Access Token
  4. Making Requests to the Spotify API

1. Registering Your App with Spotify

Before you can start using the Spotify API, you need to register your app on the Spotify Developer Dashboard.

Once you've registered your app, you'll receive a client_id that you'll need to use to authenticate your app. (Don't worry about the client_secret, this is used for other authorization flows.)

Paste your Client ID here: (we won't steal it, promise!)

Redirect URI

You will also need to register the redirect_uri for your app.

Basically, the user will click a link on your site that will redirect them to Spotify so that they can log in and authorize your app. Once they've done so, Spotify will send the user back to your site. The redirect_uri tells Spotify where they should send them. For security reasons, Spotify requires that the redirect_uri be an absolute URI and that it be registered with your app.

Go to the Developer Dashboard and add a redirect URI. You should use something like http://localhost:8080/index.html if you're running on a local server. Once your app is deployed, use the full URL of your deployed page. (Spotify treats localhost and 127.0.0.1 as different, so make sure you specify the right one - or both!)

2. Getting an Authorization Code

The first thing your app needs to do is request authorization from a Spotify user. This will send the user to Spotify, have them log in, and then redirect back to your app with an authorization code in the query string of the URL.

You will need two things to request an auth code:

Making the Request

You will need code to generate a code_challenge and a code_verifier. Spotify provides source code to create these in its developer documentation. You should use their provided code in your own project.

Here are the values we've generated for this tutorial:

You should generate your own values programatically each time you make a new authorization request. You will need to store the code_verifier in localStorage, since the page will be reloaded after Spotify redirects the user. Read the section below to see why this is important!

Here is an example of making the authorization request via JavaScript (updated with your request values):

window.localStorage.setItem('code_verifier', codeVerifier); // Save the code verifier for later

const clientId = '';
const redirectUri = '';

const scope = 'user-read-private user-read-email'; // Specifies what user data your app can access!
const authUrl = new URL("https://accounts.spotify.com/authorize")

const params =  {
    response_type: 'code',
    client_id: clientId,
    scope: scope,
    code_challenge_method: 'S256',
    code_challenge: codeChallenge, // The hashed code verifier
    redirect_uri: redirectUri,
}

authUrl.search = new URLSearchParams(params).toString();
window.location.href = authUrl.toString(); // Redirect the user

Try It Yourself!

If you've set the client_id and the redirect_uri above, you can click this button to request an authorization code:

Your auth code is:

3. Exchanging the Authorization Code for an Access Token

Once you have the authorization code, you can exchange it for an access token. This token is what you will use to make requests to the Spotify API. If you have successfully requested an auth code, it should be present in the URL's query string.

You can get the auth code from the URL like so, using URLSearchParams to parse the query string (read more!):

const urlParams = new URLSearchParams(window.location.search);
const authCode = urlParams.get('code');

Now you can exchange this code for an access token. This token is your "golden ticket 🎫" to the Spotify Web API. We will need to make another request to the Spotify server, this time a POST request.

Making the Request

There are a few body parameters, which need to be in the x-www-form-urlencoded format. These are:

Here is an example of a request that exchanges the auth code for an access token:

// codeVerifier MUST be the same as the one used to make the code challenge for the auth request
const codeVerifier = localStorage.getItem('code_verifier');

const payload = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
        grant_type: 'authorization_code',
        client_id: '',
        redirect_uri: '',
        code_verifier: codeVerifier,
        code: authCode, // From the URL
    }),
}

const response = await fetch('https://accounts.spotify.com/api/token', payload);
const data = await response.json();

const accessToken = data.access_token;

Try It Yourself!

If you've successfully obtained an auth code, you can click this button to exchange it for an access token:

Your access token is:

This token will last for an hour, after which you will need to request a new one. There is a mechanism to refresh the token, so the user doesn't need to log in again.

4. Making Requests to the Spotify API

Now that you have an access token, you can make requests to the Spotify Web API. For this tutorial, we will get the current user's profile and display their name and profile image. You can read the documentation for this endpoint here.

The base URL for the Spotify API is https://api.spotify.com/v1, and this specific endpoint has the path /me. Thus, the full URL is https://api.spotify.com/v1/me. You can read more about Spotify API calls here.

To send a request to this (or any other) API endpoint, we can use fetch() with the full URL, and additionally specify any parameters the endpoint is expecting. All your requests must include the access token in the Authorization header, with the value: Bearer [YOUR_ACCESS_TOKEN_HERE].

Example Request

Here is an example of how you can get the current user's profile:

const response = await fetch("https://api.spotify.com/v1/me", {
    headers: {
        'Authorization': 'Bearer ' + accessToken,
    },
});

const data = await response.json();

Try It Yourself!

If you've successfully obtained an access token, you can click this button to get the current user's profile:

Your user profile is:

User profile