python requests post json array

Python Requests Post JSON Array

If you want to send a POST request with JSON array in Python using the Requests library, here's how to do it:

Using the json parameter

You can pass a JSON-encoded array as the data parameter while making a POST request using the Requests library in Python. Here's how:


import requests

url = 'https://example.com/api/v1/users'
data = {'users': [{'name': 'John', 'age': 28}, {'name': 'Mary', 'age': 32}]}

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

print(response.status_code)
print(response.json())
    

In the above code, we're passing a dictionary with a key 'users' and value as a list of dictionaries. Each dictionary in the list represents a user with their name and age. We're then passing this dictionary to the json parameter of the post method. The API endpoint expects a JSON array of users, so we're sending it in the expected format.

Using the data parameter

You can also pass the JSON-encoded array as a string in the data parameter of the post method. Here's how:


import requests
import json

url = 'https://example.com/api/v1/users'
data = json.dumps({'users': [{'name': 'John', 'age': 28}, {'name': 'Mary', 'age': 32}]})

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

print(response.status_code)
print(response.json())
    

In this example, we're using the json module to encode the dictionary into JSON format and then passing it as a string to the data parameter. The API endpoint expects the data in JSON format, so we're sending it in the expected format.