Python Requests Post Body Example
If you are working with Python and need to send a POST request, you can use the requests
module. This module allows you to easily send HTTP requests, including POST requests, to a web server.
Example One:
One way to send a POST request with a body in Python using the requests
module is as follows:
import requests
url = 'https://example.com/api/create_user'
data = {
'name': 'John Smith',
'email': '[email protected]',
'password': 'pa$$w0rd'
}
response = requests.post(url, json=data)
print(response.status_code)
print(response.json())
- The first step is to import the
requests
module. - Next, you define the URL you want to send the POST request to.
- You then create a dictionary with the data you want to send in the POST request. In this example, we are sending the user's name, email address, and password.
- The
requests.post()
method is used to send the POST request. We pass in the URL and the data we created above as a JSON object using thejson
parameter. - We then print the status code and response JSON.
Example Two:
You can also use the data
parameter instead of json
for sending form data:
import requests
url = 'https://example.com/api/create_user'
data = {
'name': 'John Smith',
'email': '[email protected]',
'password': 'pa$$w0rd'
}
response = requests.post(url, data=data)
print(response.status_code)
print(response.json())
In this example, we are using the data
parameter instead of json
. This is because we are sending form data, not JSON data.
These are just a couple of examples of how you can send a POST request with a body in Python using the requests
module. There are many other ways to send HTTP requests in Python, but requests
is one of the most popular and easiest to use.