Post Python Requests JSON
If you want to send a JSON formatted data as a part of a HTTP POST request in Python using the requests library, you can do by following these steps:
Step 1: Import Requests Library
import requests
Step 2: Set the URL and JSON Data
You need to set the URL to which you want to send the POST request and also set the JSON data that you want to send.
url = 'https://example.com/api/v1'
data = {
"name": "John Doe",
"email": "[email protected]",
"phone": "1234567890",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
Step 3: Send the POST Request
You can now send the POST request using the requests.post() method.
response = requests.post(url, json=data)
The response object will contain the response from the server. You can check the status code and content of the response using the following code:
print(response.status_code)
print(response.content)
Example with Error Handling:
try:
response = requests.post(url, json=data)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err)
else:
print(response.status_code)
print(response.content)
Here, we are using a try-except block to handle any HTTP errors that may occur. The raise_for_status() method will raise an exception if the status code of the response is not in the 200-299 range.
Multiple Ways to Send JSON Data with Requests in Python:
There are multiple ways to send JSON data with the requests library in Python. Some of them are:
- Using the
data
parameter instead ofjson
- Serializing the JSON data manually and sending it as a string
- Using the
json.dumps()
function to encode the JSON data
However, using the json
parameter is the easiest and most recommended way to send JSON data with requests in Python.