How To Get Started With Spotify Web API

Coşkun Atak
6 min readJun 4, 2023
Photo by Thibault Penin on Unsplash

There are many fun websites that compare our music tastes with our friends, determine what type of pasta we are based on our most listened song, and even generate a playlist based on the songs we listen to. Okay, I made up some of them, but still, these kinds of applications are increasingly popular and add a different dimension to the enjoyment of music.

I also developed a similar application called “Randofy” a few months ago. While developing my app, which allows our friends to access a randomly selected song from our frequently listened tracks through a generated link, I learned a lot about the Spotify API and integration processes.

Now, I wanted to prepare this tutorial to share what I have learned during this process. In this tutorial, we will learn how to create a simple Spotify application. So, lets get started.

Creating Spotify App

First, we need to visit the website https://developer.spotify.com and log in. Then, navigate to the Dashboard page and create a new application.

Screenshot of Spotify Developer Dashboard Page

To create our application, we need to fill out a small form. Here, we will determine the name and description of our application, as well as specify the redirect URLs.

Example of creating app form

The most important part here is our Client ID and Client Secret information. After accessing our application’s page on the Dashboard, we need to get them from app’s settings page and save these two values somewhere secure, preferably in a separate file or environment variables for later use.

Cient ID ve

Coding Time!

After creating our Spotify application, now it’s time to move on to the coding phase (my favorite part). In this stage, we will create a simple server where users can log in to our application using Spotify.

Now, to make our lives easier, we will use some libraries. The choice of which library to use is entirely up to you. However, for the sake of demonstration, let’s say I will be using the following libraries:

npm install express axios querystring dotenv

Once we have our libraries installed, we can create our “Hello, World!” server. Here’s an example of our index.js file, using Node.js and Express.js:

//** index.js */
// Import packages
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const querystring = require('querystring');

// App config
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Hello world
app.get('/', (req, res) => {
res.send('Hello world!');
});

// Run server
const PORT = 8000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

If you can see “Hello world!” when you visit localhost:8000, that means all is well and we can continue…

By the way, it is important to protect sensitive information such as the CLIENT_ID and CLIENT_SECRET for your Spotify application. To do so, we need to create a .env file and store these credentials there. Here's an example of what the .env file might look like:

CLIENT_ID=your_client_id_here
CLIENT_SECRET=your_client_secret_here

Make sure to replace your_client_id_here and your_client_secret_here with the actual values provided by Spotify for your application. Remember to keep this .env file secure and not share it with anyone or commit it to version control.

Now, we will need two routes. The first one is the /login endpoint, which will be the initial entry point for users to our server. The second one is the endpoint where users will be redirected by Spotify after logging in (which is also the redirect URL we specified when creating the application).

// First route: /login endpoint
app.get('/login', (req, res) => {
// Handle the logic for user login with Spotify
// Redirect the user to the Spotify authorization page
});

// Second route: Spotify redirect endpoint
app.get('/callback', (req, res) => {
// Handle the callback from Spotify after user login
// Retrieve the authorization code and exchange it for an access token
});

/login

In the /login route, we will need to implement the logic to redirect them to the Spotify authorization page using our credentials. We will need some helper functions at this point. (You can visit Spotify Web API Docs for more info.)

// This is needed because Spotify recommends using it 🤷‍♂️
function generateRandomString(length) {
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = Array(length).fill(characters).map(function (x) { return x[Math.floor(Math.random() * x.length)] }).join('');
return result;
}
// Your client id
const client_id = process.env.CLIENT_ID;
// Your client secret
const client_secret = process.env.CLIENT_SECRET;
// Your redirect uri for spotify to redirect to after login
// (This must be same with the form we filled before)
const redirect_uri = "http://localhost:8000/callback";
// Your scope, list of permissions you want to access
const scope = 'user-read-private user-read-email';

app.get('/login', function (req, res) {
// Redirect user to spotify login page
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: generateRandomString(16)
}));
});

If you have set up your application correctly, accessing localhost:8000/login should redirect you to the Spotify login screen as intended. It means your authentication flow is working as expected. This is a crucial step in allowing users to log in to your application using their Spotify credentials.

Screenshot of Spotify Login Page

If there are no issues up to this point, we are moving on to the final and most complex stage: /callback.

/callback

Indeed, the /callback endpoint is typically the most complex part of the authentication process. It involves handling the callback from Spotify after the user has logged in and retrieving the authorization code to exchange it for an access token.

app.get('/callback', async (req, res) => {
try {
const { code, state } = req.query;
// return error if state is not found
if (!state) return res.status(400).send('State not found');
// retrieve access token of user from spotify
let responseTokens = await axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
data: querystring.stringify({
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
}),
headers: {
'Authorization': 'Basic ' + Buffer.from(client_id + ':' + client_secret).toString('base64'),
},
json: true
});
const { access_token } = responseTokens.data;
// retrieve user information from spotify
let responseUserInfo = await axios({
method: 'get',
url: 'https://api.spotify.com/v1/me',
headers: {
'Authorization': 'Bearer ' + access_token
},
json: true
});

//* Do something with user information here
//* For example, save user information to database, etc.
console.log(responseUserInfo.data);

// return success response
res.status(200).send("Login success!");
} catch (err) {
console.log(err);
res.status(500).send('Something went wrong.');
}
});

This code consists of three stages. In the first stage, we are verifying the data sent to us by Spotify. In the second stage, using this data, we obtain the access and refresh tokens belonging to the logged-in user. Finally, in the third stage, we access the user’s information using these tokens.

If you can successfully get “Login success!”, congratulations! That means you have made it through the process flawlessly so far.

In this part, it’s entirely up to you to decide what you will do with the user’s information and how you will develop your application. You have the flexibility to design and build your application based on your specific requirements and ideas. You can leverage the user’s data to create personalized experiences, build music recommendation systems, develop playlist generators, or implement any other features that enhance the user’s interaction with Spotify. Be creative and have fun exploring the possibilities!

Important Stuff

From this point onward, using the Spotify Web API, you can access the data specified by the scopes you have requested from the user. There are some important considerations to keep in mind in this final stage:

  • You must ensure the security and privacy of user data.
  • Your Spotify application starts in development mode, allowing only a maximum of 25 users that you can specify from your Application Dashboard. To switch to production mode and increase the user limit, you need to submit an extension request through the settings section on your Application Dashboard.
  • Don’t forget to check my source codes on Github.

Have fun and stay funky! 👋

Feel free to reach out to me through the “Issues” section of the repository if you have any questions or encounter any issues. I’m here to help!

--

--