How to use Python Requests with Basic Authentication
If you want to access a HTTP resource that requires authentication using Python Requests library, you can use the built-in support for Basic Authentication. Basic Authentication is a simple authentication scheme that requires a username and password to be sent in the HTTP headers with every request.
Using Requests with Basic Authentication
To use Requests with Basic Authentication, you need to pass a tuple of (username, password) to the auth parameter of the requests.get() or requests.post() method. Here's an example:
import requests
url = 'http://example.com/api/something'
username = 'myusername'
password = 'mypassword'
response = requests.get(url, auth=(username, password))
print(response.text)
This code sends a GET request to the URL 'http://example.com/api/something' with the Basic Authentication headers included in the request. Replace 'myusername' and 'mypassword' with your actual credentials.
Other Ways to Use Basic Authentication
You can also pass a requests.auth.HTTPBasicAuth object instead of a tuple. This can be useful if you want to reuse the same authentication object for multiple requests:
import requests
from requests.auth import HTTPBasicAuth
url = 'http://example.com/api/something'
username = 'myusername'
password = 'mypassword'
auth = HTTPBasicAuth(username, password)
response1 = requests.get(url, auth=auth)
response2 = requests.get(url, auth=auth)
print(response1.text)
print(response2.text)
You can also specify the authentication headers directly in the headers parameter:
import requests
url = 'http://example.com/api/something'
username = 'myusername'
password = 'mypassword'
headers = {'Authorization': 'Basic ' + b64encode((username + ':' + password).encode()).decode()}
response = requests.get(url, headers=headers)
print(response.text)
This code sends a GET request to the URL 'http://example.com/api/something' with the Basic Authentication headers included in the request. The username and password are concatenated with a colon, base64 encoded and included in the Authorization header.