Spotify Web API Authorization with React & Rails
Published: 2019-04-15 23:42:03

---
title: Spotify Web API Authorization with React & Rails
published: true
description: 
tags: 
cover_image: https://developer.spotify.com/assets/FBImage.png
---



Heading into project week for Module 4 at Flatiron School, I had been keen on learning how to use OAuth to gain access to real, interesting data from some of my favorite applications. With the projects that I've worked on previously, I had either used fake data or publicly available data (minimally requiring an API key). 

However, I really wanted to use data that came from real people and create an interesting application that utilized that data. This is where OAuth came in and I was determined to figure it out. I have been warned that OAuth can be challenging to implement into your application, especially if you're doing it for the first time. With the help of YouTube tutorials, informative blog posts, and help from others, my project partner and I were able to gain access to real Spotify data on Day 1 of projects.

###What is OAuth and why use it?###

It's a simple way for third party applications to obtain limited access to a web service and it's accompanying data. It allows your app to access and or modify a user's own data.

![Authentication vs. Authorization](https://swoopnow.com/wp-content/uploads/2018/02/security-authentication-user-authorization-websites.png)

###Overview of the Authorization Flow###

![Authorization Flow](https://developer.spotify.com/assets/AuthG_AuthoriztionCode.png)

###1 - Create a simple react homepage ###

- create-react-app
- Having a homepage that has a button that redirects to Spotify Authorization page 


```javascript 
class Button extends Component {
  render() {
    return (
      <a href="http://localhost:3000/api/v1/login">
      Log in to Spotify
      </a>
    )
  }
}
```

###2 - Create your application on Spotify Developer ###

- name your application
- receive your client_id/client_secret (how Spotify can identify your application and either grant or decline the proper response) 
- specify a redirect_uri (where does your application go after the request?)


###3 - Setting up the Rails Backend API###

```ruby
rails new <metrobeat_backend> --database=postgresql --api
```

- Set up your models & controllers
- Creating and migrating your database
- Configuring your routes 

```
# OAuth
  namespace :api do
    namespace :v1 do
      get '/login', to: "auth#spotify_request"
      get '/auth', to: "auth#show"
      get '/user', to: "users#create"
    end
  end
```

###4 - Create an AuthController to handle the initial request ###

```ruby
class Api::V1::AuthController < ApplicationController


  def spotify_request
    url = "https://accounts.spotify.com/authorize"
    query_params = {
      client_id: Rails.application.credentials[Rails.env.to_sym][:spotify]    
      [:client_id],
      response_type: 'code',
      redirect_uri: 'http://localhost:3000/api/v1/user',
      scope: "user-library-read 
      playlist-read-collaborative
      playlist-modify-private
      user-modify-playback-state
      user-read-private
      user-top-read
      playlist-modify-public",
     show_dialog: true
    }
    redirect_to "#{url}?#{query_params.to_query}"
  end
end
```

- Scope is one of the more interesting parameters for this request. It tells 

- How to hide your client_id
    1) Changing your credentials 
    2) Formatting your credentials 
    3) Reading your credentials 

Here's a helpful article that explains how to hide your keys: 
[How to hide your secrets in rails](https://medium.com/@jonathanmines/hiding-your-secrets-in-rails-5-using-credentials-e37174eede99)


###5 - Create a UsersController to handle access and refresh tokens###

One of the more fragile and complicated pieces of this process. Why?
- Making a post request to the Spotify API for a user's access and refresh tokens
- Saving a user's access and refresh tokens
- Handling the 1-hour expiration for a user's access token 

```ruby
#Update the user access/refresh_tokens
    if @user.access_token_expired?
      @user.refresh_access_token
    else
      @user.update(
        access_token: auth_params["access_token"], 
        refresh_token: auth_params["refresh_token"]
      )
    end
```

###6 - Accessing and Saving Real Spotify Data###

The fun part! 

- Ensuring that you can save user data properly
- Fetching a user & their access token from our backend API 
- Fetching from any Spotify Web API endpoint that the user has agreed to in the scopes of the initial authorization request 
- Manipulating the responses you get back however you'd like

###Spotify Endpoints & Cool Stuff You Can Do With Them###

- Get a user's Playlists, Tracks, Albums, etc.
- Use the Spotify Web Playback SDK
- Audio analysis (bars, beats, tempo, danceability, speechiness, etc.)

For a full list of Spotify API endpoints:
[Spotify Developers - Web API Reference](https://developer.spotify.com/documentation/web-api/reference-beta/)

###Key takeaways from the process###

- The process can be daunting at first, but there are several resources to help you.
- Documentation is key! Luckily Spotify's Web API documentation was simple and easy to follow. Even if a piece of code doesn't make sense to you, context will help you figure it out eventually.
- Using OAuth opens a lot of doors to use real-world data to make cool and interesting applications.
- It makes you more aware of what types of data could be available to applications who ask to use it.


###Helpful resources:###

[Spotify API Authorization Flow with React and Rails](https://medium.com/@davidjtomczyk/spotify-api-authorization-flow-with-react-and-rails-7f42845a43c) 
This guy (who was also a Flatiron grad was incredibly helpful in the initial setup of this project)
[Spotify Authorization Documentation Guide](https://developer.spotify.com/documentation/general/guides/authorization-guide/)
[How to hide your secrets in rails](https://medium.com/@jonathanmines/hiding-your-secrets-in-rails-5-using-credentials-e37174eede99)
[Rest client](https://www.rubydoc.info/gems/rest-client/1.8.0)
[DevTips: Pulling data from the Spotify API - #13 React JS prototyping](https://www.youtube.com/watch?v=rzk8n-4gMWs)