How to make a POST request in Python

1 min

As for the GET request, we can use the requests library to perform a POST request in Python.

POST requests are extremely useful when you want to get data from APIs.

But even more when you want to send data.

To APIs or Apps so that they can process it and save it in their database. (e.g. Hubspot adding emails).

Installing requests

First we need to install the requests library using the pip python package manager

You can write this in your terminal, it will automatically install the requests library.

pip3 install requests
for Python 3.x
pip install requests
for Python 2.7

Performing the POST request

Once again we can use the test API endpoint : "https://reqbin.com/echo/post/json" that should return

{"success":"true"}
This is what we should get from this call
# We import the library
import requests

# We set the api endpoint we want to reach
url = "https://reqbin.com/echo/post/json"

# We define the data we want to pass
data = {
    "firstname" : "James",
    "lastname" : "Smith",
    "age": 27
}

# We perform the post request against the api endpoint
# we pass the dictionary data as body.
response = requests.post(url, data=data)
print(response.json())
The script to make an HTTP GET request against a website

The JSON dict response is now accessible from response.json()

print(response.json())
Printing the response JSON

Here you are! You can now make POST requests to any website using the requests library.