Python Requests Post Request Body
When making a HTTP POST request using Python Requests library, we can pass data in the request body of the HTTP POST request. The data can be sent as form-encoded data or JSON data. In this post, we will look at how to send the request body in both the formats using Python Requests library.
Sending Form Encoded Data
Form-encoded data is the most common way of sending data over HTTP POST requests. To send form-encoded data in the request body, we can use the data
parameter of the requests.post()
method.
import requests
url = 'https://example.com/api'
data = {
'name': 'John Doe',
'email': '[email protected]'
}
response = requests.post(url, data=data)
print(response.status_code)
print(response.text)
In the above example, we have defined a dictionary data
with the data to be sent in the request body. We have then passed this dictionary to the data
parameter of the requests.post()
method.
Sending JSON Data
If we want to send JSON data in the request body, we can use the json
parameter of the requests.post()
method. The json
parameter automatically sets the Content-Type
header to application/json
.
import requests
import json
url = 'https://example.com/api'
data = {
'name': 'John Doe',
'email': '[email protected]'
}
json_data = json.dumps(data)
response = requests.post(url, json=json_data)
print(response.status_code)
print(response.text)
In the above example, we have defined a dictionary data
with the data to be sent in the request body. We have then converted this dictionary to a JSON string using the json.dumps()
method. We have then passed this JSON string to the json
parameter of the requests.post()
method.
Conclusion
In this post, we have seen how to send data in the request body of a HTTP POST request using Python Requests library. We have seen how to send data in both form-encoded and JSON formats.