python requests library json body

Python Requests Library JSON Body

If you want to send JSON data in the body of a request using the Python Requests library, it is very easy to do so. The requests library provides a method called json that you can use to pass JSON data as the body of the request.

Using the json Method

In order to use the json method, you first need to import the requests library:


import requests
  

Next, you can create a dictionary that contains the JSON data that you want to send:


data = {
    "name": "John Smith",
    "email": "[email protected]"
}
  

Then, you can send a request with the JSON data in the body like this:


response = requests.post(url, json=data)
  

The json parameter automatically serializes the dictionary into JSON format and sets the appropriate content type header.

Using the data Method

If you prefer to manually serialize your JSON data, you can use the data parameter instead:


import json

data = {
    "name": "John Smith",
    "email": "[email protected]"
}

json_data = json.dumps(data)

response = requests.post(url, data=json_data, headers={"Content-Type": "application/json"})
  

In this example, we manually serialized the dictionary into JSON format using the json.dumps() method, and then passed the serialized data using the data parameter. We also set the appropriate content type header using the headers parameter.