Automate Spotify API with Python Requests

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to another video in this video I want to show how I'm going to use the Spotify API using Python so in a previous video about scraping Spotify using beautifulsoup and somebody put on a comment saying is there a specific reason why you'd want to scrape the Spotify website instead of using their API so I did respond to this and said but I just kind of wanted to a project so that I could use beautifulsoup to scrape something but there is an API as well so I thought I'd make a video about how to use the API instead on why it is superior to scraping of scrape Spotify a few times and actually the structure of the HTML has changed so I think when I was in that video I looked at the h2 tags to find the to find the heading of album so as I could have found all the albums of grapes Spotify previously and actually the that has been burning h3 tag so over time it does change whereas the API doesn't change in the same way I mean Spotify themselves to use the API and lots of other third parties use Spotify API as well and pay for it and so if there's any major changes coming down the line then they're likely to notify you of that it's not always the case but it's more likely that it's going to be more structured more reliable you're probably going to get more information from the API than you are from scraping the website so here is an authorization guide which will take us through the various ways you can authorize yourself to use the API and there'll be a few different ways depending on what you want to do the way that I'd like to do it is using the client credentials flow it says the client credentials flow is used in the server server server authentication so I don't want to do it from the front end I'm interested in just doing it from my computer or a server using Python requests library to authenticate and then ask for information about a playlist for example that's what we'll do in this video so the it says only endpoints that do not access user information can be accessed well that's fine because all we want to for this one we don't particularly want to change any user information relation of that we just want to return information about a playlist and the songs within that playlist so this should be fine it's got little diagram here of what happens think what it is going to do is you're gonna request an access token initially and then use that access token to authenticate yourself to return information about the about the playlist and the tranqs so what you have to do initially it says you do log in with your client ID and secret key and you get an access token so if we go down here there's two steps so have your application request authorization so you have to hit this particularly endpoint account stop Spotify comm forward slash API four slash token and you have to walk in code your client ID in your client secret so what are your client ID and client secret all right so here's our Spotify for developers website and I've logged in and I've gone to my dashboard and here you can see there's an app so what you do is you create an app and when you have a look at that app I've called this one pretty playlists it says here you've got a client ID and then you've also got a client secret now I'm going to reset this client secret after I've made this video but what you have to do is you have to make a combination of these two pieces of information and encode them as base64 and then you send that to the authentication endpoints and if everything is fine then Spotify will send you back an access token so this is showing us that process in a KO request and this is the response that you get so you get an access token the token type and when it expires so that is the first thing that we'll do so we're going to get that and then with the access circ which they send back then you can just hit whatever APL you want so the playlist or the tracks API and it'll return the information you need let's go to Python and have a look at how you would do this in vs code I've set up a file called main PI and I've set up a virtual environment as well what going to do to hit that API is we're going to use the pythons requests library and the requests library isn't part of a standard library so we have to install it so that's the first thing we'll do so you need pip3 install requests excellent so now we've installed that what we will do will just import it and at the start of our code okay so so we have to send a post request to this endpoint what I will do is I'm going to copy this curl request and I will just paste that in here and comment it out because this will give us everything we need to we need to know so the post request it's also it's the type of request we want to make the minus H parameter tells us what the head is gonna be and the header is going to be this authorization basic followed by whatever our base64 encoded client ID and client secret is and then we've got minus D which is what the data payload is which we're sending with the request and in this case it's going to be grant type equals client credentials and lastly it's the endpoint we want to hit which is account still Spotify too common for slash API forward slash token so let's copy that out first and we're gonna save that same author URL okay and then I'm also going to set up or it is Walt header and actually I'm just gonna set up as an empty object for the moment and I also have off data which will also be an empty object at the moment the first thing we want to do is we're going to want to base64 encode client ID and client secret okay so normally what I do with my secrets is I import them I keep them in a separate file because I can always ignore them whoever said if I ever commit these to a repository so it's gonna save this file in the moment then I'm gonna set up a new file called secret and stop hi and I'm gonna have client ID and I'm also gonna have client secret so I can keep those there and I can just import those into my main codes from secrets import and I'll import everything then I can just use client ID and client secret where necessary all right so to base64 encode something I didn't know how to base64 encode anything so I found an article so I found this article encoding and decoding basics for strings in Python brilliant this explains very well why you need to do that or what the purpose of it is I'm not going to go into it because this document will explain it much better than me but it'll give us the instructions down here that we have to follow in order to encode something so first thing we have to do is we have to we take our string let's say here it's Python this one and then we have to turn that into bytes and then the bytes get encoded into base64 and then the base64 gets decoded back into ASCII and that's what weekend up with saying seems a bit long-winded but it seems straightforward as well so it all happens by this base64 library in the standard library so I'm going to copy all this in to my code and I'm gonna take my base64 imports and I'm going to move that up to the import section and rather than having Post in this fund because that's not going to help us what I'm going to have is an F string what we want to encode and basically for is a combination of client ID : client secret so that's what we need to do then what that should do should encode this as base64 and we're gonna print base64 message and see what that gives us I'm gonna save that and I'm going to just run it so okay so that's showing is what our base64 encoded taking this alright so that's useful so the next thing we have to do is we actually have to hit this URL so we're gonna do that would we in the site to their variable rest equals the quests dot post and then what we need to pass is the auth URL and then we want headers equals or and uh and we want data equals or data but I've also realized that we haven't actually signed anything cuz those two the headers and the data are empty at the moment we've got this grant stipend client credentials that's that they're gonna be the data so let's put that in first so we'll have Wharf data and it is grant type and I'll set that equal to Wyant underscore credentials and that's the only thing we need to send with the data and the auth header the only thing we need to send for that is the authorization session and we need to set that equal to basic and that's got a space and then we add our base64 message or encoded string same place 64 message let's print R is and see what we get and we run this say all right so that's when this got a response 200 that means it's been successful brilliant so we need to interpret what's in that because that says that this is a response object and this is going to be returned in JSON so let us import the JSON standard library module response object equals raised dot JSON and then we can print that out by saying JSON dr. dumps response object we can just print that out by saying indent equals to and they'll show pretty printer actually so let's save that and run okay so this is what's in that response object so we've got the access token which is this long field here and it's a bearer type and it's going to expire in 3600 seconds this is good say let's just comment that out so what we're gonna do we just need our access token is equal to response object exists token in or does it tidy this up a little bit I think I might make this into a function and then I can return this access token so if I send it the client ID and client secret their nightly encode air do a little bits and bobs and then it will just return the access token we're going to call this function to get access token and we're going to be passing this client ID and client secret and then I'm going to move all of this out to be in that function and then I'm just going to return the access token so then if we say get access token client ID and client secret and we'll assign that to access but we'll just call it token so it's not confusing so token nickels get access to a good client ID client secret and then we all say print token yes excellent that's what we need okay so that's good news in fact I'm just gonna get rid of that print token don't need any more better write another function I think because now we've got access token what do we need to do we need to an end point so if I go to yeah this is the backing of documentation the authorization guide so the first step was have your application request authorization and we've got this token which is great and then the second step is use the access token to access the Spotify Web API and what you do is you just make another request like this go request with a header of authorization bearer with the token and you hit whatever the end point is in this case it's tracks in our case we want to hear a particular playlist so I've actually set off a playlist called pretty playlist and it is this start just selected a few songs from one-hit wonders because they're amazing and I'm going to copy the playlist link and I'm gonna say so our playlist ID is equal to this and we don't want the first part because that's how to access it on the office-boy if i website we just need the actual ID says brilliant we've got that and then what we need to do is have another function to request the tracks from that playlist so I'm going to set up something called def get playlist Trax and I'm gonna pass in our access token and our playlist ID okay so what we want is the endpoint documentation and this has got an is the API endpoint reference and one of the endpoints is to get a playlist and it's this here on the right-hand side that we were after so it's gonna be a get request rather than a post request and this is the endpoint API Docs but if I go come for such b14 slash payload playlists and then you send the playlist ID which we have let's say our playlist and point is equal to we don't need to get bit let's make this into an F string because then that allow us to just play this with playlist ID and then that's the endpoint which we're going to be hitting and then we can set up the gets header and call it because we're getting something is going to be equal to and we'll do it all in the object here this time rather than adding something to an empty object so authorization and this time is going to be bearer and we'll just gonna add token you don't have to encode it or anything that should be our header then we will say we want to go and get a response is equal to requests don't get and we want to do playlist endpoint and the headers he calls get I get hey Heather so playlist object it's gonna be equal to result dot Jason and then we can return the playlist object that should be good so down here in our main part of our program there's comment that so let's comment this here to say this is the API requests those on that put to get the token and then done that to get the playlist ID will say track list is equal to get playlist tracks and we're going to send token and playlist ID and then we'll print json dot dumps tracklist and again what so indent because ii and see what that produces and run it for a long time so pretty made some errors here and there let's go command K and run it and like the rest name of course we haven't anything okay oh yeah no included this ending should be there okay let's try this now whoa loads and tell you what let's make this bigger and go through I mean this looks pretty successful I know a few of the checks that I've put in here and I can see that we've got we got here the newer ice is back that looks promising we know we've got Ice Ice Baby as one of our songs so there you go we've managed to authenticate against the Spotify API and return some information I'm going to put this down and rather than look at it in the terminal I'm going to write it into a file so with open track list dot JSON and we'll do that and to write as if so then we're gonna do JSON dump and we want to dump the tracklist into if this is the file that we've just talked about so let's just run that and then we've got this trackless JSON and if we go in there should be able to format this documents so if we look at the so I exported this into tracklist got Jason and yeah we can just kind of collapse and expand the various parts of the of the file so you can see the structure so at the start of the video I mentioned about how you get so much more information but you use the API rather than scraping and this is huge this is a massive massive file with it's got 1,200 rows in it it's got a lot of information album artists all kinds of stuff URLs say if we want to get the actual tracks out of here then this is the start of our our JSON and we're looking for a list of tracks for the playlist so here this is just some information about the playlist itself because it's at the first level so it's got some images associated with the playlist it's got the name of the playlist here the owner this is me which is great then we've also got so here we go tracks so yep tracks is going to have all the information so you've got tracks and within tracks we've got the URL of the playlist I think we've also got items so within tracks we've got items so the number of items within I guess the number of items is the number of tracks I'd imagine so if we look at one of these so yeah so items has got I'd imagine five different I've only got five tracks actually in the playlist I think so one two three four five yeah so if we look at the first one so in this item we've also got we've got some information about the item when it was added some other bits and bobs then we've got track so yeah we need so yeah within tracks we've got a number of items which is number of tracks and within the items we've also got a track object which older four is the item but I guess the item is a track I don't know it's getting confusing there so in track you can see you've got information about the album about the artists about the available markets and then you've got information here like the name so we know this is kung fu fighting and we want to get the artists as well they have the artist is a is a list of object so using that we can go and try and get this information out of there so let's start for loop so for and we'll call it t in tracklist and we know within track lists it's gonna be within tracks and then it's gonna be with some items and I think that's it so let's just try and get the name of the song song name it's because that's gonna be the lowest level of guess if the items say for RT which is tracks tied and items within that we're gonna have track and then within track it's the name that we want and then we'll print some name now let's run that and see what it does yes country fighting here comes the hotstepper somebody that I used to know jump around and Ice Ice Baby fantastic okay well that's what we want so then let's just get the artist as well so that's gonna be in T track and it's gonna be artist and we said it was gonna be the first item an artist I don't think there's gonna be anybody else in and any of these songs with two artist names otherwise we would probably just say we'd start another loop here saying for a in now let's just do this this is the long way but it's the most thorough I guess track artist and then we'll do prints that's all yeah print print a and then sets name so a name they print all the artists out which would be good say and then at the top of this we're just gonna do and just do a separates up for each track so this is really just to demonstrate that you can get the information from the API pretty easily and there's lots of information in there so you have to dive a little bit deeper sometimes to actually get it then if we run that let's have a look nope we've done something wrong Oh these artists yes it is that's the reason why artists that's what we gonna be the problem right that's right now and there we go I've got Cole Douglas concrete fighting any Kamoze here comes the hotstepper got jetan Kimbra so we did have two artists in one of the songs somebody that I used to know and house a painter Brent and vanilla ice ice ice baby so we got all our tracks all the artists for each track and the name of the song and we printed them out so what you might want to do then with this is then use this JSON file as a data file and you can probably just build a static website with it so just pulling out the various bits information that you want you've I think for each track that you've got you've probably got a a URL so here we go so we got artist URL and things like that so you can link everything back to Spotify get some album artwork and some and the playlist artwork and just throw it into a website and you're good to go anyway I thought that might be interesting taking a little bit of time but hope it's helped see you next time
Info
Channel: Pretty Static
Views: 3,361
Rating: 4.9411764 out of 5
Keywords: python, automation, api, spotify, requests, spotify api, pretty static, automate
Id: 9mKAAWRheTA
Channel Id: undefined
Length: 29min 52sec (1792 seconds)
Published: Tue Jun 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.