In order to send JSON data with an HTTP Post Request in Python, we need to make use of two modules - requests and json.
Let's look at an example.
Example:
import requests
import json
# JSON Data
user_data = {
"username": "code2care",
"password": "password123",
"first_nane": "Mile",
"last_name": "Samuel",
"date_of_birth": "23-July-2000"
}
post_url = "https://code2care.org/api/v2/create_user"
headers = {"Content-Type": "application/json"}
try:
response = requests.post(post_url, data=json.dumps(user_data), headers=headers)
response.raise_for_status()
response_data = response.json()
print("Server Respose:")
print(response_data)
except requests.exceptions.RequestException as e:
print(f"An error occurred while creating user: {e}")
Make sure to set the request header Content-Type as application/json
Server Response:
{
"status": "success",
"message": "User created successfully!",
"status_code": 200
}

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!