REST APIs in Python.

REST APIs in Python.

Isaac Tonyloi

martin-shreder-5Xwaj9gaR0g-unsplash.jpg Photo by Martin Shreder on Unsplash

An API(Application Programming Interface) is a set of rules/protocols that determine the format and type of data that a particular service can access using various HTTP methods. A REST API is an api that conforms to the REST architectural constraints. REST APIs make it much easier for us to access and retrieve data easily by making a simple request.

An HTTP request is a call made to a server through an endpoint in a bid to interact with some data. Besides endpoints an HTTP request also contains the following components:

Endpoint - also simply referred to as a URL, this is the address to the location of resources that an API wants to access. Method: Now once we have an address to the resources we also need to specify the method that we can use to access them. REST APIs provide full CRUD functionality using the following methods: -GET method to retrieve data -PUT method to modify data. -POST method to add new data

                        - DELETE method to remove data

Data: An HTTP request also includes a data payload when making PUT or POST requests. Headers: Headers are an important part of any request to the server. They contain information useful for tracking and resolving issues that may arise when working with APIs. These information includes:
Request Authorization Response Cookies Response Caching Information in the header will normally be displayed in string format as key-values pairs and can be traced in the message body An HTTP Response on the other hand is the response that is received from the server. A typical response would also contain response headers and response data. JSON is one of the most common formats when returning an API response since it is language agnostic and readable by humans; however, XML format can also be used. Now REST or RESTful APIs are those that conform to the REST architecture and are expected to conform to the following constraints:

  1. Statelessness - This means that the server cannot store nor reference any session data. Each request should contain enough information to complete the request successfully.
  2. Client-Server architecture - The server and the client exist as independent entities. The client or the user interface is tasked with making requests to the server in order to help users retrieve various data. While the server is responsible for the storage of data.
  3. Cacheable: Response data is stored in high-speed memory known as a cache so that future similar requests to the same data are served very fast.
  4. Layered System - Allows the REST architecture to have hierarchical layers such as security layer or intermediary servers that enable Load Balancing. However, the client should not be able to tell that there are intermediaries along the way.
  5. Uniform Interface - This allows us to simplify the overall Restful system architecture. By making use of constraints such as identification of resources, self-descriptive messages, and manipulation of resources through representation we are able to achieve separation of concerns.

Working with the Requests Library. In Python, the Request Library is the de-facto library for making HTTP requests. This Library is both lightweight and simple to use and understand even for novice developers. The request library can be installed using pip, the common package installer in Python using the command below. Code pip install requests

Now to get started with using the request Library to make requests and interact with APIs we simply need to import it into our programs. Using the keyword import we can do that as shown here. Code import requests

In this example we are going to use an open api known as agify. Agify.io predicts the age of a person given their name. This API can be used for analytics, ad segmenting, demographic statistics etc. To make a simple GET request to the API we are going to use the requests.get() function as shown here. Code

import requests

response = requests.get("https://api.agify.io?name=michael")
print(response)

Output

<Response [200]>

Receiving a response code of 200 signifies that the request was successful and that a response object was returned. Now using the response variable we have stored that response object returned but the request. Now, this response object contains some information that we can access using various methods. The first kind of information that we are looking to extract from the response object is the response code returned along with it. As mentioned a response code of 200 signifies that the request was successful. Code

import requests

response = requests.get("https://api.agify.io?name=michael")
print(response.status_code)

Output

200

Of course, the API may return other forms of status_codes signifying a different message some of the common ones include: 404, 400, 403, 401 that signifies not found, bad request, forbidden, and Unauthorized respectively. More on those here. A response object would also include a payload i.e data that is returned as a response to the request that we have made. This payload is usually returned in bytes, however, we can view it in other formats such as in text format or in JSON format as shown below. Code

import requests

response = requests.get("https://api.agify.io?name=michael")
print(response.content)

Output

b'{"name":"michael","age":70,"count":233482}

Or in text format as shown below. Code

import requests

response = requests.get("https://api.agify.io?name=michael")
print(response.text)

Output

{"name":"michael","age":70,"count":233482}

We can also access the payload in JSON format as shown below.

Code

import requests

response = requests.get("https://api.agify.io?name=michael")
print(response.json())

Output

{'name': 'michael', 'age': 70, 'count': 233482}

A response object also contains headers. The response header contains important metadata that is often useful in solving problems with APIs. Such information includes content type, information about Caching and cookies authorizations, and more. We can the response header as shown below.

Code

import requests

response = requests.get("https://api.agify.io?name=michael")
print(response.headers)

Output

{'Server': 'nginx/1.16.1', 'Date': 'Mon, 24 Jan 2022 15:32:21 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '42', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type, X-Genderize-Source', 'X-Rate-Limit-Limit': '1000', 'X-Rate-Reset': '30459', 'X-Rate-Limit-Remaining': '990', 'ETag': 'W/"2a-PJtWtULWnPtrkG3i0MFP3YinIdk"'}