Create an application in the Spotify Developer Dashboard

  • First go to the Spotify Developer Dashboard.
  • Log in with your Spotify account.
  • Click Create an App.
  • Add a name (eg. Website Now Playing) and a description.
  • Click on Show Client Secret.
  • Save both Client ID and Client Secret.
  • Add http://localhost:8080 as redirect URI. It can also be the one where your local version of your site is running (eg. http://localhost:5000).

Get the refresh token and authenticate

You need to go to an URL first to authorize your account by logging in using your spotify account and giving permission to scopes that you will be using. These scopes let you have control on what you can share after authorizing your account. These are basically OAuth 2.0 scopes.

Here's the URL:

https://accounts.spotify.com/authorize?client_id=8e94bde7ddb84a1f7a0e51bf3bc95be8&response_type=code&redirect_uri=http%3A%2F%2Flocalhost:8080&scope=user-read-currently-playing,user-read-playback-state,user-read-recently-played

You need to replace the client_id with the Client ID you saved from before. The redirect_uri is the same as your local application redirect URI. It can be anything you set it.

The scope is what you give permission to access from the Spotify API. In this case, I used the user-read-currently-playing, user-read-playback-state and user-read-recently-played scopes. You can find a list of Spotify authorization scopes right here.

After authorization, it will redirect you to the redirect_uri given to the URL. That URL will have a code query parameter. You need this value.

http://localhost:8080/callback?code=AQC7P..gBoDU

You will use this returned code and a Base64 encoded string using the Client ID and Client Secret to retrieve the refresh token you need to access the Spotify API.

The format of the Base64 string is client_id:client_secret.

1
2
3
4
5
6
7
8
/*
 * This will generate a Base64 string from the given format.
 * You can write this in any developer console on any browser.
 */

btoa('client_id:client_secret')

// Outputs a Base64 string.

Next, let's go to a terminal and make a curl request.

1
2
3
4
5
6
7
curl -H "Authorization: Basic
[Base64 client_id:client_secret string without brackets]"
-d grant_type=authorization_code -d
code=[code from the redirect URI after authorization
without brackets]
-d redirect_uri=http://localhost:8080
https://accounts.spotify.com/api/token

This curl request will return a JSON response with our much needed refresh_token to access Spotify API. This token does not expire unless the user revokes access, so you can use this to access the API.

Edit

Pub: 23 Sep 2022 19:10 UTC

Views: 192