Talking to the internet with Python sounds scary, right?
Fortunately, the internet has been in good hands for a long time.
Our methods for talking to the internet are well established and surprisingly easy.

Lets get straight to it.
We send data in a specific format.
We then get data back in a specific format.

This magical box is simply a script kept on a server.
Fortunately, APIs are generally very well documented and follow the same usage patterns.
As in most cases, with data, we are more interested in downloading it.

POST, PUT, and DELETE are all used whenmodifying information.
You might also seePATCH this is used for partial updates, similar to PUT.
Ive never used this before, and it seems to be less common but it is worth knowing.

This format is JavaScript Object Notation (JSON).
JSON implements the same hierarchical structure with key-value pairs that we find in Python dictionaries.
But how do we do any of this stuff?

We userequests an incredibly easy-to-use library.
Lets take thePokemon APIfor example its incredibly simple to use.
So lets see how many they added with generation II.

Well, this is the HTTP200 OKstatus code.
It means our request succeeded!
But where is the data we wanted?

Now we can find everything we need to know about Pokemon.
Thats great, but maybe not that useful.
Real world use-cases
Lets write some more relevant code, using real APIs and use-cases.

Looking at it now makes me feel queasy so well rewrite it.
Our objective is to plot a directory of addresses onto a map.
The API expects two variables,addressandkey.

We dive into the Geolocation API athttp://maps.googleapis.com/maps/api/geocode.
We append our coordinates to theCOORDSlist which can now be used for plotting locations on a map.
Interacting with GitHub
We can use APIs to interact with GitHub too.

Keeping it simple, well use the POST request to create a new repo calledapi_test.
First, as always, we need an authorization token.
The only required field here is thenamevalue, which specifies the new repo name.

We also setpublictotruewhich simply sets the repo privacy prefs to public rather than private (the default).
Note that we usePAYLOADto contain our instructions for the API, which we pass to thedataargument withinrequests.post.
We also include our authorization key/token using theheadersargument.

Final notes
That is everything you gotta know to start working with APIs in Python.
Of course, there are many more, and likely more relevant use-cases out there too.
Pulling data from the internet is also a frequent task and therefore, an incredibly important skill to have.

Understanding and getting some practice with APIs is super useful.
Also tagged with



