How to POST JSON Data With requests in Python

Siddharth Swami Feb 02, 2024
How to POST JSON Data With requests in Python

Python provides us with the requests library that allows us to interact between client and server for posting JSON data.

In this tutorial, we will post JSON data with Python requests.

The requests.post() function sends a POST request to the given URL. It returns a requests.Reponse type object.

For posting the JSON data, we will a URL object for targeting a URL string accepting the JSON data using the post() function.

We will then specify the post data. We will be passing the data through the message body as per the HTTP specification. We can specify the JSON data using the json parameter in the post() function. This parameter is available from requests module 2.4.2 version.

See the following example.

import requests

response = requests.post(
    "https://httpbin.org/post", json={"id": 1, "name": "ram sharma"}
)

print(response.status_code)

Output:

200

In our example, we also printed the status code of the requests.Reponse object. Status code 200 indicates that we were successful in sending the POST request with JSON data.

Below version 2.4.2 of the requests module, we can convert the data to JSON using the json.dumps() function and specify this data in the data parameter of the requests.post() function.

For example,

import requests
import json

response = requests.post(
    "https://httpbin.org/post", data=json.dumps({"id": 1, "name": "ram sharma"})
)

print(response.status_code)

Output:

200

Related Article - Python JSON