HTTP (Hypertext Transfer Protocol) operates on a request-response model, serving as the core communication method between a client and server on the web. As a developer, it's important to know how HTTP works and how to use different methods it provides to create strong web apps. In this article, I'll show you how to write various HTTP methods in Python, like GET, POST, PATCH, PUT, and DELETE.
If you're interested in creating HTTP client-server application in GO language which can retry failed HTTP requests due to server internal errors or network glitches then, I highly recommend reading this article.
Prerequisites
Before diving into code, it's essential to have python
installed on your computer. For Windows users, the simplest method is to utilize 'winget' for Python installation.
You can learn more about how to use winget here.
pip
is a tool that comes with python
installations and is used to install different python packages and their dependencies
We'll use a widely-used Python package requests for handling HTTP requests
. To install this package, simply execute the following command:
$ pip install requests
HTTP Methods
GET
The HTTP GET method retrieves the requested resource located at a specific location (URL) from the server without modifying it. Following example illustrates how HTTP GET method requests a resource from the server.
def make_get_request(url, token):
try:
limit = 10
offset = 2
params = {'limit': {limit}, 'offset': offset}
api_header = {'Authorization': f'bearer {token}', 'Accept': 'application/json'}
response = requests.get(f"{url}", headers=api_header, params=params)
print(f"Request URL: {response.request.url}")
print(f'Received GET response from {response.url}')
if response.status_code == 200:
print('Resource retrieved successfully')
prtefied_response = json.dumps(response.json(), indent=2)
print(prtefied_response)
else:
print('Failed to retrieve resource')
except requests.RequestException as e:
print(f"GET request failed: {e}")
if __name__ == "__main__":
url = "https://api.coindesk.com/v1/bpi/currentprice.json"
token = "test-token"
make_get_request(url, token)
In this example, we write a function make_get_request()
, to send a get request to open API api.coindesk.com
, to get latest Bitcoin price in three different currencies, i.e. USD, GBP and EUR. It first sets up the necessary headers for the request, including the Authorization
header. We add JWT
(JSON Web Token), a dummy "test-token"
in Authorization
header for authentication and authorization purpose.
Here is output:
Request URL: https://api.coindesk.com/v1/bpi/currentprice.json?limit=10&offset=2
Received GET response from https://api.coindesk.com/v1/bpi/currentprice.json?limit=10&offset=2
Resource retrieved successfully
{
"time":
{
"updated": "May 13, 2024 22:21:17 UTC",
"updatedISO": "2024-05-13T22:21:17+00:00",
"updateduk": "May 13, 2024 at 23:21 BST"
},
"disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"chartName": "Bitcoin",
"bpi":
{
"USD":
{
"code": "USD",
"symbol": "$",
"rate": "62,875.814",
"description": "United States Dollar",
"rate_float": 62875.8143
},
"GBP":
{
"code": "GBP",
"symbol": "£",
"rate": "50,066.376",
"description": "British Pound Sterling",
"rate_float": 50066.3761
},
"EUR":
{
"code": "EUR",
"symbol": "€",
"rate": "58,275.128",
"description": "Euro",
"rate_float": 58275.128
}
}
}
POST
The HTTP POST method enables clients to send data to the server for the purpose of creating and updating a resource. HTTP clients typically use POST method to submit form data or upload files to the servers. They include the data
payload into the POST request body.
The following example illustrates how to use the POST method to send data to a server:
import requests
def make_post_request(url, token, data):
try:
api_header = {'Authorization': f'bearer {token}', 'Accept': 'application/json'}
# Make the POST request
response = requests.post(url, json=data, headers=api_header)
print(f'Received POST response from {response.url}')
# Check the response status code
if response.status_code == 201:
print('Resource created successfully')
print(response.json())
else:
print('Failed to create resource')
except requests.RequestException as e:
print(f"POST request failed: {e}")
# Example usage:
if __name__ == "__main__":
url = "https://example.com"
token = "test-token"
data = {'name': 'test-name', 'email': 'test@example.com'}
make_post_request(url, token, data)
PUT
The clients use HTTP PUT methods to update an already existing resource on the server. When sending PUT requests, the clients typically send the entire resource, even if they want to update only a portion of the resource.
We use the requests.put()
function to send an HTTP PUT request. The following code snippet shows how to use this function to update a resource:
import requests
import json
def make_put_request(url, token, data):
try:
api_header = {'Authorization': f'bearer {token}', 'Accept': 'application/json'}
# Make the PUT request
response = requests.put(url, json=data, headers=api_header)
print(f'Received PUT response from {response.url}')
# Check the response status code
if response.status_code == 200:
print('Resource updated successfully')
print(response.json())
else:
print('Failed to update resource')
except requests.RequestException as e:
print(f"PUT request failed: {e}")
if __name__ == "__main__":
url = "https://example.com"
token = "test-token"
data = {'name': 'test-name', 'email': 'test@example.com'}
make_put_request(url, token, data)
PATCH
The HTTP PATCH method is similar to the PUT and is used to update an existing resource on a server. However, the key difference is that a PATCH request is intended to update only a portion of the resource, rather than replacing the entire resource as with PUT. This method is often used in cases where only a few fields of a resource need to be updated, rather than the entire resource. To send an HTTP PATCH request in Python, we use the requests.patch() function. The code snippet below demonstrates how to use this function to update a resource:
import requests
import json
def make_patch_request(url, token, data):
try:
api_header = {'Authorization': f'bearer {token}', 'Accept': 'application/json'}
# Make the PATCH request
response = requests.patch(url, json=data, headers=api_header)
print(f'Received PATCH response from {response.url}')
# Check the response status code
if response.status_code == 200:
print('Resource updated successfully')
print(response.json())
else:
print('Failed to update resource')
except requests.RequestException as e:
print(f"PATCH request failed: {e}")
# Example usage:
if __name__ == "__main__":
url = "https://example.com"
token = "test-token"
data = {'name': 'updated-name', 'email': 'updated@example.com'}
make_patch_request(url, token, data)
The requests.patch()
function is used to send the PATCH request, with the updated data and headers included in the request. Finally, we check the response status code to determine if the update was successful or not.
DELETE
The clients use HTTP DELETE method to delete a resource on a server. When sending a DELETE request, we typically only need to specify the URL of the resource we want to delete.
We use the requests.delete()
function. The code snippet below demonstrates how to delete a resource:
import requests
def make_delete_request(url, token, resource_id):
try:
api_header = {'Authorization': f'bearer {token}', 'Accept': 'application/json'}
# Construct the URL with the resource ID
delete_url = f"{url}/{resource_id}"
# Make the DELETE request
response = requests.delete(delete_url, headers=api_header)
print(f'Received DELETE response from {response.url}')
# Check the response status code
if response.status_code == 204:
print('Resource deleted successfully')
else:
print('Failed to delete resource')
except requests.RequestException as e:
print(f"DELETE request failed: {e}")
if __name__ == "__main__":
url = "https://example.com/resource"
token = "test-token"
resource_id = "12345"
make_delete_request(url, token, resource_id)
If delete operation is successful on the server, the client will expect a 204 (No Content) status code. This is different from the 200 status code, because there is no response body returned by a DELETE request.
Conclusion
The HTTP methods GET, POST, PUT, PATCH, and DELETE are essential for interacting with web servers and APIs. These methods allow us to retrieve data, create and update resources, and delete data from servers. In Python, we can use the requests
library to make HTTP requests and handle the response data. We have provided examples of how to use each of these methods in Python, and how to handle the response data. We have also demonstrated how to add a callback function to a GET method, which allows us to execute custom code when the server responds to our request.