Connecting to the Spotify API Using Node.js and Axios — Client Credentials Flow
Hi! I’m new to web development and was playing around with my newfound skills by making a project utilizing the Spotify API.
As a person who’s never really worked with HTTP request libraries or an API that uses authentication tokens like Spotify’s, I felt really intimidated and stuck. The documentation was a tad confusing to wrap my head around and the issues I faced had varying answers online, and I didn’t really know which way to go.
I even asked on StackOverflow, but I think my questions were a little too basic and vague! So I figured it out on my own and wanted to share my journey, both for myself to read in the future and for anyone else who is a beginner and stuck.
Keep in mind I was a complete beginner and a lot of explanations may be really basic (and maybe a bit flawed) for someone with more experience that’s reading this! But feel free to chime in below!
What Was I Trying To Do?
My vision with this project was to connect to the Spotify API, use one of the API resources to send in a playlist ID, and use the metadata I get back to visualize the quality and attributes of the playlist.
Really straightforward and simple in my mind, but a bit complicated for me in practice. There were a couple of initial roadblocks I hit:
- Spotify’s API requires you to get an access token before you can use their API to make GET requests to get your data. What in the world is an access token!
- I didn’t know how to make a request to this server, in what format, and what tools/utilities to use?
Oh boy, I’m in for a nightmare…let’s try to figure this out!
Reference the Spotify API…
The first step I took was to go back and reference the API documentation from Spotify. I needed to figure out how to connect and authenticate with the API to access its features.
Here’s the documentation I referred to. Let’s break it down together.
Here are the two key steps I found:
Register Your Application
First, I learned I would have to register my app with Spotify. You can do that by going here and logging in with your Spotify account.
Then, click on the “Create An App” button on the dashboard page (as I marked in the red box above).
Next, fill out the app name and app description as I did above and click create.
Congratulations! You now have your app registered with Spotify. Click on your app from the dashboard and note down the two items I have covered in white above (Client ID and Client Secret). You can think of this as your “username” and “password” to access the API.
Authorization Flows
The second step the documentation referred to was to “follow one of the four Spotify authorization flows”. An authorization flow is a way APIs like Spotify can let users access data that isn’t publicly available. Spotify’s API has 4 flows — each having a different purpose:
- Authorization Code Flow — for long-running applications needing a user’s data
- Authorization Code Flow With Proof Key for Code Exchange (PKCE) — same as above but for mobile and desktop apps, where storing sensitive data may prove to be unsafe
- Implicit Grant — for applications that need a user’s data temporarily
- Client Credentials Flow — for applications that don’t need a user’s data, but still need the app to be authorized to access the API
The flow that was relevant to my project was the “Client Credentials Flow”, as I didn’t need a user’s private data, but rather just the public data of tracks and playlists.
This flow, as noted by Spotify, is used for server-to-server authentication. I would send my “Client ID” and “Client Secret” (remember that from above?) and then, if they are valid, get back an access token. That access token can then be used to request data from the API. Here’s a diagram from the docs that shows this visually:
How to Make HTTP Requests to the API Using Node.js
This brought me to my next question — how in the world do I make this request? My research brought me to the Spotify GitHub where they gave solid examples for the flows. However, they were a bit outdated (and I believe, no longer being maintained).
Ok, maybe I was being a bit nitpicky here, but “Request”, the library they used here for requests to the API (in the client credentials repo), was outdated and deprecated. It was a bit hard to sift thru and find docs on it and seeing the words “deprecated” every time I ran the examples made me panic. Rookie mistakes I know, and the fundamentals are the same, but I searched for an alternative.
Now there were two alternatives to request that I found out about, fetch and Axios. As a person who knows only the basics of HTTP requests, I don’t want to even go down the rabbit hole of why use fetch or Axios, but here's a cool Medium article that led me to choose Axios. Plus, it seemed more relevant (again, spoken like a rookie I know…).
Axios had some cool documentation but it was a little too simple for my taste with the example, especially when it came to sending and receiving auth tokens. These two links however proved more useful:
- Link on Axios and its capabilities — talks about using async-await as well (as one of Axios’s capabilities is that it return a promise!)
- Link on Axios on Authorization — talks about sending headers with Axios for authorization (huge headache for me to figure out)
Circling Back to Spotify Docs…
Now that we knew what tool we were to use for HTTP Requests. I needed to understand what requests we were sending and what information we had to send with it.
According to the Spotify API Docs, there are two steps in the ‘Client Credentials Flow”
- The application requests an access token.
- The application utilizes an access token to access Spotify API.
For step 1, we will need to send a POST request with our “Client ID” and “Client Secret” (remember that from above?) to the URL “https://accounts.spotify.com/api/token”. The header of this request must also contain the parameter “Content-Type” specified to “application/x-www-form-urlencoded” and “grant_type” as “client_credentials”.
Simple? Nah I know this makes no sense to a beginner like myself, but when we code it the structure will fall in place! Those two parameters tell the Spotify API endpoint important identifiers that it needs to know which authentication is being requested.
For step 2, we will need to send a GET request with our newly gotten token from step 1 to an endpoint in the Spotify API such as “https://api.spotify.com/v1/playlists/{playlist_id}”. You can find more API endpoints as your use case needs here!
The Code
Now that we have a decent understanding of what and how (after a bunch of Googling), we can start to code! I’m going to be using steps on a Mac/Unix Terminal (especially for the beginning setup), but I’m sure Windows isn’t much different.
Setup
First, create a new project folder and create a new file in there by the name of “app.js”.
mkdir new-project
cd new-project
touch app.js
Now, we need to initialize the Node runtime environment and add the required dependencies.
npm init -y
npm install axios qs dotenv
We have installed 3 packages. Check your package.json to make sure you see the 3 packages listed!
Axios, as we discussed above, is our HTTP request tool. Qs is a new package with quite a few utilities, but the one we will use is .stringify
, which basically converts a JSON object into a string. Lastly, the dotenv package is used to make a file that holds sensitive information in a separate file “.env”.
Let’s do that now. Create a file called “.env” in your project directory. Add your Client ID and Client Secret. It should look like this:
SPOTIFY_API_ID=put client ID here...
SPOTIFY_CLIENT_SECRET=put client secret here...
Now, you should see 5 files/folders in your project folders.
Awesome! Let’s write the code in our app.js file now…
App.js
Here’s my full code:
This may seem like a blob of (poorly commented, lol) code right now for a beginner like myself — but trust me it’s not that bad. Let me break it down section by section…
Lines 1–3
Remember how we installed the dependencies above? Well, now we need to tell App.js to use them. For this, we use the require(...)
function.
Lines 5–7
Remember how we stored our sensitive environment variables in the .env
file? Here, we bring them into App.js and store them in variables. We then combine the two variables into a Base-64 Representation we can send to the Spotify API with our POST request later!
Lines 9–28 (getAuth() function)
Now here’s the juicy part. We need to make an asynchronous function that makes a POST request to the Spotify API with all the important information. If it’s successful, we return the access token from the API. If not successful, we will log the error on our console.
Errors can vary here. If you do get an error, the log (although convoluted) will provide helpful information to where it may be going wrong. For example, I once got an error for going over the rate limit of requests set by Spotify.
Lines 30–48 (getPlaylist() function)
Another juicy part here! I need to make an asynchronous function that takes in a playlist ID to make a GET request to the Spotify API to get information on that playlist. We first use the getAuth()
function from above to get our token. We then send in a GET request to the URL + the playlist ID. If it’s successful, we return the data we received from the API, else, we log the error on our console.
I want to note that line 13 and line 40 seem very similar. However, it’s important to understand that in line 13 our authorization type is that of a “requestor” of the access token, and in line 40 our authorization type is that of a “bearer” of the access token. Just something that helped me understand this process better!
Line 50
Here we are simply outputting the data into the console to see the contents, but you can do whatever you need to with the data that is returned from the function here!
Conclusion
I hope this long article helped you understand the Spotify API better. I know as a beginner it’s hard to find easy-to-understand resources for things, so I figured I’d try to help out by writing something as a beginner for a beginner!
This is my first Medium article too! Hope you liked it and if you have any questions or spot any dumb error I made, feel free to comment it below!
Also, follow me as I get into more problems on my beginner journey and write about how I solved them!
Wish me luck on the rest of my little project :)