Python: How to POST Json Data with HTTP Request


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
}
Python HTTP POST with JSON Data Example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap