Using the Spotify API

Nicholas Thomson
Nerd For Tech
Published in
3 min readJul 30, 2021

The Spotify API is a powerful resource that allows users to access the treasure trove of data on Spotify’s servers. You can pull individual tracks, you can drill down into playlists, or even users’ data! However, the barrier to entry is high when compared with other APIs, and Spotify’s documentation can be some of the more daunting for a burgeoning developer to approach.

A look at the laborious authorization flow on the Spotify for Developers site is enough to convince me that they don’t want too many people accessing their API:

Luckily, if you don’t need to access data related to Spotify users, or playlists, you can sidestep Spotify’s oAuth process. For my project — a Spotify clone for classical music — I only needed to search Spotify’s database of songs so that I could embed them in browser. Luckily, there turned out to be an easier way.

Enter the RSpotify gem — a Ruby tool that lets you search through the Spotify database from your Ruby backend. The full documentation can be found here: https://github.com/guilhermesad/rspotify

Just add:

gem 'rspotify'

to your gemfile, then

bundle

Once you’ve got the gem installed, you can pull down data from the Spotify API and use that data to seed your database. Here is how I used the RSpotify gem to search and seed:

In seeds.rb

Let’s break this block down. Composition calls on my model of the same name. For each composition instance in the database, Ruby will send out a request to RSpotify with two authentication keys, which you can get from Spotify via the developer tools:

On login, you will be given a Client ID and a Client Secret

I have hidden the Client ID and Client secret in my .env file, and I recommend that you do the same. This is the same method for using API keys and other sensitive information you do not want published to github where malicious actors could take advantage.

The RSpotify gem allows you to search by artist, album, or track. The results of an RSpotify search are going to come back as Active Record instances:

This means that accessing the precious Spotify ID — which is what you will need if you want to embed the songs on your website — requires the .instance_variable_get method:

Don’t forget the @!

Once you’ve gotten the ID from Spotify and saved it to the backend, you can fetch it from the frontend and dynamically interpolate it into the Spotify embedded <iframe> player like so:

And with that, you can stream songs from Spotify on your own applications. It’s amazing how generous apps like Spotify are with their data, and developers would do well to avail themselves of it!

--

--

Nicholas Thomson
Nerd For Tech

Software engineering student at the Flatiron School