Python Requests Post List of Dictionary
If you want to send a list of dictionaries in a POST request using Python requests module, you need to pass them as a JSON object.
Using JSON
First, you need to import the requests module and the json module:
import requests
import json
Then, you can create a list of dictionaries:
data = [
{
"name": "John",
"age": 30
},
{
"name": "Jane",
"age": 25
}
]
Next, you can convert the list of dictionaries to a JSON object:
json_data = json.dumps(data)
Then, you can send a POST request with the JSON data:
response = requests.post(url, data=json_data)
Make sure to set the Content-Type header to application/json:
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json_data, headers=headers)
Using Form Data
You can also send a list of dictionaries as form data. In this case, you need to use the urlencode function from the urllib module to encode the form data:
import requests
from urllib.parse import urlencode
data = [
{
"name": "John",
"age": 30
},
{
"name": "Jane",
"age": 25
}
]
encoded_data = urlencode({"data": data})
response = requests.post(url, data=encoded_data)
Make sure to set the Content-Type header to application/x-www-form-urlencoded:
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(url, data=encoded_data, headers=headers)
These are two ways you can send a list of dictionaries in a POST request using Python requests module.