python requests post payload json

Python Requests POST Payload JSON

When working with APIs, sending data in JSON format is a common way of exchanging data with the server. In Python, we use the requests library to make HTTP requests to the server.

POST Request with JSON Payload

To send a POST request with JSON payload, we need to specify the content-type header as application/json and pass the data as a dictionary which will be converted to JSON by requests library. Here is an example:


import requests
import json

url = 'https://example.com/api/v1/users'
headers = {'Content-Type': 'application/json'}
data = {
    'name': 'John Smith',
    'email': '[email protected]',
    'age': 30
}
json_data = json.dumps(data)

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

print(response.json())
  

In the above example, we first import the requests and json libraries. Then, we define the URL of the API endpoint and specify the content-type header. We also define the data that we want to send in JSON format and convert it to a JSON string using json.dumps() method. Finally, we make a post request using requests.post() method and print the response.

Alternative Way of Passing JSON Payload

There is another way of passing JSON payload in a POST request using json parameter instead of data parameter. Here is an example:


import requests

url = 'https://example.com/api/v1/users'
headers = {'Content-Type': 'application/json'}
data = {
    'name': 'John Smith',
    'email': '[email protected]',
    'age': 30
}

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

print(response.json())
  

In the above example, we use the json parameter instead of data parameter while making the POST request. The requests library automatically sets the content-type header to application/json and converts the data to JSON format.