python requests json post

Python Requests JSON POST

Python Requests library allows us to send HTTP requests using Python. We can send data in the form of JSON using the 'POST' method provided by the library. In this answer, I will explain how to use Python Requests to send a JSON POST request.

Step 1: Importing the Required Libraries


import requests
import json

Step 2: Defining the JSON Data

We need to define the JSON data that we want to send in the request. We can create a dictionary in Python and then convert it to JSON using the 'json.dumps()' function.


data = {'name': 'John', 'age': 30}
json_data = json.dumps(data)

Step 3: Sending the POST Request

We can now send the JSON data using the 'requests.post()' function. We need to provide the URL to which we want to send the request and the JSON data as a payload.


url = 'https://example.com/api'
response = requests.post(url, data=json_data)

Step 4: Handling the Response

We can handle the response returned by the API using the 'response' object returned by the 'requests.post()' function. We can get the response code using 'response.status_code' and the response content using 'response.content'.


if response.status_code == 200:
    print('Request Successful')
    print(response.content)
else:
    print('Request Failed')

Alternative Method: Sending JSON directly as Payload

We can also send the JSON data directly as the payload parameter of the 'requests.post()' function. In this method, we do not need to convert the dictionary to JSON using 'json.dumps()'.


data = {'name': 'John', 'age': 30}
url = 'https://example.com/api'
response = requests.post(url, json=data)