AWS Requests Auth
aws-requests-auth (version 0.4.3) is a Python library that implements the AWS Signature Version 4 signing process for the popular `requests` module. It enables authentication to AWS services that support Signature Version 4, originally designed for AWS Elasticsearch instances but extensible to other services. The library has been stable since its last release in May 2020.
Warnings
- gotcha Incorrect or expired AWS credentials (access key, secret key, session token) or an invalid combination of host, region, and service are common causes of authentication failures. AWS will respond with errors like `InvalidClientTokenId` or `SignatureDoesNotMatch` if the request cannot be authenticated.
- gotcha When deploying applications using `aws-requests-auth` to serverless environments (e.g., AWS Lambda), ensure the library, along with its dependencies (like `requests`), is correctly bundled in your deployment package. Failure to do so can result in `Runtime.ImportModuleError` (e.g., `No module named 'aws_requests_auth'`).
- gotcha If using the `BotoAWSRequestsAuth` class for automatic credential retrieval, `botocore` is an optional dependency that must be installed. Without `botocore`, `BotoAWSRequestsAuth` cannot function and may lead to runtime errors or incorrect credential handling.
Install
-
pip install aws-requests-auth
Imports
- AWSRequestsAuth
from aws_requests_auth.aws_auth import AWSRequestsAuth
- BotoAWSRequestsAuth
from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
Quickstart
import requests
import os
from aws_requests_auth.aws_auth import AWSRequestsAuth
aws_access_key = os.environ.get('AWS_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY')
aws_secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY', 'YOUR_SECRET_KEY')
aws_region = os.environ.get('AWS_DEFAULT_REGION', 'us-east-1')
aws_service = 'es' # Example service, e.g., 'es' for Elasticsearch, 's3', 'execute-api'
aws_host = 'your-aws-endpoint.amazonaws.com'
# For STS temporary credentials, include aws_token
aws_token = os.environ.get('AWS_SESSION_TOKEN')
auth = AWSRequestsAuth(
aws_access_key=aws_access_key,
aws_secret_access_key=aws_secret_key,
aws_host=aws_host,
aws_region=aws_region,
aws_service=aws_service,
aws_token=aws_token # Pass if using STS temporary credentials
)
try:
# Replace with your actual endpoint
response = requests.get(f'https://{aws_host}/_cat/health', auth=auth, timeout=10)
response.raise_for_status() # Raise an exception for HTTP errors
print("Successfully authenticated and received response:")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f"Response Status Code: {e.response.status_code}")
print(f"Response Body: {e.response.text}")
print("Please ensure your AWS credentials, host, region, and service are correct.")