Understanding APIs
How about looking at APIs in a whole new light? or should I say taking a fresh start looking at something new. Before exploring what Python can do, let's take a look at how an API functions. APIs make it feasible for two different software systems to communicate. It's like when you're in a restaurant ordering food. The menu lists your options (the API), the waiter places your order (the request), and when it's ready, he/she delivers it to you (the response). So, if you look at it, requesting something using an API is no different. One sends the request and in return, the API provides the information in the format requested, mostly in JSON or XML.Modern day programming is filled with APIs from obtaining weather information, working on social networks, sending emails and even operating cloud services. APIs can also be used with the programming language Python to work with other data and develop custom applications.
Configuring Your Python Environment for API Use
When working with APIs in Python, the first step is to set up the required libraries. To make HTTP requests, the first thing to have is the `requests` library which makes it easier to send HTTP requests and manage responses. To do this, you must install the 'requests' library if it is not already installed on your system. You can do this through the following command: pip install requests
import requests
response = requests.get("https://api-example.com/data")
Making API Calls
To make use of an API, you need to make an HTTP call to it, most of the requests made are of the following types:- GET: Used for getting information from a server.
- POST: Generally used for sending files or information when filling forms to a server.
- PUT: Used to make modifications on the already existing information of a server.
- DELETE: A request specifically used for the removal of information from the server.
Let's begin with the GET request, which is frequently utilized for getting data from APIs. A straightforward GET request is made by utilizing the `requests.get()` method as we have seen in the previous example. This makes a request to the server and gets back a response.
As an example, querying an API that provides data about books may make use of the following code.
import requests
response = requests.get("https://api.example.com/books")
Receiving Responses
With the request already dispatched, there is the need to tackle the response. In Python, the 'requests' library boasts several techniques for manipulation of response data. For instance, the status code can be verified to establish if the request succeeded. A code of 200 is a clear indication that the request was properly executed.Consider this example,
import requests
response = requests.get("https://api.example.com/books")
if response.status_code == 200:
print("Request was successful")
print(response.json()) Python dictionary representation of the response
else:
print(f"Error: {response.status_code}")
Extracting API Data Alright, Now What?
When retrieving API data, chances are that you will have to perform a good deal of extraction and modification of data for the sake of the application. Most APIs, if not all, send JSON files which consist of key, and value pairs. In Python, this can be classified as a dictionary type structure which is quite common and simple to use.For the sake of this example, let us suppose the API issues a following request for book data in a JSON format.
{
"books": [
{"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"},
{"title": "1984", "author": "George Orwell"}
]
}
import requests
response = requests.get("https://api.example.com/books")
if response.status_code == 200:
data = response.json()
books = data["books"]
for book in books:
print(f"Title: {book['title']}, Author: {book['author']}")
Lets Discuss API Call Errors
When it comes to APIs, there are likely situations and times when errors and exceptions may arise, and it is advisable that one prepares for such circumstances. There are numerous reasons as to why one may encounter an error, for example the URL endpoint which is being hit is inactive, you are sending a corrupted request, or the endpoint, in this case a server, decides to send an error back. In the case of these events occurring, in Python you are able to catch them by simply wrapping the piece of code in "try" and "except" blocks.For instance:
import requests
try:
response = requests.get("https://api.example.com/books")
response.raise_for_status() Handles errors, if there are any
data = response.json()
except requests.exceptions.RequestException as e:
print(f"Error making request: {e}")
except ValueError:
print("Error processing JSON response")