Continuously Analyzing My Spotify Library

Published 1 week ago5 min read- ViewsJames IvesJames Ives

A couple of years ago, I wrote an article on Google Music about how everyone was sharing their end-of-year Spotify statistics. I felt inspired to hack together my version even though Google Music had no API for me to use. Fast forward to 2022 and I've well and truly caved to pressure and have since switched to Spotify. While Spotify sends out user statistics at the end of the year I'm incredibly impatient and wanted to see them now. I thought to myself it would be cool to be able to have a place to see this information all year round. In this article, I'll outline the process I used to gather this information and also share my current statistics. This is intended to be a living breathing article that updates over time and continuously analyses my Spotify library.

Keeping the Rave Alive (Photo Credits: Branndon
Thomas)

Keeping the Rave Alive (Photo Credits: Branndon Thomas)

Integrating the Spotify API 🔧

Getting started with the Spotify API is quite straightforward. You'll want to begin by registering your application on their developer portal, doing so will get you a client id and secret. However, to make API calls for user data you'll first need to generate a refresh token via their Authorization Code flow. Spotify has a tutorial on how to do this which can be found here along with a sample application to get you started. Be sure to grant the flow with the correct permission scope needed for the data you want to request

Before making any user data request, you'll also need to generate an access token which can be done by combining your client id and secret along with the refresh token which you generated in the previous step. As you can use this for multiple purposes you may find it helpful to split this into its own method whose sole purpose is to generate the access token.

const getSpotifyAccessToken = async () => {
  const spotifyClientId = process.env.SPOTIFY_CLIENT_ID
  const spotifyClientSecret = process.env.SPOTIFY_CLIENT_SECRET
  const spotifyRefreshToken = process.env.SPOTIFY_REFRESH_TOKEN
  const spotifyCredentials = Buffer.from(
    `${spotifyClientId}:${spotifyClientSecret}`,
  ).toString('base64')

  const response = await fetch(`https://accounts.spotify.com/api/token`, {
    body: new URLSearchParams({
      refresh_token: spotifyRefreshToken,
      grant_type: 'refresh_token',
    }),
    headers: {
      Authorization: `Basic ${spotifyCredentials}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
  })

  return response.json()
}

Once your getSpotifyAccessToken method is defined and responding as expected you can begin making requests for the data you want. As the credentials used for the API are private you should avoid making client side calls. If you have the means you can proxy these requests on your servers back-end or leverage a GitHub Action or something similar for static site generators. The intention of the token generated by getAccessToken is so it can be used in subsequent requests to get the user data. To get a sense of how to use this check out the example below.

export const getTopStats = async (stat, timeRange) => {
  const { access_token } = await getSpotifyAccessToken()

  return fetch`https://api.spotify.com/v1/me/top/${stat}?time_range=${timeRange}`, {
    headers: {
      Authorization: `Bearer ${access_token}`,
    },
  })
}

With that all setup, let's look at some data! All images and other data points below belong to their respective owners.

Top Artists

These are my top artists of all time. Well, ever since I started using Spotify at least. To get this data I made a request to the /me/top/artists endpoint using the long_term range. At the time of writing this article there's no surpirses here with appearences from Post Malone, Dave and Armin van Buuren. Following the artists is a list of genres they collectivly produce. It will be interesting to see if over time this list changes at all.

Recent Top Artists

If we narrow the results down, these are the artists and their genres I'm listening to a lot recently. For this data, I changed the range to short_term in the request. According to Spotifys API reference this data is averaged over the last 4 weeks.

Top Tracks

The following list represents my top tracks since the inception of my Spotify account. You can click the buttons within the cards to give them a listen if you're interested. For this data, I made a request to the /me/top/tracks endpoint using the long_term range.

Recent Top Tracks

Likewise, these tracks represent the songs I'm listening to recently. Similarly, I used the short_term range for this data.

Closing Thoughts

Switching from Google Music (now YouTube Music) to Spotify felt like a good choice overall as it appeals to the developer in me. While I don’t have much of a end conclusion to share, being able to generate things like this using code is really neat. If you have any questions please feel free to leave a comment or reach out on Twitter.