Python Requests Module Basic Auth
If you are working with web APIs that require authentication, you will need the Python Requests module to make authenticated requests. The requests module is used to send HTTP requests using Python.
Basic authentication is one of the simplest authentication methods. It requires a username and password combination to access a resource. In Python, you can use the Requests module to make HTTP Basic Auth requests.
Using the requests module for basic auth
When making a basic auth request with the requests module, you need to pass in the username and password as a tuple in the headers parameter.
import requests
url = 'https://my-api.com/data'
headers = {'Authorization': 'Basic ' + b64encode(b'username:password').decode('utf-8')}
response = requests.get(url, headers=headers)
- Line 1: Import the Requests module
- Line 3: Define the URL of the resource you want to access
- Line 4: Create the headers dictionary with the Authorization key and the Basic auth string. The string is encoded using base64encode() method.
- Line 6: Make a GET request to the URL passing headers as a parameter
Using the HTTPBasicAuth object
You can also use the HTTPBasicAuth object to create a Basic Authentication request in Python:
import requests
from requests.auth import HTTPBasicAuth
url = 'https://my-api.com/data'
auth = HTTPBasicAuth('username', 'password')
response = requests.get(url, auth=auth)
- Line 3: Import the HTTPBasicAuth object from the requests.auth module
- Line 5: Define the URL of the resource you want to access
- Line 6: Create an instance of the HTTPBasicAuth object with your username and password
- Line 8: Make a GET request to the URL passing auth as a parameter