Python for API - Learn how to access any API with Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
if you want to be successful in the it field you're going to want to know how to work with apis and that's exactly what i'm going to show you in this video if you're unfamiliar with what api stands for it stands for application programming interface and it's a way for applications to talk to each other when working with apis you can use tools like postman or insomnia but if you want to take things a step further you should be using a programming language like python this will allow you to completely automate anything that has an api available and almost every tool nowadays has an api that you can use today we're going to have a look at an api offered by coin market cap and it's going to allow us to pull the price data of cryptocurrencies now if you don't care about cryptocurrencies that's fine this video will still be applicable to you as most apis follow a similar standard in format so you're going to be able to take what you learn in this video and apply it to any api that you're working with the first thing we're going to do is pull up the documentation for the api after that we're going to create an api key this is going to allow us to make api requests to the coin market cap api servers after that we're going to create the python script that works with the api let's go ahead and jump into the tutorial all right so we're going to start off with a little rtfm we're going to read the documentation for coin market cap api and the documentation for coin market cap is actually pretty good and it's going to be very similar to any type of api documentation that you come across in the industry so we'll have a quick look at that uh the next thing we're going to do is we're going to grab an api key we need an api key to talk to the api server so we're going to grab that and we're also going to import our modules into python the module that we're going to be using for this script is requests so if you're not familiar with it stick around and i'll show you how it works and uh once we get our requirements imported we're going to just do a basic test make sure we can talk to the api server and pull some information from the api server and then after that we're going to build up a class so we can easily make our rest api calls now this is something that a lot of people don't do when they're working with api servers but it's something that you should do you really want to create classes so you have objects that you can work with and it just makes your life so much easier when you're maintaining the code and when you're descripting things out so i'm going to show you the way that i do it and if you can implement it into your workflow i'm sure it will help so let's go ahead and get started and have a look at the documentation here so this is the basic documentation for coin market cap you can get there just through this url slash api slash documentation and it gives you a basic introduction quick start guide and everything like that it gives you example code and you can see i have the python one open but there's java c sharp go and whatever you need having a look at this you can see that it basically imports the request module uh sets the url uh sets some parameters and sends off the request so this is very similar to what we're going to be doing i'll go ahead and show this in the code editor the next thing you want to do is actually generate your api key but before we do that the first thing you're going to want to do is generate your api key so if you just go to the top and hit login you should be able to create an account and it'll bring you to a page like this and you'll just want to go over to overview and you should have a generate key button just generate your key copy it over and put it into your code editor so i'm going to do that right now and i'm just going to create a new file here and i'm going to call it secrets dot pi and i'm just going to call it api underscore key and i'm just going to copy over that api key off screen so heading back here and uh going over to the coin market cap api we can go over here and we can search so let's go ahead and search for cryptocurrency and looks like we found it here and you can see that it has all the api endpoints for any cryptocurrency that you want information on so let's have a look at this first one and click it right there and you can see it gives you this endpoint url and it tells you the payload that it sends back on a success as well as the ones when it is not a success so you got your 400 messages and your 500. so having a look at this one it returns some json data which can be easily brought into a dictionary in python so the first thing in that dictionary is this data field and then within that it's a list of dictionaries and you have bitcoin tether binance coin so it looks like it's just returning a list of cryptocurrencies over on the left you can see there's query parameters and basically these are just parameters or variables that you can send in your request and those parameters are going to affect the way that it sends this payload back to us so having a look at this parameter which is limit it looks like you can limit the amount of data that you get back so if you just wanted the top 10 cryptocurrencies you could set it to 10 and it would just give you back the top 10. and it looks like you can set the symbol so you could set the symbol to uh btc and that should just return the information for bitcoin so anyways that's enough of the documentation let's go in and actually start working with this api okay so we are in our script so we've read the manual so i'm just going to take this out and just i'll leave this like this it's always good to have a reference in your script of the documentation so i like to leave that in there and then up above i'm going to import our modules so i'll go import requests and now i also want to import our api key which we have in that secrets file so we're going to go import secrets and now we'll be able to access that api key variable so let's clean this up a little bit and we've imported our modules so let's take that out all right so the first thing we want to do when we're sending a request is we need to know where to send this request so we need to grab the url so let's grab that from the api documentation so we'll head on back here and you can see here that it gives the endpoint url but if we click it gives the entire url so let's just go copy and go url equals and just paste that in so the next thing we want to do is create a request object so let's go r equal requests dot get which is the method for doing a http get request now in some apis this would be enough but since coinmarketcap requires an api key we need to set that in the header so let's go ahead and have a look at the documentation again and i believe it was in the quick start guide so go to quick start guide and you can see that it sort of sets the headers so let's grab it from their code actually and let's just put that here so the headers are accepts and it accepts application slash json and then it also wants you to set this api key now they have an example api key here which does not work so we need to put in our api key so i'm going to take this out and i'm going to go secrets dot api underscore key and this is going to set our api key to this header now we need to go into our request and then set headers equals headers now this should be enough to have a look at the data so i'm going to go ahead and open up a python console here just so we can test this out and let's just copy and paste this code in so it looks like it accepted that so one thing we can do is r dot status underscore code and we need to spell that right okay so we know that the status code is 200 so it's okay so the next thing we're going to do is have a look at the actual data and the best way we can do that is go r dot json because this is going to be json formatted data so let's go ahead and do that and it's actually going to return us a python dictionary and we can access all the data in here just like we would access any python dictionary so you can see it gives a lot of data here let's go ahead and print this out nicely so i'm going to use the module pretty print so i'll go from p print import p print as pp and i'll go pp here trying to say that with a straight face we went pp let's go r dot json and print it out and now you can see it prints out much nicer but there's still a lot of results there was actually a dictionary and the first key value pair of that dictionary was data so we'll go data and then we want the first entry in data so i'll print that out and you can see it's bitcoin and you could just sort of go through the list here and see all of the different cryptocurrencies so that's pretty good we've tested basic functionality with the api server but if we don't want our code to turn into spaghetti code we want to start using classes and this is going to allow us to implement a lot of functionality into our api object so start off a class we just go class and then we give it a name so i'll go class cmc and you don't specify a parameter or anything like that now the first thing we're going to do in our class is we're going to create the init function and this init function is used when you first substantiate an object and basically we're going to set all the parameters that we sort of want used in our other functions that we're going to create within our class it's going to make more sense as we move along in the video just follow along and it should make sense so let's go def double underscore init double underscore and we're going to set two parameters here it's going to be self and the next one is going to be token now let's just do that and i'll just say pass and i'm just going to quickly type out so it makes sense how we're going to substantiate this class object basically what we would do is just go cmc this is just a variable name and would go equal and we'll go cmc and then we'll pass it that token name which is actually going to be this secret api token so i put this here now to sort of illustrate the flow but basically we're creating this object based on this class and we're passing the token to it that brings us to this class over here it hits the init function and sends that token there okay so i hope that makes sense and it should make it a little easier to follow if you're not used to working with classes so the next thing i'm going to do is set some variables here that we're going to reference a lot in our other functions so the first one i'm going to set is for this base url since we're going to be using it for all our requests so let's go self dot api url equals and let's copy and paste that the next one is these headers so i'll go self.headers and let's pull this paste it here and then let's just put this all in one line we don't really care about pep 8 too much now after that let's go ahead and create a session and basically what a session is is a request object and it just sort of allows you to reuse the request object so what we need to do is go to the top here and go from request import session now the next thing i want to do is instead of using this request i actually want to create a request session you can do it the request way but using a session is just sort of a best practice so let's go ahead and do that let's scroll to the top and go from requests import session and it's with a capital s and then let's go down here and we'll go self dot session equals session and now the last thing we want to do is go into our session so it's self dot session and then within that session we can set the headers so it's headers dot update and then we specify the headers so we'll go headers equal headers and this just makes it so whenever we call a request we won't have to set the headers like we did here we only have to do it this one time and now any future requests that we make the headers are already going to be set so that's one of the benefits of using this session object so this should be good enough i'm going to go ahead and copy and paste this into my code and just sort of to test it out and make sure i don't have any errors so i'll paste that in and it looks like i have an error and i think it was just the way it copy and paste it in so let's do that okay it accepted the class now let's copy this in and we can see that it doesn't like this because we didn't actually copy and paste this in we got that pasted in now let's paste this in and then here so now we have the cmc object now you can sort of see that we can access all these variables and we just have them available to us so we have the api url we can look at the headers and we have this session object so basically the session object is from the request library and we can use this object to make requests to our api server and it's going to have this header set which has our api token so basically what we want to do next is functionalize all those calls that we found on the documentation so if we go back here to cryptocurrency we can basically take all these and turn them into functions and that way we will be able to easily call them so let's create the first one and it was this mapping one so i think it was just returning the coins so i'll just go def get all coins let's add some lines here and this is a function within this class so whenever you're doing that you want to set self and this one doesn't take any parameters it just goes to the url so let's take let's correct this spelling error and then let's go down here we're going to set the url so we'll go url equals self dot api url which is the base url plus and then let's just take this so this is the endpoint portion of the url so we'll take this and put it in here so the next thing we can do is take this session up here which is self.session and we're going to do a get request very similar to what we did up here and we're going to send the url and let's assign that to a variable r and that is going to send the request to this url now for the next line we want to clean up the data a bit if you recall when i actually called it before see if we can get back to it you can see that the actual data that we wanted was under r dot json and then slash data so let's grab that i'm all to say data equals r.json data and now we can return data so this looks pretty good let's go ahead and copy it and paste it into our idle session and resubstantiate this object and now if we go cmc dot get all coins and we can see that we have an error here and it's sort of giving away my api key so let's let's clear that up all right so i ran the code and i ran into a few errors and it took a little bit of troubleshooting not gonna lie but i saw quite a few different errors i'm sure a lot of you were yelling at me through the screen and just being like why are you typing it like that that makes no sense let's go ahead and fix these together it's going to be great troubleshooting so the first one is obviously this one it looks like my copy and pasting got ahead of me uh let's take this out obviously that's not how you assign a variable uh the next one has to do with scope so i copy and pasted this from up above but i actually need to change this to the local variable of token so that's the next error and then we have one more here which is this headers let's take this out and we actually want to reference the self variable so we'll go self dot headers and the next one is a little embarrassing i called this ap why instead of ap api i i don't know guys it's getting pretty late here but anyways that should fix all the problems so let's go ahead and rerun this but before i do let's import that pretty print module so go from p print import p print as pp and we'll go to the bottom and enable pretty print and we'll throw in that cmc object and we'll say get all coins and now let's go ahead and run this and cross our fingers and there we go it returned almost all the coins um that's all your cryptocurrencies right there i guess um so let's go ahead and add more functionality and as we add more functionality you're gonna see why using classes is just so awesome so for the next one let's make it a little more interesting let's get the actual price and let's go ahead and set it so we can send a parameter to the api so it returns us information based on that parameter so heading back here let's scroll up and i think quotes latest is the endpoint we want so let's go ahead and grab this and have a quick look at the parameters and it says symbol and you see you can just send a symbol looks like you can do comma separated so you can do like btcf any of the coins you want we'll go ahead and just test this with all right so my camera died there and i know you guys love seeing my pretty face so i replace the batteries and we're ready to go again so having a look at this documentation you can send a symbol and within that parameter you can give it looks like any amount of uh cryptocurrency symbols and it's going to return you the prices for that so let's go ahead and build a function within our class to take advantage of this endpoint so i will grab this again put in my clipboard now before we paste that in let's get a function ready so we'll call this one get price and then let's paste in that url and then we're going to make it similar to this one up here so we'll go url equals so we'll go url equal self dot api url plus this endpoint now let's go up here and set self and we actually want to add an additional parameter here and that's going to be the symbol so we'll be able to send the symbol bitcoin ethereum or whatever their ticker symbol is and this is going to pull back the data of that coin so we'll go down here and a lot of this is just copying and pasting you know you're a good programmer when you can just copy and paste a lot of your code so we have our function just about ready there's one additional thing we need to do here and that is to take this symbol and send it as a parameter to the request so let's create a dictionary object here and we'll go parameters equals and we'll say symbol and it will get assigned that symbol variable and then down here in the actual request we'll go params equals parameters and i believe this should be enough to get it working so let's go down here and change it from all coins to get price and we're going to send it a symbol so i'll say btc now let's go ahead and run the code and i think i did not copy and paste something incorrectly and hi that is true it's missing this slash so i guess i'm not as good of a copy and paste programmer as i thought let's go ahead and run this again and there we go we get our coin back i think i think there's a lot of information i guess these are tags to describe what the coin does you can see bitcoin is a store of value he uses sha256 uh pow which is proof of work minable so lots of interesting information about bitcoin here and then price of course what everyone's interested in and i guess just your volume and then just a whole lot of other data so let's go ahead and move this down and zoom out of my code a bit it's a little large here and i will take this stuff out because it's not required and one thing i like to do is take this and put it in here just so i know the documentation since a lot of my scripts do make use of a lot of different classes i sort of like to paste in like any documentation that i build those classes around just so it's easy to reference when i'm troubleshooting code it's very helpful when you're troubleshooting someone else's code and they do something like this it just makes it life a whole lot simpler anyways that's all i really wanted to show for this video i just sort of wanted to start from scratch with a new api and build up a script that uses that api if you found this video helpful at all please go ahead and hit that like button for me i really appreciate it and if you want to learn more about it or anything devops related go ahead and subscribe to my channel thanks so much for watching and i hope to see you all in the next video
Info
Channel: DevOps Journey
Views: 41,344
Rating: undefined out of 5
Keywords: api in python, api python, api python tutorial, api using python, api with python, coinmarketcap api, coinmarketcap api python, how to use api, how to use api in python, python, python api, python api for beginners, python api request, python api tutorial, using api in python, working with api in python, working with apis in python
Id: p71SWzjeqtk
Channel Id: undefined
Length: 25min 38sec (1538 seconds)
Published: Mon Apr 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.