How to make custom HTTP requests in Python

HTTP, or Hypertext Transfer Protocol, is a protocol that allows resources to be fetched and transferred between clients and servers.

Various programming languages implement this protocol in their own ways. In this shot, we will look at how Python implements it.

We will make use of the requests module to make custom HTTP requests.

Get request

We first import the Python requests module into our project.

Next, we call the HTTP request method we want to make use of:

import requests
response = requests.get("www.example.com")

Code

To test a real example, we will make a request to JSONPlaceholder API, which is a free platform that provides JSON responses for testing purposes.

import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.status_code)
print(response.json())

This will give us the status code and the data returned from the server in JSON format.

Post request

As usual, we first import the Python requests module.

Next, we call the HTTP request method we want to make use of.

Unlike a get request, which sends its data in the URL, the post request can transfer data safely in an encrypted form in a request body.

import requests
response = requests.post("www.example.com",{'key': 23})

Code

We will send our post request to the posts endpoint.

import requests
payload = {'title':'Hello World!','body':'Welcome home.', 'userId':3}
response = requests.post('https://jsonplaceholder.typicode.com/posts', payload)
print(response.status_code)
print(response.text)

Put request

We import the Python requests module. Then, we call the HTTP request method that we will use.

The put request is very similar to the post request, as it also transfers its data safely in an encrypted form in a request body.

It is usually used to make updates.

import requests
response = requests.put("www.example.com",{'key': 23})

Code

We will send our put request, as usual, to the posts endpoint.

This put request updates the particular post with the sent payload.

import requests
payload = {'title':'John Doe', 'body':'Educative rocks!', 'userId':2}
response = requests.put('https://jsonplaceholder.typicode.com/posts/1', payload)
print(response.status_code)
print(response.text)

Delete request

We import the Python requests module. Then, we call the HTTP request method that we will use. In this case, this is the delete request.

It is usually used to remove an item.

import requests
response = delete("www.example.com/23")

Code

We will send our delete request, as usual, to the posts endpoint.

import requests
response = requests.delete('https://jsonplaceholder.typicode.com/posts/2')
print(response.status_code)
print(response.text)