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.
We’ll skip the small-talk introduction and get straight to it. This article will cover everything we need to communicate over the web effectively — this includes:
- Application Program Interfaces (APIs)
- JavaScript Object Notation (JSON)
- Requests with Python
- Real world use-cases
An API is like a magic box. We send data — in a specified format. We then get data back — in a specified format.
This magical box is simply a script kept on a server. It acts as a gatekeeper — we tell the gatekeeper that we would like to know, change, or delete something, and the gatekeeper will (hopefully) perform the action we request and let us know how it went.
Fortunately, APIs are generally very well documented and follow the same usage patterns. The vast majority of Web APIs use the representational state transfer (REST) structure — which sounds far more complicated than it is.
RESTful API architecture applies six key constraints:
Expires Wed, 17 May 2020 07:12:27 UTC
).What all of this means to us is that we will communicate with a single location and expect specific behaviors — this is further standardized using a set of HTTP methods.
When communicating with an API, we tend to use four methods:
The most commonly used of these is the **GET **protocol. As in most cases, with data, we are more interested in downloading it.
If we would like to get the latitude and longitude coordinates for an address using the Google Maps API, we would send a GET request — as we are literally getting data from the API.
POST, PUT, and DELETEare all used when modifying information. Using the example of a GitHub repo, we can create it with POST, update it with PUT, and delete it with DELETE.
You might also see **PATCH **— this is used for partial updates, similar to PUT. I’ve never used this before, and it seems to be less common but is worth knowing.
When using GET, POST, PUT, and DELETE, we will usually receive one of the following codes:
2xx - Success Codes
200 OK - success (most common with GET)
201 Created - request fulfilled and new resource created (POST/PUT)
204 No Content - success but no content is returned in response
4xx - Client Error Codes
400 Bad Request - request could not be understood due to bad syntax
401 Unauthorized - most likely we missed the auth key
403 Forbidden - we're trying to go places we're not allowed
404 Not Found - what we're trying to access doesn't exist
Honorable Mentions
418 I'm a teapot - stop asking a teapot to brew coffee
420 Enhance Your Calm - sending to many requests to Twitter
Take note of the final two — they’re incredibly important, never forget them.
#python #web development #programming #api