python requests send json

Python Requests Send JSON

If you are working with APIs or web services, sending and receiving data in JSON format is a common practice. Python Requests library allows you to send JSON data easily with just a few lines of code.

Using Request's json parameter

The simplest way to send JSON data is by passing it as a dictionary to the 'json' parameter of the requests.post() method. Request's json parameter automatically serializes the dictionary and sets the Content-Type header to 'application/json'.


import requests

payload = {'name': 'John', 'age': 30}
response = requests.post('https://example.com/api', json=payload)

print(response.json())

In the above example, a dictionary 'payload' is created with JSON data. Then, it is passed as a parameter to the requests.post() method with the 'json' parameter. The response is obtained by calling the .json() method on the response object.

Manually setting headers and data

If you want more control over the headers or need to send additional data, you can manually set headers and data using the requests.post() method. In this case, you need to manually serialize the JSON data using the json.dumps() method and set the Content-Type header to 'application/json'.


import json
import requests

payload = {'name': 'John', 'age': 30}
headers = {'Content-Type': 'application/json'}

response = requests.post('https://example.com/api', data=json.dumps(payload), headers=headers)

print(response.json())

In the above example, a dictionary 'payload' is created with JSON data. The headers dictionary is created with a single key-value pair, setting the Content-Type header to 'application/json'. The payload is serialized using the json.dumps() method and passed as the 'data' parameter to requests.post() method. The response is obtained by calling the .json() method on the response object.

Conclusion

Sending JSON data with Python Requests library is easy and can be done in multiple ways. The simplest way is by using the 'json' parameter, which automatically serializes the dictionary and sets the Content-Type header to 'application/json'. If you need more control over headers or additional data, you can manually set headers and serialize the JSON data using the json.dumps() method.