In this Tutorial -:
In this tutorial, we’ll explore how to make a PUT request to an external API using the requests module in Python. The requests module provides a convenient way to interact with web APIs, allowing you to update existing resources on the server. We’ll cover the process of installing the requests module, making a PUT request, handling the response, and providing JSON data in the request body.

Introduction to the requests module
Get an overview of the requests module and its features, explaining why it’s widely used for making HTTP requests in Python. Understand the various HTTP methods and their purposes.
Installing the requests module
Before we start, ensure you have the requests module installed in your Python environment. If you don’t have it installed, you can do so using pip:
pip install requests
Making a PUT request to an external API
To make a PUT request to an external API, you can use the requests.put() function. Let’s create a simple example to update an existing resource on the “https://api.example.com/posts/1” API:
import requests
url = "https://api.example.com/posts/1"
data = {"title": "Updated Post", "content": "This is the updated content of the post."}
response = requests.put(url, json=data)
print("Status Code:", response.status_code)
print("Response:", response.json())
Handling the API response
After making the PUT request, the requests.put() function returns a Response object, which contains the server’s response to the request. You can inspect various aspects of the response, such as status code, headers, and content.
In the example above, we printed the status code of the response using response.status_code and parsed the JSON content of the response using response.json().
Sending JSON data in the request body
As with the POST request, you can also send JSON data in the request body for a PUT request:
import requests
url = "https://api.example.com/posts/1"
data = {"title": "Updated Post", "content": "This is the updated content of the post."}
response = requests.put(url, json=data)
print("Status Code:", response.status_code)
print("Response:", response.json())
Using the json parameter automatically serializes the data to JSON format and sets the appropriate Content-Type header for you.
Error handling and status codes
Always include error handling when making API requests. Different status codes represent different scenarios (e.g., 404 for not found, 500 for server errors). Handle status codes appropriately to provide a robust user experience in your application.
import requests
url = "https://api.example.com/posts/1"
data = {"title": "Updated Post", "content": "This is the updated content of the post."}
response = requests.put(url, json=data)
if response.status_code == 200:
print("Post updated successfully.")
elif response.status_code == 400:
print("Bad Request: Invalid data.")
elif response.status_code == 401:
print("Unauthorized: Authentication failed.")
elif response.status_code == 404:
print("Not Found: The resource does not exist.")
elif response.status_code == 500:
print("Internal Server Error: Something went wrong on the server.")
else:
print(f"Unknown Error: Status Code {response.status_code}")
Adding headers to the request
If the API requires specific headers, you can add them to the request using the headers parameter of requests.put():
import requests
url = "https://api.example.com/posts/1"
data = {"title": "Updated Post", "content": "This is the updated content of the post."}
headers = {"Authorization": "Bearer YOUR_ACCESS_TOKEN"}
response = requests.put(url, json=data, headers=headers)
print("Status Code:", response.status_code)
print("Response:", response.json())
Rate limiting and API tokens
Similar to POST requests, rate limiting and API tokens are essential considerations when working with PUT requests. Some APIs may have rate limiting to control the number of requests per unit of time. You might need to handle rate limiting and include API tokens in the headers to authenticate your requests.
Best practices for working with PUT requests
Remember to read and adhere to the API documentation to understand usage limits, authentication requirements, and proper handling of data.
In this tutorial, we explored how to make a PUT request to an external API using the requests module in Python. We covered sending the request, handling the response, sending JSON data, error handling, and other essential aspects. Armed with this knowledge, you can now easily interact with various web APIs and incorporate external data into your Python applications.
By following best practices and understanding API-specific requirements, you can build robust and efficient applications that leverage the power of external APIs for enhanced functionality and data retrieval.
