Spotify API —A Rite of Passage

Rails API Backend:HTML/CSS/JS Front End

Welcome, weary traveler. If your journey of learning how to use Spotify’s API in your app was anything like mine, this is probably not the first medium article you’re reading on your quest. Hopefully for some of you this will be the last stop of your search, and the beginning of your exploration. While Spotify’s API has a steep learning curve, once you get your foot in the door, the possibilities are numerous.

https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow

First Step- Registering your App

Above is a flow-chart of Spotify’s authentication process, a.k.a. your yellow brick road(including some flying monkeys). The very first thing you need to do is create and register an app with Spotify’s developer platform. You do need to have an active spotify account, however, it does not need to be a premium one. If you have a free account you simply won’t be able to choose single songs to play, and will be forced to shuffle. But thats still a ways away.

First, visit https://developer.spotify.com/dashboard/ , where you will be prompted to login.

https://developer.spotify.com/dashboard/

Once logged in, navigate to the dashboard where you have the option to create your app. The name of this app can be anything, and is not tied to your actual app at all. So don’t worry about matching names.

Once your app is made, click on your app, which will open up and show you info on numbers of users, where they’re located, amount of requests made etc… You want to click on show client secret, both of these pieces of info are our key into spotify. Mine are blocked out as yours should be. In the app they should also be made private, otherwise others can possibly use your keys, which can cause a bunch of headaches. For the sake of this blog, I won’t be explaining how to hide the keys, but here is a great blog explaining that.

https://medium.com/better-programming/how-to-hide-your-api-keys-c2b952bc07e6

Create Your Backend

Create a new Rails backend using rails new <project-name> — -api -T — -database=postgresql (mine is using postgres, but you can use the database of your choice. In your Gemfile you will want to uncomment ‘rack-cors’. In your config file, under initializers, go into your cors.rb file and uncomment everything under “allow” and change origins to ‘*’, which allows any origin to be accepted.

config/initializers/cors.rb

Routes

For the quickest way to start getting responses from the API, were going to make two controllers, both in folder within the controller, to show us clearly that they are responsible for the API calls.

rails g controller api/v1/auth create --no-test-framework
rails g controller api/v1/user create --no-test-framework
rails g controller api/v1/playlist create --no-test-framework

And you want to have corresponding routes in your routes.rb, for both auth, and playlist. You can just put the resources for users.

Rails.application.routes.draw do
namespace :api do
namespace :v1 do
get'/login', to: "auth#spotify_request"
get '/auth', to: "auth#show"
get '/users', to: "users#create"
patch '/user', to: "users#update"
end
end
resources :usersRails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :playlists do
collection do
get :get_playlist
get :random
get :search
get :index
end
end
end
end
end

Auth Controller

Next, in the auth controller, we want to put in the code that is responsible for the first step of authentication.

app/controllers/api/vi/auth_controller.rb

The important things to note here are the client_id, which we got earlier from our developer portal, should be filled in with your unique id. The scope can be many different things, and this depends on what you are trying to have your app be able to do. Documentation on spotify’s scope can be found here (https://developer.spotify.com/documentation/general/guides/scopes/).

The last important part of note is the redirect_uri. When you make a request for authentication to spotify, they send a response back to a uri of your choice. In this situation, I set the redirect_uri to our users controller, which will take the response, parse it, and send another request for an access token. But first, you also have to whitelist this redirect_uri in spotify’s developer, so that spotify knows it's safe to send the response here.

This is also your first time encountering one of spotify’s endpoints, or the urls that requests to spotify are sent. In this case, our first authentication request is sent to their authorization endpoint. Spotify’s documentation for their endpoints are located here. (https://developer.spotify.com/console/) They even allow you to try it out in the browser.

Client + Secret IDs

This can be done by going back to where we got our client and secret ids and clicking on edit settings.

https://developer.spotify.com/dashboard/applications

Once in settings, you can add your redirect_uri. Mine being to the users controller on the local host I currently have the server running on.

HTML

Spotify’s authorization process requires a pop-up, or a new window for completion. The easiest way I found was to create a login.html where the sing-in to spotify link was located, and an index.html that spotify’s authorization window could redirect to where my main app could reside.

Users Controller

Next, we want to set up our users controller which will be handling the callback after we send our first authentication request for our access token.

The code on lines 23–25 is the common header required for most spotify requests that also require our access token for authorization, so saving it to global variable allows us to use it in different controllers for different requests. The access token only lasts for an hour before it needs to be refreshed, for now when it expires, you can just go back to localhost:52300/login.html and repeat authentication.

We’re In!!

But now that we have been authorized and have our access token, were able to start making our requests for spotify information saved to our actual profile!

Playlists Controller

Let’s move over to our playlists controller. The first call we’re going to make is to return the saved playlists from my spotify.

For this case, I saved my personal spotify user_id to a global variable so I can use it in all requests to get my info. Again, this isn’t hidden, but for learning how to get into spotify’s API it’s fine for now. Endpoint1 is an example of another one spotify’s endpoints. This one is to my saved playlists. When we make a call to spotify, we need to parse into it, and also iterate over it in order to get into the information spotify sent us. The first level of the json response spotify sends is entered using [“items”], this allows you to iterate over the type of information you made the request for. While for some reason I saved everything to the variable @tracknames, those are actually the individual playlist objects we requested, parsed out so we can access them with javascript. We have to render them back to json at the end, so we can make a request from javascript and manipulate them there.

Javascript

Moving on to our last step in the process, we can go into the javascript file responsible for our app.

To access this information, we make a fetch request to our local url responsible for carrying out this spotify request. This url is calling the get_playlist function from our playlists controller responsible for the spotify requests regarding playlist. So a url we could probably end up using down the line is playlists/create_playlist. From there we can convert the response from json to accessible info. Which if instead of -

data.forEach(showPlaylistNames)

We console logged it -

console.log(data)

It would look return this-

You can also see that there are even more spotify endpoints in each playlist object, which can then be used to make even more requests to get the individual track objects in this playlist.

Writing the code without the console log however, means we have a full complete path, starting with —

  • Sending an authentication request to spotify, receiving a response with an access token, and an authorized spotify profile.
  • Making a request to spotify’s API with our controllers using our access token, and then parsing the response into usable and accessible information, before converting it back into json.
  • To making a fetch request from javascript, converting that response into objects which we are then manipulate and display over our HTML

Resulting in…..

the most beautiful website ever made

My actual spotify playlists!!!! Sad country being my personal favorite.

And there you have it, your foots in the door. You are fully connected to Spotify’s API, and from here you can start exploring spotify’s many different endpoints and the different requests necessary for them!!!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store