How to Use Spotify's API with Python | Write a Program to Display Artist, Tracks, and More

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video I'll show you how to use the Spotify API from python code specifically I'll show you how to get your Spotify access token and then how to use that token to interact with different API endpoints once we know how to do that we'll write a basic program that will allow us to search for an artist and see the top tracks that were written by that artist after going through this video you should have a good understanding of how the Spotify API works and how you can use it for more complex projects now before I get into it I will mention that my name is Tim I'm a developer advocate for lenode and I run the tech with Tim YouTube channel where I have hundreds of other programming tutorials so feel free to check that out I hope you're looking forward to the video and with that said let's get into it alright so let's go ahead and get started now the first thing we need to do here to interact with the Spotify API is create a Spotify project or application now we can do that from the Spotify developer website the URL is developer.spotify.com now from this website you're going to want to go to your dashboard and sign into your Spotify account so let me do that and then I will be right back all right so I've just signed into my account and it's brought me to my dashboard and you can see here I have some existing applications that I've worked with in previous videos now for this video we'll create a new application most of you won't have any here so just click create app now from create app you need to give it a name and a description it doesn't matter what you put here so anything will work I will say python Spotify API and then python Spotify API for the description as well okay so after creating this project here what we're going to want to look for is the client ID and the client secret now within this project we can also view information about our usage so how many people have actually utilized this API how many requests have been sent Etc we don't really care about that for this project but it is nice to know if you're working on a larger project where you're going to have some kind of backend server that's maybe sending requests on behalf of a specific user so again what we want here is our client ID and our client secret and where we're going to be putting this is in an environment variable file so let's actually set that up first so that we have a place to copy this into so on the left hand side of my screen you can see I'm inside a visual studio code this is the code editor I'll use for this tutorial feel free to use whatever you'd like now I'm going to be using python specifically python version 3.10 however this should work with any modern version of python so I'm inside a new folder here in vs code and I'm going to create a new file and I'm just going to call this dot EnV now this is where I'll store my environment variables for my client ID and my client Secret so I'm going to create a variable here client and then ID and this will be equal to the client ID here so let me copy this in and then we need to do the same with our client Secret so let's create that variable and let's show the client secret obviously you don't want to show this to people but for the video this is okay I will delete this project afterwards and then paste the client Secret inside of here okay so now that we have the client ID and the client secret we don't actually need access to this page anymore so let's close that and head into Visual Studio code now that we're here let's create a python file and see how we can load in our environment variables and use those to request a Spotify access token alright so I'll go here to create new file I can just call this something simple like main.pi and at the top of my program here I need to import a module that we actually need to install so I'm going to go to my terminal here let me just clear this and there's two pip packages that we need to install for this tutorial to work now the first is going to be python.env now this allows us to very easily load in our environment variable files and just makes working with environment variables much easier so let's install that and if for some reason this can man does not work for you then you may try pip 3 install python.env especially if you're on Mac or Linux alternatively you can try python hyphen M pip install and then the package name or Python 3 hyphen M pip install so try one of those four commands and that should ideally work for you otherwise you will need to add your pip to your system path okay so now that we've installed python.env the next module we're going to need is the request module so I'm going to say pip install and then requests like that again try pip 3 or python hyphen M pip install if this command does not work for you okay so you can see I already have these satisfied but that's all we need to install uh for the rest of the tutorial so now at the top of our program we're going to import the dot EnV package specifically we'll say from.env import load.env and then we're just going to call this function and this will automatically load our environment variable files for us now they're only going to load if you've named them.env so make sure you have a DOT EnV file in the same directory as your python script now that we have that let's load in our client ID and our client secret we can print them out and just make sure it's working then we can move on to doing our authorization and getting our token that we can use based on our client ID and our client Secret so I'm going to say client ID is equal to and this reminds me I now need to import the OS module and it's going to be OS dot get EnV which will get the value of an environment variable and in this case we want client ID now we'll want the same thing down here but this time it will be the secret so let's just change the text here okay so now we should be getting these values so let's print them out client ID and the client Secret and I will run my code by pressing the Run button here and let's see if this works and notice it does we get our client ID and our client Secret perfect so now that that is working let's quickly have a conversation about how authorization works for the Spotify API so the first thing to understand here is that authorization and authentication differs based on the different apis that you're using for us we're going to be using an API that just allows us to query information about the Spotify Library so artists album playlists songs tracks Etc right however there is another aspect of the Spotify API that allows you to control somebody's Spotify player and to have information about a specific user's profile or their playlist we're not going to be using that part that actually requires that you authenticate a individual user and usually that's done through some kind of website or front-end user interface in our case since we're using a back-end kind of script here or CLI script we're going to be doing this just using our clients ID and our client's secret so actually let me just pop up a little diagram here from the Spotify documentation to show you exactly what we're going to do so again we're using the client credentials workflow there is another workflow for user credentials and that's specific users using your application in this case we just have one set of credentials and anyone who runs our python script will be using that set of credentials okay so here we have our application now the first thing we need to do is request an access token we do that by sending our client ID the client secret and a few other pieces of information that I'll get into to the Spotify accounts service now this is a different service than the main API this service then returns to us a temporary access token that I believe has an expiry of 10 minutes it's either one hour or 10 minutes I can't remember the exact time frame either way it has some expiry date on it it then gives us that access token and having that access token we can then send requests to the Spotify web API which you can see right here which allows us to get information about artists tracks albums playlists Etc so fairly straightforward but there is kind of a multi-step process here and one thing to note is that if your token does expire then you need to request a new token or use something known as a refresh token but we're not going to get into that in this video okay so now that we understand that I will just walk you through exactly what we need to do to get this token so it's actually a little bit complicated Spotify doesn't make it super simple you can see here that we need to send in our request body a grant type and that Grant type needs to say client credentials specifying that we're going to be sending our clients ID and our client secret and we need to have our data encoded in this format we also need to send this to the slash API slash token endpoint which is associated with the if I could find it here where is the URL the accounts.spotify.com URL okay so this is the base URL then we have headers we need to pass our authorization header which I will show you how to create as well as the grant type once we do that it will give us our access token and the expiry time store all right so let's go ahead and do that so I'm going to write a function here from inside of my python code we can get rid of this print statement and I'm going to call this get underscore token because of course that is the first step that we need so inside of get token I'm going to create the authorization string that I actually need to encode with base64. now again this is a little bit weird and complicated but essentially what we need to do is take our client ID concatenate it to our client secret and then encode that using a base64 encoding and that's what we need to send to retrieve our authorization token so I'll show you how we do that but it is a few steps so I actually need to import up here base64 which is a built-in module in Python then I'm going to go here and say my authorization string is equal to my client ID plus a colon very important that you have the colon plus my client secret now that I have that string I actually need to encode it so I'm going to say auth bytes is equal to and then this is going to be auth string Dot and code and I'm going to encode this with utf-8 then I need to encode this using base64. so I'm going to say auth base 64 is equal to then I'm going to say string and this is going to be base 64 dot b64 in code I'm going to pass to this my authorization bytes and then I'm going to pass utf-8 here for turning this into a string again I know it seems a bit strange but this returns a base64 object of some sort so we need to convert that into a string so that we can pass that with our headers when we send the request to the kind of accounts service API all right so now we're going to write out the URL that we want to send a request to so this is going to be https colon slash accounts dot spotify.com slash API slash token and then we need to create our headers so headers are going to be associated with our request we're going to be sending a post request to this URL so the first header that we need is our authorization header make sure you spell this correctly which I did not and for our authorization header we're going to pass the string basic up an empty space here make sure you have a space plus and then we're going to have our auth base 64 strict so this is where we're sending in our authorization data and this is where it will verify that everything is correct and then send back to us the token next we need to specify our content type now unlike usually where we have our application Json here we actually have to have this type which I'm going to copy in just to make sure that I don't mess it up so the type here is application slash x dash www.form dash URL encoded okay so that is all we need for our headers the next thing that we need is our data now as it said on the website there what we need to pass is a grant type and the grant type needs to be equal to client underscore credentials like that and I believe it's a plural yes it is a plural okay so now that we have our URL our headers and our data we are ready to formulate the response or the request sorry so I'm going to go up at the top of my program and say from requests import post which allows us to send a post request I'm then going to say a result is equal to post and I'm going to post my URL with headers equal to my headers and my data equal to my data really this is like the body of the request okay now what's going to happen here is we're going to be returning some Json data in a field known as content from this result object so what I want to do is convert that Json data into a python dictionary so I can actually access the information that's inside of it so really it'll be a Json string we want to convert it to a python dictionary so I'm going to say my Json underscore result is equal to Json dot load s which stands for load from string and then the string I'm going to be loading from is result dot content then what I can do is parse my token my token is going to be stored in a field known as access token like that and then I can return my token so what we'll do now is we will call this function get token let's store this in a variable called token and then we can print the token out so we'll say print token like that perfect I know that was a lot but let's run the code see if it works so we can walk through it so I'm going to run here and I've got an issue here it says auth base64 referenced before assignment okay that's because I made a mistake here let me just change this to say bytes and now if I run the code we should be good and requests got an unexpected argument headers okay just a small typo my apologies so let's clean that up and rerun and Json is not defined okay another error let's import the Json module this is the beauty of debugging live on video and if I run again now you can see that we get our access token all right so apologize about a few mistakes there but you can see that we just needed to add Json we just had to change the name here which I'm sure many of you already caught and then fixed the header's spelling mistake okay so now that we have access to our authorization token this is what we need to use in any future headers uh when we are trying to send a requests to the API to get some artist information playlist information whatever it may be so I'm going to make a function here just for convenience that will kind of construct the header that we need whenever we're sending another request so I'm going to say Define and this will say get off headers like this or actually it's just going to be header because we actually only have one we're going to take the token here and we're going to return the following header authorization again need to spell this correctly and then this is going to be Bearer space plus the token so that's all you need for the authorization header for any future requests you got to use this API token okay now that we have that let's write a function that allows us to for example search for an artist now I'll bring up the documentations you can see all of the different things you can do with the Spotify API what I'd like to do here is just write a simple program that allows us to search for an artist and then get all of that artist's top tracks alright so I've just brought up the Spotify API documentation there is quite a bit of documentation here but I'll quickly click through a few things and you can see what we can do so we have access to albums artists write audio books browse chapters all kinds of stuff here and really just shows you what the URL is going to be as well as kind of all of the values or parameters that you need to pass to get specific information now you'll notice here when we're looking at for example the artist endpoints and we want to get the top tracks of an artist it requires that we pass an ID for that artist you can see it is a required field now the issue is I can't find the ID of an artist unless I know what that artist is or I know what the ID is already so I need to kind of search for an artist find the artist I'm looking for and then grab the ID from them so the way you do that is you go to search here and you can see we have V1 search if I click into this it shows you all of the different values you can pass as query parameters to this search URL so we have q which is our query string I'll show you how we construct that in a minute and then we have type now type is specifying what result we want to get back from this search in our case we'll be searching for an artist but you can see we could be searching for a track we could be searching for both a track or an artist all kinds of things we can look for here so really the step is going to be search for an artist find the artist we're looking for get their ID and then get the tracks associated with them obviously if you want to do something different you can have a look at the documentation it's pretty straightforward and what I'll show you here will kind of translate into any other endpoint you want to call so let's just look at this endpoint here it is https colon slash api.spotify.com V1 search so let me just save that we'll go into vs code and let me make a function here that is going to a search for artist okay now we need the token as well as the artist's name that we want to be searching for in this function so let's start by defining our URL we'll say our URL is equal to this if we can put it inside of a string okay perfect and then we want to get our headers so I'm going to say my headers is equal to get auth header and I will pass my token and now I need to construct my query so to construct a query for this search API endpoint is actually a little bit unintuitive but we're gonna do the following we're going to say query is equal to we're going to use a python F string we're going to say Q which is the query string is equal to and then the first thing we're going to place here is whatever the text value is that we're searching for so in this case I'm going to be searching for the artist name but if I was searching for a track name or searching for any other name whatever the values I'm looking for I would place it here okay so after I do that then I'm going to put an ampersand and the next argument that I want to have here is type now for the type I need to specify a comma delimited list of things I could potentially be looking for so in this case I'm looking for an artist but if I was looking for an artist and a track I would do artist comma track right pretty straightforward now after that we have some optional arguments we can pass but in my case I only want to get the most popular artist associated with this search result so I'm going to say limit equals one so it just gives me the first artist that pops up when I search for this specific name now it is possible that no artist will appear if I type in an artist name that doesn't exist but the chances that there'll be many artists that show up when I search for even a popular artist so I just want to grab the first one and then we can kind of parse that out and use it okay so now that we have our main URL and kind of the query component uh which is really the query parameters of this URL I want to combine them together so I'm going to say my query URL is equal to URL plus a question mark plus my query now given I could just put the question mark here and I could remove the question mark and I would probably make it a little bit clearer okay now that we've done that I want to use the get method for this endpoint so this other endpoint here we're using post uh can I find posts right here we want to use get now so I'm going to import get here go back down and I'm going to say result is equal to get I'm going to pass my query URL I'm going to say headers is equal to my headers okay now similarly to up here we need to kind of parse this Json result so I'm going to say Json result is equal to json.loadsresult.content and for now let's print this out let's see what we're getting and then we can go from there so I'm going to print Json result okay so now that we have our token let's call this function so search for artist and for the artist's name uh let's just pass kind of a popular artist here let's go with something like AC DC I guess that's more of a band but that should show up uh and we'll see the result that we get okay so let's run the code here and see if we get anything and it said we got an unexpected argument okay again gotta fix this so it says headers instead of header my apologies let's clear and re-run and notice that we get kind of this gibberish result appearing so inside of here if you can see we're getting a field that says artist and then within this we're getting items so what we actually want to do is we want to start by grabbing this artist value that kind of gives us this whole Json object or python dictionary whatever you want to refer to it as then I want to grab items because items is what contains all of my different results what I'm highlighting here is actually one artist result that I got so I want to get that result if we have at least one of them then we will look up the songs for that artist otherwise we'll just print out some message saying hey no artist exists with this name okay so let's do that it's clear and close this uh oops that's not what I meant to do let's go back down uh okay so now I'm gonna say Json results equal to this and I'm going to say artists and then items which are fields that are always going to exist now I'm going to say if my Json result and actually we'll have to get the length of this so if the line of Json result is equal to zero then we're going to print no artist with this name exists dot dot dot and we will return none otherwise we will return the Json result and we'll return the very first result like that okay so I think that should be good now let's try this again but we're going to instead say result is equal to this and then we're going to print the result which this time should just give us the individual artist okay so let's run this code and notice that we get just the artist we're not getting any of the other information now just to make sure everything's working let's print out the name of the artist so let's close this and do result and we can say name like that and if I run the code notice that I get AC DC perfect okay so now that we have our artist what we want to do is get the ID of the artist now that ID is stored in the ID field so I'm going to say my artist underscore ID is equal to result at ID and now that I have that I can look up these songs for this artist now I won't go back to the documentation I do have the URL in front of me so I'll just plug it in here and you'll see how that works so I'm going to say Define get songs by artist like that and I'm going to say token and my artist underscore ID now similarly to before I need to have my URL I'll just copy this because it's going to be similar rather than search it's going to be artist slash and then it's going to be the ID slash and then this is going to be top and dash tracks question mark country is equal to us now I'm going to make this an F string and inside of here I'm going to pass my artist ID okay so let me explain what I'm doing here so we have again our base URL and then we're looking for a specific artist and actually this needs to be a plural sorry so let's make this artist then I pass my artist ID which is the specific artist I'm looking for and then I want the top tracks now when I do this I do have to pass a country here uh for it to kind of rank the top tracks by so a valid country is us you could also do say ca any kind of two-digit country code you can think of is going to be valid so just place that here for the country that you're looking for okay so now that we have our URL again I want to get my headers so let's just copy this line from here and now that we have that that should be all we need to do to actually send this request so I'm going to set result is equal to get I'm going to say URL and then headers is equal to headers and then again we need to parse this using Json so let's grab this here and this time is it going to be artists now I believe it's going to be tracks that we want to grab and then items and then we can say return our Json result and let's go here now and say songs is equal to get songs by artist we'll pass our token and artist ID and we'll then print out the songs and then we'll make them look a little bit better in just one second alright so I was about to run the code but I just realized we need to actually remove items here my apologies so just get rid of items and then we should be good to go okay so let's run this and see what we get all right perfect so we have all of these tracks uh they're not very readable obviously but now what we can do is print them out in a more readable format and kind of view the name of each of the tracks that we have so let's close this terminal okay so now that we have our songs let's Loop through them so let's say four and we'll go with idx Comma Song in enumerate and then we will enumerate our songs like that and then what we'll do is we'll print our idx plus one and then we will do actually we're going to do this a little bit differently do an F string I'm going to say idx plus 1 Dot and then this is going to be the song and the name just so we get kind of an ordered list here I need to use my single quotation marks otherwise my F string will break all right let's give this a shot again and see what we're getting now and there we go we have our top 10 songs by this artist awesome so that said I think I'm going to wrap up the video hero quickly scroll through the code and zoom out a little bit in case you guys want to view all of it at once I can kind of copy any of it down but this is how you use the Spotify API really the difficult aspect here is getting the authorization token correct knowing how to encode it using base64 and then how to send kind of the correct authorization headers afterwards once you figure that out it's very easy to use the API and you can reference the Spotify documentation to find any specific information that you're looking for with that said I hope you got some value from this video if you did make sure to leave a like subscribe to the channel I hope to see you in another one foreign [Music]
Info
Channel: Akamai Developer
Views: 206,711
Rating: undefined out of 5
Keywords: linode, linux, cloud computing, alternative cloud, linux server, open source, sysadmin, linode server setup, linode tutorial, spotify tutorial, spotify api, spotify api python, spotify api react, spotify api project, spotify api node js, spotify api tutorial python, spotify api authorization, spotify tutorial authorization, getting started with spotify api, how to use spotify api, spotify api authorization python, python spotify api example, python spotify playlist downloader
Id: WAmEZBEeNmg
Channel Id: undefined
Length: 26min 51sec (1611 seconds)
Published: Wed Dec 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.