In development, we often need to interact with APIs that require authentication, andHTTP Basic Authentication is one of the most common methods. The Python <span><span>requests</span></span> library provides a simple and easy-to-use API for handling Basic Auth. This article will detail how to construct Basic Auth requests and implement persistent authentication to enhance code efficiency and security.
1. Basic Auth Basic Usage
Method 1: Directly Passing Authentication Information
import requests
url = "https://api.example.com/protected"
username = "your_username"
password = "your_password"
# Directly passing authentication information
response = requests.get(url, auth=(username, password))
print(response.status_code)
print(response.json())
Method 2: Using the <span>HTTPBasicAuth</span> Class
from requests.auth import HTTPBasicAuth
response = requests.get(url, auth=HTTPBasicAuth(username, password))
2. Persistent Authentication (Session Object)
If multiple requests to the same API are needed, using <span>requests.Session()</span> can maintain the authentication state, avoiding repeated sending of authentication information and improving performance.
Basic Session Usage
session = requests.Session()
session.auth = ("your_username", "your_password") # Set global authentication
# Subsequent requests automatically carry authentication information
response1 = session.get("https://api.example.com/api1")
response2 = session.post("https://api.example.com/api2", json={"key": "value"})
import requests
# Create and configure session
session = requests.Session()
session.auth = ('username', 'password') # Set default headers, cookies, etc.
session.headers.update({'User-Agent': 'MyApp/1.0'})
# The first request may include authentication handshake
response1 = session.get('https://api.example.com/api1')
# Subsequent requests will automatically use the same authentication and headers
response2 = session.get('https://api.example.com/api2')
Advantages of Session
✅ Connection Pool: Reduces the overhead of establishing TCP connections✅ Default Parameters: Global settings for <span>headers</span>, <span>cookies</span>, etc.✅ Cookie Persistence: Automatically handles session cookies
3. Advanced Usage
Custom Authentication Class
If the API uses Token Authentication or other methods, a custom authentication class can be created:
from requests.auth import AuthBase
class TokenAuth(AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, request):
request.headers["Authorization"] = f"Token {self.token}"
return request
# Use custom authentication
session = requests.Session()
session.auth = TokenAuth("your_api_token")
response = session.get("https://api.example.com/protected")
Using Environment Variables (More Secure)
import os
username = os.getenv("API_USERNAME") # Read from environment variable
password = os.getenv("API_PASSWORD")
session = requests.Session()
session.auth = (username, password)
response = session.get("https://api.example.com/data")
🔒 Recommendation: Do not hard-code sensitive information (like passwords) in the code; use a
<span>.env</span>file or environment variables for storage.
4. Error Handling and Best Practices
Error Handling
try:
response = requests.get("https://api.example.com/data", timeout=5)
response.raise_for_status() # Check HTTP error status codes
print(response.json())
except requests.exceptions.HTTPError as err:
print(f"HTTP Error: {err}")
except requests.exceptions.RequestException as err:
print(f"Request failed: {err}")
Best Practices
- Always use HTTPS (Basic Auth credentials are Base64 encoded, equivalent to plaintext transmission)
- Use Session to improve performance
- Set reasonable timeouts (to avoid hanging requests)
- Implement retry mechanisms (to handle temporary failures)
Session Example with Retry
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
# Configure retry strategy
retry = Retry(
total=3, # Maximum of 3 retries
backoff_factor=1, # Exponential backoff
status_forcelist=[500, 502, 503, 504] # Retry for these status codes
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("https://", adapter)
session.mount("http://", adapter)
try:
response = session.get("https://api.example.com/data", timeout=5)
print(response.json())
except Exception as e:
print(f"Request failed: {e}")
Summary
- Simple Authentication:
<span>requests.get(url, auth=(user, pass))</span> - Persistent Authentication: Use
<span>requests.Session()</span>and set<span>session.auth</span> - Advanced Features:
- Custom authentication classes
- Using environment variables to store sensitive information
- Implementing retry mechanisms
- Always use HTTPS
- Avoid hard-coding credentials
- Set reasonable timeouts and retry strategies