How to POST JSON data with Python Requests?
You can use the requests
library in Python to send a POST request with JSON data. Here is a code snippet that demonstrates how to do it:
import json
import requests
# Prepare the JSON data
data = {'name': 'John', 'age': 30}
json_data = json.dumps(data)
# Send the POST request with JSON data
headers = {'Content-type': 'application/json'}
response = requests.post('https://httpbin.org/post', data=json_data, headers=headers)
# Print the response
print(response.text)
In this example, the json.dumps()
method is used to convert the Python dictionary to a JSON object. The Content-type
header is set to application/json
to indicate that the request body contains JSON data. The requests.post()
method is then used to send the POST request with the JSON data.
Watch a video course
Python - The Practical Guide
You should replace the url 'https://httpbin.org/post' with the url endpoint you want to send the request to.
Note: The example above is a simple test case, you can also pass your json object directly to the data parameter, like this:
response = requests.post('https://httpbin.org/post', json=data)