How to Authenticate and use Spotify Web API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys on my maker play channel i'm working on a project that uses the spotify api i'm actually going to create a little box that's got an echo dot inside of it with an nfc reader so this piece up at the top has the nfc reader concealed inside of it so whenever you take the cd which have the tags on the back and now you just once you set the in there it will start playing [Music] alexa stop and put some mc tags on some old cds i have and when you place the cd on top of the box it's going to tell spotify to play that cd on the echo dot that's inside that box i'll put a link up here or somewhere down there to that project if you want to go check it out but in order to prepare for that project i had to learn how to actually use spotify api so i created a quick javascript application to exercise all the apis make sure i understood how it all worked so then i would know how to use that within that project i figured since i already learned how to do that that'd be a good video to throw out here on my code life channel plus you know months from now when i need to go refresh myself on how this works these videos are good to refresh my memory too so with that let's jump in and talk about the spotify api i'll show you how to go in there and set up an app within their dashboard and how to make the authorization calls to get your off tokens that you need then how to make some api calls to fetch a list of all the devices that you have on your spotify account so let's jump into that so the first thing we gotta do to use the spotify api is to go to their website and create ourselves an app and that will give us our client id and client secret that we need to authorize ourselves to call their apis so if we navigate out to the developer.spotify.com website it will land here and we want to go into dashboard and if you're not you'll have to log in i think that the user apis you may have to have a paid account on spotify but 100 sure of that but i do have a paid account so i do know it works for me and we want to hit this create an app button and give it a name i'm just simply going to call mine uh sandbox just as a test i think i can leave that blank accept all their terms hit create nope i guess you can't leave description blank uh playing with the api hit create and now that create our application and the two pieces of what's important here is we need this client id right here and we're going to need this secret id right here and yes i'm not going to blur these on the video because once i'm done with all this i'm going to go back and delete all these so these ids will not work if you try to use them you need to go to the website and create your own so now we have those next useful step is you go over to their documentation and you want to take a look through reading server documentation good spot here is on that quick start and this kind of walks you through how to set up the account which i just did as well as some other apis and library stuff that they use so in this example i did not use any other third-party libraries i am just going to write raw javascript code and actually makes the restful api calls and the reason i want to do that is i want to make sure i actually understand how the apis work what do i what json do i need to pass to the api for to work what json is going to return back from me i don't want that abstracted away in any sort of libraries because for my open project i'm not actually going to be able to use javascript or use some libraries i'm going to write all this to work on an esp32 microcontroller which means i'll have to be able to write all this in c plus so i need to know truly how it all functions first thing i know we have to do is do authorization so spotify apis use oauth for authorization like most other websites out there so to start with authorization you click on the docs go to general hit guides and then we click the authorization guide and then this is what walks you through the flow of how to get an off token i'm going to walk through this demonstrating it as i write the code to show you how this flow works and what this starts with is you're going to have to have a callback url that you pass to it and that callback url has to be registered with your application so we're going to go back to our dashboard go back into our app and under edit settings there's this redirect url and you need to populate the sheet redirect your around with the url that your application is being hosted on so for me right now i am hosting this on my local box i'm using visual studio code with the live server plugin so i can actually host the server locally and that's going to be on 127.0.0.1 and i know for my live server it's going to be running on port 5500. so i can put this into the right directory around and this is simply just a string mat and he's heard spotify doesn't actually have to be able to access this url because obviously no one no one outside of my home network can navigate to this site but again for this to work it's not a matter of spotify being able to hit this url it's just a matter of your javascript application and browser being redirect back this url click add on that got that set up hit save so it should be good there we got our app all set up in spotify now let's jump over to some code and see how we're going to use this so the authentication workflow starts with request and authorization to access data for us that's just a redirect to the spotify website and pass on a certain set of query parameters we go down here we can see what those query parameters are that is we're going to pass client id response type redirect uri state scope show dialog so let's take a look at the code for that so i've set up a web page here and i've got an input box to take the client id got it input control take the client secret and on the button i'm going to call request authorization function we take a look at our javascript code our request authorization function is going to fetch our client id our client secrets we're going to just go ahead and set those in the local storage for us so we can save them for future use but then we're going to build the url that we're going to redirect to so if we look at that we can see here we're setting our client id and we're going to add response type which our response type is we want to code our redirect url which is coming here from the top which keep in mind again this redirect url uri has to match what we set up in the dashboard so this is the same value as what we put in the dashboard show dialog equal true this is optional i'm putting it to true here just so as i go through these demonstrations it will always display the spotify dialog if this is not set to true and they've pre-authorized you before then this redirect will automatically redirect back and you won't actually see the screen and finally set in scope scope is where we get to ask for what permissions we want and here i'm providing a nice long list of lots of stuff because i want to play around with all their apis keep in mind this list of scope can be any list of permissions that you want from spotify you just want to make sure that you're asking for the permissions you need for whichever api you want to use later on then finally we do the actual redirect so here we set the window location and we redirect that url let's execute this and see what happens so i'm going to need my client id and secret id grab my client id i'll paste that in grab my secret id and paste that in and now we're going to hit this request authorization and here at the top if we copy that you see this is that url that we built so we're sending across our client id our response code we get our redirect which is url encoded show dialog true and then scope which is all those parameters that we asked for again you can see this is all url encoded and based off of that we can see here it's popped up and telling the spotify user here are all the permissions that we're asking for and down here we agree or disagree to allow it i hit agree now you see it redirects us back to our web page but look at all this data that's up here on our url so on the redirect it came back with this code so this is the code we need for the next step to actually get our token and our refresh token so let's write some code to be able to handle parsing this code off the url that get redirected back to us so first thing we need to do is on our page load we need to detect are we actually being redirected and have that code or is this the first time the page is being loaded and it doesn't have that code on it i did just for simplicity i'm doing the on load on the page to call the unload but there's all kinds of ways you can have this function called i'm going to simple around so i want to inspect my url so if our euro has query params on it i want to call a function called handle redirect then the handle redirect we need to look for and parse that code off the url so in the handle redirect i'm going to call another function to parse the code off just to keep my code isolated and clean the code function is going to look like as we're going to grab the query string make sure there's actually data there then that data we're going to search for the parameter called code so if we go back here we can see on the redirect we had this query param that had a property of code with the value of the actual code that was returned find that code we're going to return it so we set it here that's good so now that we have the code what do we do with the code so we go back look at their workflow now that we have the code step two we have to request access and refresh tokens so let's go take a look down here so now we're on step two so we want to make a call to account spotify.com api token we need to pass grant type code that we just received with the authorization call and then our redirect url and then for authorization we've got to be able to pass in the client id and client secret as basic authorization so to do all of that calling myself another function is a fetch access token now that we have the code we need to fetch the access token and do that we have to make an api call which is going to be a post call to the api token endpoint with this json body of a grant type the code itself the redirect uri so we're going to build that body which happens to not be json but it's form post which is name value pairs so here we have our grant type one of the observation code here is the code that we just received we'll put it there our redirect uri again is the same uri that we've configured for passed our client id and our secret id and then call authorization api which for me call authorization api it's right here where i'm using the xmlhttprequest object to be able to do a post token which i've defined as constant appears token is the api endpoint and then we're going to set the header type of our content type putting the authorization in the header which means i don't need to do it in the body that's being redundant right now but oh wow and then we make the api call and then the response will be handled by this method don't handle authorization response we're going to see if we got a successful 200 if we did not let's just log at the console and display our error message this 200 we're going to parse the json body log in for debugging purposes then we want to see did we get an access token if we got that access token let's go ahead and save it to our local storage and did we get a refresh token if we got the refresh token let's save that to local storage because we'll need that for later but now that we have this access token we have what we need to actually start making api calls so let's execute through this and see how it works we've got a client id that's not good why is my client id invalid i also forgot that when we get the redirect back it reloads our page fresh so our client id and client secret aren't there unless we're persistent to local storage and read them back so let's throw that code in real quick so we're setting the local put them in local storage here but we need to on our page load read those back so up here on page load or read those back from storage and another quick thing too as you see every time i refresh my page now that this code is on there it's going to keep refreshing and using that same url so i also want also help with debugging i have to delete that code off the address bar i want to put in here on my handle redirect let's go ahead and clear that off the redirect url so that way i have a clean url each time the page refreshes so now you see no more code up there to keep giving us that error post client id paste client secret request authorization agree now that we redirect let's hit f12 and if we look in our application store we'll see we get our refresh token we'll get our access token and our client secret client id so again this access token is what we needed so now we have our access token let's make our first api call which for me will be let's make a call to list all the devices that are attached to your spotify account post in some html here that's going to create a it's going to create a pick list that will be populated with all the devices and also we'll have a button here that will allow us to refresh the device list which will make the actual api call here we go there's our pick list of course it's empty right now so i've made the api call yet so now let's implement api call when you press this button jump over to our javascript i'm going to have this call a more generic method that makes the extra api call because writing this already i see that most apis have a very common pattern and can be normalized into a single api call so the call api is going to take the method i passed in so we're going to do a git call we've got to set up content type which for these api calls is json or authorization which is going to be that access token that we got we're going to send that off and then when we get a response back we're going to call the function that was passed into here which in this case i want to call the handle device response now let's go with that method so handle device response is going to check did we get a 200 if not it's a 401 that means that our access token has expired and we need to go through the process of refreshing our token which we will do that in a moment else if it's not 200 or 401 any other error we're simply just display the error it is 200 we're going to parse the json we are going to clear out the content of our pick list so i need to have that remove all items function which then this is taking the html element and deleting all the children out of it so that way if we call this multiple times we're not just adding more and more to list we're actually clearing the list and reacting to the list once we remove all those items then we're going to iterate through the devices i return from the api and for each of those items call add device which is going to also take the html element we want to add them to so here's our add device method which is going to create the option node set it the id of the device id set the name is what's going to be displayed in the list and add it to the item on our list so in addition to quality pattern we also need the url we're calling which i put in my urls here at the top for convenience so we add that in we go back now let's refresh our devices also bring up our dev tools so we can see what's happening going on behind the scenes so from my network refresh devices and there we go we see we got one two three four five devices that are on my spotify accounts take a look at devtools and see what happened here we can see here's that api call so we made a call to version one me player devices it was a git call we can look and request headers that we passed our off token in the as a header our content type was json if we look at the results of this we get a json result back which is an array of five devices for each device you get an id it's active what the name was what its type is in particular case yep michael's clock says speaker because that's for me it's an echo smart speaker so that is the round trip on how to make a call to spotify to get an off token and to make an api call so now let's see handle that situation where we get a 401 back that means our access token has expired ford i can tell with spotify the access tokens are good for about an hour so they last about 60 minutes so let's implement the refresh access token method so refresh access token it is going to be similar to when we requested where are you at so it's similar to when we did the call authorization api to get the off token to begin with put this in here so we call it first we need to actually get the refresh token because we've got to be able to pass that back to spotify we're going to build our body time our grant type is a refresh token whereas last time you see our grant type was an authorization code we got to provide the refresh token and we had to provide our client id and then this will make that same reuse this code here to make the api call which also it's important an api call you also have to provide your client id and secret id in the header as authorization so it takes both your refresh token and your client id and client secret in this figure method to refresh that token there we go that is how you make the api call now implement out the rest of all those apis copy all that code over copy this all over and now we can see going through some of the other apis i implemented when you refresh the device list we get those from that i can call and say i want to refresh my playlist so here's that api call so recall under the v1 me playlist and it returns back an array of items or these are all of the playlists that i have defined so let me take a look see here's those different playlists let's look at on these alternative rocks so now that i have that playlist i can make a here api call to fetch songs or tracks that are inside that playlist to make an icon now see here's all the songs within that playlist take a look at that api call we see here it was b1 playlist this is the id of the selected playlist and then tracks let me see that again returns an array of items which these are the actual tracks that are in the playlist and then finally down here we have some buttons where i can say i want to play so if i say echo show which is sitting here on my desk i select let's do chop suey and say play if you can hear the song started playing on the echo show sitting on my desk pause it just can't play it for too long or youtube will flag this as copyright violation when i post this video let's take a look again at devtools and here we can see where we call it play so this api was v1 me player play and the device id passed along because and i told it to play on this device here so i took that device id so the play api takes a json body which is going to be the id of the playlist that you want to start playing which is the one we selected so that's that id here but then you also can set and then position tells you where into that playlist so which track into it you want to play as grace i think it's zero base so we just chose the second track which is one and then one i paused it this is the mini player pause and a device id to pause it now this player so this get call here which was calling to get the player that is what returns information about which of the devices is currently planned spotify and what's being played on spotify so you notice down here that's where it populated this image and the title of chop suey because that was the song that was being played at that particular time but there you go there's how these apis work i will put a url possibly on the screen here as well as down in the description of where this sample app will actually be hosted so if you simply want to go out and interact with it you can do that plus a link to the github repo for the source code so you can review that and do what you want with it and again i'll have a link i'll also create a link to my maker play video where i'm using all this code in the microcontroller to be able to detect nfc tags on my cds to start the echo dot playing spotify songs so you might want to go check that out that's pretty cool and that's it i appreciate you watching if you're so inclined hit that like button i'd really appreciate if you provided the comment get some feedback down below if you have any questions definitely leave those comments down below i reply to all of them and i'll see you in the next video
Info
Channel: Maker At Play Coding
Views: 24,165
Rating: 4.9298244 out of 5
Keywords: michael hawkins, Maker At Play, MakerAtPlay, Code Life
Id: 1vR3m0HupGI
Channel Id: undefined
Length: 23min 38sec (1418 seconds)
Published: Sun Jan 31 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.