Back to Index

Intro to APIs in Python - API Series #1


Chapters

0:0 Intro
0:20 What is an API?
1:47 RESTful APIs
5:26 API Methods
7:20 HTTP Codes (200s)
8:14 HTTP Codes (400s)
10:0 JSON Format
11:21 Talking to APIs in Python
14:30 Google Geocoding API
22:8 GitHub API
27:48 Outro

Transcript

Hi, welcome to the video. We're doing something slightly different this time We are going to put together a series of videos just covering apis What apis are how we interact with them how we build them? And we'll have a look at a few different python frameworks that we can use for putting them together now what I have tried to visualize here is how we can think of apis so api To start with stands for application program interface And we can think of apis as a black box So this thing in the middle here is our api now inside this magical black box What we do is we send data to it over here And all we really know is that it sends data back to us over here now in reality this This api here is a script on a server somewhere and What it is doing is acting as a middleman or a gatekeeper between us And the server that it represents now through this api we can typically download or get information We can request to change some information over on the server or we can request to delete information on server And most requests we can kind of fit into one of those three things We're either getting information updating or putting information or deleting information now apis are very structured in that they have a very specific way of working so they generally all follow the same structure and the most common structure out there is called a RESTful api now a RESTful api or REST stands for Representational state transfer and that sounds really complicated in reality.

It is very straightforward. We don't really need to go into too much depth but But it consists of six key factors So we need to follow these six rules in order to make sure our api is RESTful or a REST api So the first of those is we use a single Outward facing interface.

So there's a single entry point For us to communicate with this api There should be client server independent so Like we saw before over here on the left. That is the internet and that is where we are coming from Over here is a server And what this api does is acts as a middleman between both of those and it allows those two to For example, if the client gets updated it will not break the Connection between the client and server.

We just all we need to do is communicate with the api So our communications to the api should not change Now if the server is updated and things change on the server the api Should remain the same and therefore when we try to communicate with it. Nothing will change and then we also have statelessness, so What this means is say you send a api request And then we send other api requests immediately after the results of that second api request Should not rely or should not be dependent or change based on the results of the first request unless of course we're changing information changing or deleting information and Requesting all that information back again, of course in that in that case It will change but the actual state of the api will not change All that's changing there is the underlying data that is hosted on the server Is changing but the state of the api does not change.

It's a blank slate at the start of every new request For caching so down here all we're saying here is that the api must It needs to inform us whether its responses are allowed to be cached by the user the next rule is that the Api should follow a layered system structure.

So there should be a modular structure to this api So one layer can be changed and it should not affect the other layers and finally where it's applicable the api Should be able to provide code executable code on requests now, not all apis Are relevant for this so we're not going to see this everywhere and as far as I know, it's reasonably rare as well So I wouldn't worry too much about that but all of this together for us as general users just means there'll be a single interface for us to interact with the api through and There are a specific set of behaviors that we would expect so we wouldn't expect this api to deviate too much from from any other api Now there are a set of different methods that we can interact with an api with So we have a get request which is where we retrieve Information a post request for creating a resource or creating basically creating a new record On the other side of the api we have a put request for updating a resource or record And then we have delete For deleting an existing resource or record Now the most commonly used of these is the get request we use up Quite a lot to be honest whenever you want information from an api you use a get request and then if you are Interacting with the api in some way.

There's a database that you're modifying behind it You're going to use post put and delete quite a lot as well so for example if we wanted to get the gps coordinates from the google maps api we would use the get request so we'd be requesting information Alternatively if we were going to use the github api and we wanted to Create a repository we wanted to update a repository or wanted to delete a repository We would be using one of those three Now there is also another well, there are quite a few methods, but there is another one that I See online Um, so I mean the patch request is for partial updates So it's like a put request but for partial updates now i've never actually seen this used so i'd I mean, i'm sure it's used somewhere And if you use apis a lot, then maybe you'll use it But I think for most users, you're probably not going to come across it Okay.

Now we've covered how we interact or what? Requests we send to an api now. What about what it returns to us now? An api will return different codes depending on the output or the not output the Result of whatever it is. We we asked it to do so The first set of codes here are the 200 success codes.

So anything the two is Anything within the 200 range is usually a successor. It's a good thing now We have the most common one, which is 200. Okay, which just means success in general 201 we created something or 204 we There's a success but the api didn't return anything.

It's not necessarily a problem and then we have The 400 codes now. These are client-side errors. So errors on our side And we have the most common Actually to be honest. All these are pretty common the one that you Means that you're probably doing something wrong is 400 is your bad request.

That means we're entering the request wrong. So that might be A the syntax is wrong the form the json format is wrong or we are using the Wrong fields in our request and then we have also unauthorized typically it's because we're not authorized ourselves with a authorization key Forbidden so you're trying to access something that you're not allowed to access again That might be because you're unauthorized and you just need to enter your auth key and then you'll be allowed there And then also 404 which is not found that means there's nothing there Although some websites like github will use this When there is actually for example a repo there, but it's a secret and you're not allowed to see it They'll give you a 404 because otherwise they're telling you.

Hey, look, this is actually exist So they they also give you that sometimes instead of forbidden or unauthorized And then there's also these ones. So these are probably the two most important Client error codes. So there's a 418 which is i'm a teapot And and that's when you know, sometimes it happens where you ask a teapot to brew coffee Um, so in that case just stop doing it and there's also 420 enhance your calm.

So that's specific to twitter And that's just saying you really need to chill and because you're sending far too many requests to twitter. Okay, and that's it for the codes and let's move on to The json object. So this is the format we use For interacting with our api.

It stands for json object notation And it I mean you can probably tell from this if you use python. It looks like a dictionary and it Pretty much is a dictionary that they use the exact same structure Although they're not technically the same but dictionary is a json like object Now it's just a hierarchical format.

It allows us to use all these different fields. We can put lists with strings Put more dictionaries inside it. Uh, so it's it's pretty useful and this is the standard format. It's used by everyone for apis Now I can show you an example of this. So I just come over here.

I have this little link here. So this is Actually, we're going to go to an api in the browser and make a request from the browser So we we can do that. It's not there's nothing weird about doing that and We've gone To this it's called the pokey api.

So it's actually an api for pokemon Um, and it just returns you all this information. You can see that. I mean, it looks pretty messy It's not on a clean format, but this is basically just a dictionary And this is uh, this is a json format Now, let's go back to our code and we're going to start putting something together.

So we're going to start making some requests So we first want to import requests, this is just a standard library for making api requests in python It's super easy to use So we just import requests and to make a get request. All we need to do is write request dot get And let's use the the pokemon api that we saw before so i'm going to copy this In fact, I already copied it.

No, I didn't and so i'm going to copy this And just bring it down here so enter is a string And let me I'm going to store this in the response variable there And let's see what we get so we get a 200 response. So remember before That's what we see over here, so it's the 200 okay response so it's good.

It means it went. Okay. It went well Uh, but we that's all we see. So how do we actually access the the json response underneath that? All we need to do is write json like that, so We use the json method and that's that's all there is to it So now we see something very similar to what we've got in the browser before so we have this Dictionary now, uh, we have these abilities.

I'm not sure exactly what this is returning. I think it's just returning Why is it returning? Oh, so we're searching for charizard So charizard Has several abilities blaze solar power solar power And lots of other things forms okay, so I'm, not sure why you use that but So if we want to access we can access abilities there Okay, and it goes in To what is now a list?

So now we need to access the first end level of that list and we have this other uh, this one entry here Go further so you see it's basically just a Sort of a tree structure. We just keep going deeper and deeper in there and we can Let's go Let's get the url Just out of curiosity.

I really want to see what what is there? so Ah, okay So it's just another is it is the api we can see that because it says up here i'll zoom in Uh pokie api.co and then slash api Just very curious I wonder if I can access the website directly like Ability 66.

No, we can't. Okay. No problem Um, yeah, so we have that so maybe that's useful if you're really super into pokemon But I don't know maybe like it for a game or something could be useful I'm, not sure. I think to be honest. I think this is more for Learning how apis work than anything else Uh, it's pretty I mean it's pretty useful for this example.

It's great Now I want to show you something that's maybe more relevant So i'm coming over to google and we have the google maps api So documentation here just describes how you access it You can you can follow it along if you want, but i'm going to very quickly just go through it So we come down to create api keys go to credentials page.

You'll probably need to create a project. So we click that Uh doesn't matter what we call the project. So i'm just going to leave it with the default name we continue Now you have to wait a minute for that to load Okay, and then this page will load over here.

So What we want to do is we'll scroll down and we want to use the geocoding api. So we click there click enable and Once that is loaded we want to head over here go to credentials create credentials Api key and we just copy this Okay, so i'm now just going to write that in here so we've got api key Copied it over from before.

So there we go Okay, I just need to make sure that is a code cell, okay Okay, so that's the api key And then we also need a few other things so the api url so that is right out here Geocoded in there and then what we're going to do is we're going to enter an address and with that address we're going to return the Latitude and longitude from google maps.

So what we need to do is write requests Don't get because we're getting that information In here we want our api address first Follow that with jason like that And then we want to include the address that we want to search for so we go address Equals and then in here we we write that so i'm going to go with the address for the coliseum in rome so piazza del coliseo Like that now just note that here i've added the Plus marks rather than a space if you you can't use spaces in In http requests, so and you can also use this that represents a space but i'm using the the plus signs there And then the last thing in fact, actually, let me show you what happens if I try and run it like this.

So let's see, okay, we get a 200 It's interesting actually not expected Let's see Okay, so we get 200 requests which is strange I would have expected I would have expected a like a not unauthorized response maybe but fine So it's just saying so we return this error message saying you must use an api key, right?

Because we we have defined our api key up here, but we haven't included it in our request. So google doesn't know we actually have one so Uh, we also can include that so we come over here right and Key equals then we have api Okay, I know that's not what we it's api key Okay Now let's have a look what we get so we will check we should still get a 200 response.

It's good And we also need to make sure that we write https there Run that again, and then we get the all of the address information for the coliseum in room and if we want so we said we wanted the longitude and latitude, so how do we get that we Have a look through it.

So first thing we do We can see everything in there. So we have results or status Okay So, let me copy this come down so we have results and the results covers everything from here To Not pretty far actually Ah to here So our results is is where we want to go for the longitude latitude because we have the latitude and longitude here So we go to results And then in this case, it's a list So we have all these different Components here and we want the first entry in that list Like so Okay, so it was just a it was a single entry in in the list I assume they do that if you are requesting multiple addresses I'm, i'm not sure And then we want to go into address components Okay, and then we're in another list again here so we have this one or zero one Two Three four Five so It's dictionary number five, I think.

Yeah. Oh, no, no. No, um Oh, we don't have we don't have the coordinates. So let me remove that. It's not address components So we we just went into this list here Ah, no, so we want geometry I think So let's go into geometry Okay And then in here we have bounds Uh, I mean we can just actually no we can go for location.

It's probably Center I mean, I mean these are all obviously going to be very close. I don't think that address area for Coliseum is that big So we go location Okay, and then here we have our coordinates so we can we just save those to coords like so and then Within there.

We would just write coords Lat I think it was for latitude And obviously coords long for the longitude Like so and there we are. We have our coordinates so that's the google geocoding api I like to use that example because the the first sort of coding Job, I ever had was using this weirdly enough although the code back then was absolutely horrific when I I I don't think I have it anymore.

I'll have to have a look Uh, but yeah, it was not very not very clean code. It's it's pretty horrific And the next example, so we just that was an example of using the get request but I want to show you also how we can use a put post or post put and delete as well, so um I think the easiest or most popular one that is just github.

So we will Come down here. So this is the documentation for getting access to it again link in description And what we do is we just come down here We come to create a token. So i'm assuming you have a github account So you just need to make sure everything is verified and it says you need to go into github And click profile photo click settings.

So we'll do that Okay, so I have it open here come over here go to Settings And then over here on the left we want to go down until we see developer settings over here And we want to go to this personal access token. So click on there Uh, and then we just need to click on this generating token Okay, and we just want to click on repo here.

So it's all we need. Um, if you also want to delete i'm not going to It's I think just a bad idea you can you can click delete repo here as well But i'll generate that token And then I have it down here. So i'm going to copy that over into my notebook Okay, so i've put that in a variable called github key And what i'm going to do here is Create a a new repository.

So we're going to send a post request to Initialize a new repository. Um to do that. We we also need this other Library, so import json. I'll show you why in a moment um, so with json We'll see in a moment, but i'm going to create this dictionary which is going to contain information for my api requests So typically you you would you use this when you're using?

post put delete Think as well. So you generally you are going to use this but not so much for get requests So you have the name of the repository which is going to be api test And i'm also going to set it to be public so we can See it and i'm going to say that's true Okay, and now i'm going to say request.post And then we have the url so it is htps api.github.com user repos And then in the headers so we have this other Argument called headers in here.

We put sort of your authorization typically and then any other random little bits of information Which is what we're going to use it for so we're going to use it to include our authorization code and you'll typically find that that is formatted in in Slightly different ways. It's not just a string.

You also need to include something else so authorization so this is just the the parameter name And then here there's an f string I need to put token space and then in here I have my my actual token. So github key Okay And then this is where we include our payload and why we're using the json Package so we write data equals json.dumps so this is essentially going to convert our dictionary here into a json formatted string Okay, because we can't just include a dictionary in a json request.

You you will get you'll get an error So you do need to convert that into a json json string Okay That looks pretty good. So let's let's try it Let's see we got we got a 422 response, so let's see why repository Creation failed because I already have it.

I've already tested it before apparently so I'm, not very creative with my names. So we're going to call it api test 2 Here we go again Uh, but notice with with that, uh response that we although we haven't covered 422 Uh, we could see that was a 400 code.

So we knew that something had gone wrong on our side All right, is it is a client-side error? Okay, so now Okay, it looks good Yeah, cool so we have now created a New repository. So if I go to my github and have a look I should see that so come over to my github go to repositories And right at the top there.

We see this api test 2 so we did create it And from now we can do other things you can you can post things to your repos. You can delete them You just need to modify which permissions you've set when we build up when we create that personal access token So I think that's it for this video I think we've covered quite a lot.

We so we've covered the essentials of apis had a quick look at the pokemon api then the Google maps geocoding api and now the github api so I think that's plenty so in the next Video what I want to do is have a look at how we can build an api with flask and python So, thank you very much for watching and I'll see you in the next one.

Bye!