Making REST API calls in Python is a common operation when you need to access third-party APIs. Using the
requests
library, you can interact with third-party endpoints using a simple yet powerful interface. It supports all HTTP methods and provides additional features that can streamline your work.In this article, you will learn how to use the
requests
library in a Python project.Without further ado, let's dive in!
Setting Up a Python Project
If you're an experienced developer looking for quick reference, you can jump directly to each HTTP endpoint.
If you're starting a new Python project, follow these step-by-step instructions to set it up.
This sample code assumes you are using Python 3. If the script doesn't work with the
python
command, you can use python3
instead.Create a Directory for the Project
It's a good practice to create a dedicated directory for your Python project. This approach allows for easier future management, especially when using version control systems like Git.
To create a directory, use this Unix-like command in the terminal. This command is suitable for Linux or macOS terminals.
mkdir python_project cd python_project
The above script will create a directory named python_project and change your terminal's working directory to it. After executing the script, you will be inside the python_project directory.
Create a Python Script File
Within the python_project directory, create a Python script file named
main.py
.touch main.py
Now you can add a "Hello, World!" message to your
main.py
file and run it to check if your project is set up properly.Add this line to your Python file:
print("Hello, World!")
Then run the Python script:
python main.py
If the above command doesn't work, you can try using
python3
.Using the Requests Library in Python
Follow the steps below to install the Requests library.
Install via PIP
The recommended way to install Requests is through PIP, a Python package manager that handles third-party dependencies.
Use the following command to install the Requests library:
pip install requests
This command will download the dependency to your system-wide package cache. Whenever you need to use the library, your Python project or script will utilize the library from this package cache.
The above installation will install
requests
into the system-wide package cache. To ensure no conflict in the future, you can use venv (virtual env).Import Requests into Your Python Project
Importing the
requests
library into your Python project is as simple as adding this line to your Python file:import requests
This line will import all the interfaces provided by the
requests
library into your file.Making REST API Calls using Requests in Python
Now that you have the
requests
library available in your Python project, you can make REST API calls using this library. In the following sections, you will learn how to make HTTP requests in Python using the four main methods.Instead of making calls to a nonexistent API, we'll use the JSONPlaceholder API to test whether your REST API calls are working against a real server.
GET Request
A GET request is used to retrieve data from a server by supplying information in the URL endpoint.
import requests base_url = "https://jsonplaceholder.typicode.com" # GET Request def get_request(): response = requests.get(f"{base_url}/posts/1") if response.status_code == 200: data = response.json() print("GET Response:", data) else: print("GET Request Failed")
In the above example, the
get
function from the requests
library is used to invoke the posts/1
endpoint. This endpoint will return the post with ID 1
. The requests
library will return a response
object from which you can extract the JSON body.To parse the JSON data from the response, you use the
json
method provided by the response
object.POST Request
A POST request is used to send data to a server within the request body.
import requests # URL of the API endpoint base_url = "https://jsonplaceholder.typicode.com" # POST Request def post_request(): data_to_post = {"title": "New Post", "body": "This is the body of the new post", "userId": 1} response = requests.post(f"{base_url}/posts", json=data_to_post) if response.status_code == 201: data = response.json() print("POST Response:", data) else: print("POST Request Failed")
In the above example, the
post
function from the requests
library is used to invoke the posts/1
endpoint.The
post
function accepts the URL endpoint and a dictionary. The requests
library will serialize this dictionary to JSON and place it within the request body.PATCH Request
A PATCH request is used to update existing data on the server within the request body.
import requests # URL of the API endpoint base_url = "https://jsonplaceholder.typicode.com" # PUT (Update) Request def put_request(): updated_data = {"title": "Updated Post Title"} response = requests.patch(f"{base_url}/posts/1", json=updated_data) if response.status_code == 200: data = response.json() print("PUT Response:", data) else: print("PUT Request Failed")
In this REST API call, the PATCH method is used instead of POST.
With the PATCH method, you update specific fields rather than replacing the existing record in the database. Similar to the POST method, you can pass a JSON dictionary to the method, and the Requests library will automatically serialize it into a JSON object to be sent to the server.
DELETE Request
A DELETE request is used to remove data from the server by providing information within the URL endpoint.
import requests # URL of the API endpoint base_url = "https://jsonplaceholder.typicode.com" # DELETE Request def delete_request(): response = requests.delete(f"{base_url}/posts/1") if response.status_code == 200: print("DELETE Request Successful") else: print("DELETE Request Failed")
Deleting a request can be accomplished using the
delete
function from the Requests library.When you delete a record, you expect the corresponding data to be removed from the server's database. The
delete
function only accepts the endpoint; there's no need for a dictionary body.Wrapping Up
Congratulations! You've learned how to make endpoint calls using the Python Requests library. In this tutorial, you explored how to perform GET, POST, PATCH, and DELETE requests against the JSONPlaceholder API.
For further information on the
requests
library, consult its Requests documentation website.