python requests post basic auth

Python Requests Post Basic Auth

If you are working with APIs, sometimes you need to authenticate your requests. One of the authentication methods is Basic Auth, which requires a username and a password. In Python, you can use the Requests library to send HTTP requests. Here is how you can send a POST request with Basic Auth:

Method 1: Using Auth Tuple

The requests.post() method accepts an optional parameter auth, which should be a tuple containing the username and the password. Here is an example:


import requests

url = 'https://api.example.com/endpoint'
data = {'key': 'value'}

response = requests.post(url, data=data, auth=('username', 'password'))

print(response.status_code)
print(response.json())

In this example, we are sending a POST request to https://api.example.com/endpoint with some data. We are also passing the username and password as a tuple to the auth parameter. The response object contains the status code and the JSON response from the server.

Method 2: Using HTTPBasicAuth Object

You can also use the HTTPBasicAuth object to authenticate your requests. Here is an example:


import requests
from requests.auth import HTTPBasicAuth

url = 'https://api.example.com/endpoint'
data = {'key': 'value'}
auth = HTTPBasicAuth('username', 'password')

response = requests.post(url, data=data, auth=auth)

print(response.status_code)
print(response.json())

In this example, we are creating an HTTPBasicAuth object with the username and password. We are then passing this object to the auth parameter of the requests.post() method. The response object contains the status code and the JSON response from the server.

Conclusion

These are two methods you can use to send a POST request with Basic Auth in Python using the Requests library. The first method is simpler and more concise, while the second method gives you more control over the authentication process.