Excerpt:
“APIs make software applications modular. They speed up software development time”.
Application Programming Interface (or API) is an abstracted layer that enables communication between different software applications and components. How does this communication happen? Web APIs which happens to be what we will be dwelling on in this article, sit between a piece of software application being used by a client and the database where the information is stored. Read about the different types of APIs here. The communication happens irrespective of the programming language in which the individual software applications are written; whether Python, Java, JavaScript etc. Provided the request sent from the software applications to the API is valid, be it a retrieval, update, delete, or create operation.
Imagine a social media platform like Instagram where a particular user posts a picture, what happens internally is that the user is making a POST request to the prescribed Instagram API endpoint; sending a picture to the database. Another user gets to see the post by making a GET request to the API without even knowing so when scrolling on the timeline. You see that there is communication there—through the API.
This can also be the case even when the two users are communicating through the API with software applications written in different languages.
The illustration below shows two distinct software applications communicating through an API.
Photo by author
Furthermore—APIs make software applications modular. They speed up software development time. Modular in the sense that the API implementation is separated from our code base, we just have to make calls to the API. It speeds up development time because we don’t have to write code that provides functionality similar to the one the API does from scratch, we just have to invoke it.
In this article, you will learn how to utilize a publicly available API using Python. Stay tuned.
Prerequisites
This article is suitable for beginner-level Python programmers seeking to broaden their understanding of APIs with specific implementation in Python.
To practice alongside, ensure that your machine is connected to the internet.
This article also serves as a refresher for more experienced Python developers.
Objectives
By going through to the end of this article, you should:
Learn about the requests library in Python.
Know how to make GET, PUT, PATCH, DELETE and POST requests.
Learn to store and utilise the data received from an API call inside your code.
Understanding the requests library
requests is one of the most downloaded Python packages with around 30M downloads every week according to pypi. It enables you to send HTTP requests easily in Python. requests is a tested and trusted Python package, used by many established brands like IBM. Find the source code here.
Some of the “beloved” features of requests are:
Keep-Alive & Connection Pooling
International Domains and URLs
Sessions with Cookie Persistence
Browser-style SSL Verification
Automatic Content Decoding
Basic/Digest Authentication
Elegant Key/Value Cookies
Automatic Decompression
Unicode Response Bodies
HTTP(S) Proxy Support
Multipart File Uploads
Streaming Downloads
Connection Timeouts
Chunked Requests
.netrc Support
Getting started with requests
I assume you already have Python installed on your machine. Install the requests package by following the instructions below:
On Linux or Mac OS open your terminal and do:
python3 -m pip install requests
On Windows do:
python -m pip install requests
This downloads the requests package to your machine.
Making a GET request
A GET request is made to retrieve existing data. It returns an object that can be further explored to get more details about the request made by calling the desired attribute on it. See the example usage below:
- Create a Python file, for example, get_request.py, in the file, write the following code:
# Import the requests module
import requests
# Making a simple GET request
response_object = requests.get("https://jsonplaceholder.typicode.com/posts")
From the response_object, different attributes can be called:
status_code: HTTP status code of the response.
- .text: The response body as a string.
- .json(): Parses the response body as JSON (if applicable).
- .content: The response body as raw bytes.
- .headers: A dictionary of the response headers.
- .cookies: Cookies set by the server.
- .url: The final URL after redirects.
- .elapsed In this article, we will focus more on the .json() attribute. In your requests.py file, call the .json() attribute on the response_object
json_data = response_object.json()
print(json_data)
The JSON returned is stored in the json_data variable, and can be used inside your program.
The following will be outputted to your console.
Making a POST request
POST request sends data to a specified endpoint, creating a new record. Unlike the GET method which seeks to retrieve already existing data. Follow the steps below to make a post request:
- Create a new file named post_request.py or whichever name that is convenient. Write the following code in the file:
# Import the requests module
import requests
# Making a simple POST request
data = {'userId': 1, 'id': 1, 'title': 'This is for POST request', \
'body': 'This body is modified for this technical writing article by Augustine Alul'}
response_object = requests.post("https://jsonplaceholder.typicode.com/posts/", data=data)
print(response_object.status_code)
This sends data to the prescribed endpoint and also returns a response object; this object possesses several beneficial information about the POST request sent. It can be accessed by calling the suitable attribute on the object.
Call the status_code attribute on the response object to be sure that the operation was successful. Update your code.
print(response_object.status_code)
It returns a 201, which indicates that your POST request was successful and a new resource has been created. As shown in the image below.
Making a PUT request
PUT request involves replacing existing records with new ones; it takes new data from the sender or client and replaces the existing data with it.
This is how you make a PUT request:
- Create a new Python file, for this article, we are using put_request.py. Write the following code in it.
# Import the requests module
import requests
# Making a simple PUT request
data = {'userId': 1, 'id': 1, 'title': 'This is for PUT', \
'body': 'This body is modified for this technical writing article by Augustine Alul'}
response_object = requests.put("https://jsonplaceholder.typicode.com/posts/1", data=data)
Making a DELETE request
This ensures the removal of a certain record or data. The record to be removed is always specified through its unique ID, which is usually specified.
This is how you perform a DELETE operation:
- Create a new Python file, for this article, we are using delete_request.py. Write the following code in it:
# Making a simple DELETE request
response_object = requests.delete("https://jsonplaceholder.typicode.com/posts/1")
Making a PATCH request
Use the PATCH method whenever you want to make partial changes to already existing records or data.
- Create a new Python file, for this article, we use patch_request.py. Write the following code in it:
# Import the requests module
import requests
# Making a simple PATCH request
data = {'userId': 1, 'id': 1, 'title': 'This is for PATCH', \
'body': 'This body is modified for this technical writing article by Augustine Alul'}
response_object = requests.patch("https://jsonplaceholder.typicode.com/posts/1", data=data)
Conclusion
The requests library provides a simplistic way of making HTTP requests in your Python code; it enables easy interaction with APIs and returns an object that provides useful information about the request made, by simply calling the desired attribute (the attributes can be found in the article).
Working with APIs in Python never got any easier—there are other popular libraries for interacting with APIs in Python, but the requests library was chosen for its simplicity.
Thanks for sticking around to the end of this article, this gives you a good background to start working with APIs in Python.
Top comments (0)