Python Requests Post Body JSON
If you're working with APIs, sending JSON data as the request body is a common task. Python's requests
module makes it easy to send POST requests with JSON data.
Using the json
Parameter
The simplest way to send JSON data in a POST request is by using the json
parameter. Here's an example:
import requests
data = {"name": "John", "age": 30}
response = requests.post("https://example.com/api/users", json=data)
print(response.json())
In the above code, we create a dictionary with the data we want to send as JSON. Then we pass that dictionary as the value of the json
parameter in the post
method. The requests
module automatically sets the Content-Type
header to application/json
.
Using the data
Parameter
If you need more control over the headers or if you want to send data in a format other than JSON, you can use the data
parameter instead. Here's an example:
import json
import requests
data = {"name": "John", "age": 30}
json_data = json.dumps(data)
headers = {"Content-Type": "application/json"}
response = requests.post("https://example.com/api/users", data=json_data, headers=headers)
print(response.json())
In the above code, we first convert the data dictionary to a JSON string using the json
module's dumps
method. Then we create a dictionary of headers with the Content-Type
set to application/json
. Finally, we pass both the JSON data and headers as values of the data
and headers
parameters, respectively, in the post
method.