AWS4 Authentication for Requests

1.3.1 · active · verified Sat Mar 28

requests-aws4auth is a Python library providing AWS Signature Version 4 authentication for the popular Requests HTTP library. It enables secure interaction with AWS APIs by signing HTTP requests according to the SigV4 protocol. The library is actively maintained with a history of regular releases and improvements.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up AWS4Auth using access keys and a service endpoint, then make a GET request using the `requests` library. For production, always use environment variables or a secure credential provider (like `boto3`'s session credentials with `RefreshableCredentials`).

import os
import requests
from requests_aws4auth import AWS4Auth

# It's highly recommended to use environment variables for sensitive AWS credentials
aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY_ID')
aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY', 'YOUR_SECRET_ACCESS_KEY')
aws_session_token = os.environ.get('AWS_SESSION_TOKEN', '') # Optional for temporary STS credentials

# Replace with your target AWS service region and canonical service name
aws_region = os.environ.get('AWS_REGION', 'us-east-1')
aws_service = os.environ.get('AWS_SERVICE', 's3') # e.g., 's3', 'es', 'execute-api'

if aws_access_key_id == 'YOUR_ACCESS_KEY_ID' or aws_secret_access_key == 'YOUR_SECRET_ACCESS_KEY':
    print("WARNING: AWS credentials are not set in environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY). "
          "Using placeholder values, which will likely fail authentication.")

# Construct the authentication object
auth = AWS4Auth(
    aws_access_key_id,
    aws_secret_access_key,
    aws_region,
    aws_service,
    session_token=aws_session_token if aws_session_token else None
)

# Example endpoint for S3 (adjust to your specific AWS endpoint)
endpoint = f"https://s3.{aws_region}.amazonaws.com/"
print(f"Attempting to connect to: {endpoint} with service: {aws_service}")

try:
    response = requests.get(endpoint, auth=auth)
    response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
    print(f"Successfully authenticated and received status code: {response.status_code}")
    # print(response.text) # Uncomment to see the response body
except requests.exceptions.HTTPError as e:
    print(f"HTTP Error: {e.response.status_code} - {e.response.text}")
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")

view raw JSON →