python requests post json with basic auth

Python Requests Post JSON with Basic Auth

Python is a widely used programming language for web development, data analysis, and artificial intelligence. One of the most popular libraries for making HTTP requests in Python is Requests. The library makes it easy to send HTTP/1.1 requests with built-in authentication, multipart/form-data encoding, and JSON format data. In this article, we will explore how to use Python Requests to make a POST request with JSON data and Basic Authentication.

Step 1: Import Required Libraries

First, we need to import the required libraries - Requests and JSON in Python.


import requests
import json

Step 2: Define Basic Authentication Credentials

To use Basic Authentication, we need to define the username and password. We can use the Python base64 library to encode the credentials.


username = "myusername"
password = "mypassword"
auth = (username, password)

Step 3: Define the JSON Data

We need to define the JSON data that we want to send in the POST request.


data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
json_data = json.dumps(data)

Step 4: Send the POST Request

We can now send the POST request using the Requests library. We need to define the URL, headers, authentication credentials, and JSON data.


url = "https://example.com/api/user"
headers = {"Content-Type": "application/json"}
response = requests.post(url, headers=headers, auth=auth, data=json_data)

Step 5: Handle the Response

We can check the status code and response content to ensure that the request was successful.


if response.status_code == 200:
    print("POST request successful")
    print(response.content)
else:
    print("POST request unsuccessful")

Alternative Method: Using JSON Parameter

We can also send JSON data in the POST request using the JSON parameter of the Requests library. This method automatically sets the Content-Type header to application/json and converts the JSON data to a string.


url = "https://example.com/api/user"
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
response = requests.post(url, auth=auth, json=data)