Creating a Spotify Login Portal for your App with the Spotify API
In order to begin building an app that will use the Spotify API, we first have to create a new Spotify app through the Spotify developer portal.
First we visit the link to the portal: https://developer.spotify.com/dashboard/login
Once on the page, hit the Login button to login to your Spotify. If you don’t have an account just follow the link to create a new one.
Upon logging in, we’ll see the user dashboard:
The dashboard displays all of the apps you’ve created so far, as well as a few buttons for creating a new client id or new app. If you’re building a brand new Spotify API based app from scratch, click on the transparent My New App icon to begin setting up your new app. This will open a window that prompts you to name and describe your app and agree to some terms and conditions.
Once the app is created, you’ll be redirected to a page displaying your app:
Here we’ll need to do a few very important things in order to make our first login attempt to Spotify through our app.
First, we’ll copy our Client ID so that we can enter it as a query param in our first request to the Spotify API.
Inside of our Rails API backend we have a Login Controller which redirects to a link that includes all of the required query params to authorize a Spotify login. Be sure to use only the scopes required for your app.
Here’s a link to a list of all scopes: https://developer.spotify.com/documentation/general/guides/scopes/
Next, we need to set up our app to allow whatever redirect URL we want the page to travel to after the initial authorization request. On the dashboard, hit the edit settings button and scroll down until you see the section called Redirect URIs. Enter the url that leads to your Rails method that’s going to send another request to the API using an authorization code you receive in response to the first request.
In my case, it was a custom route called ‘http://localhost:3000/api/v1/logging-in’ that points to the create method on my users controller.
Inside this method, we first make a post request to ‘https://spotify.com/api/token’ with a body that includes the code we received in response to the previous request, the SAME redirect URI we included in the initial request, and our client_id and client_secret from the dashboard page.
Then we define the response body as a variable ‘auth_params’ and immediately send a get request to ‘https://api.spotify.com/v1/me’ with a header that includes the “access_token” of your auth_params response.
Finally, the response to this last request will give us all of the data about the logged in user. I saved it as user_params, which I used to create a new user in my database, then redirect back to my frontend webpage.
Here at the bottom, we redirect to the welcome page of our front end site!
Here’s what the final product looks like: