AWS SigV4 Authentication for Requests

0.7 · active · verified Sat Apr 11

requests-auth-aws-sigv4 is a Python library that provides an authentication class to integrate AWS Signature Version 4 (SigV4) into the popular `requests` module. It simplifies the process of signing HTTP requests to AWS services, including API Gateway, Elasticsearch, and others, by handling credential retrieval from environment variables, parameters, or `boto3`. The current version is 0.7, with its last release in February 2021, indicating a mature and stable but less frequently updated library.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `requests-auth-aws-sigv4` to sign a request to the AWS Security Token Service (STS) `GetCallerIdentity` API. It shows how to initialize the `AWSSigV4` class with the service and region, explicitly providing credentials or relying on environment variables. The example includes error handling for common `requests` exceptions.

import os
import requests
from requests_auth_aws_sigv4 import AWSSigV4

# Ensure AWS credentials are set as environment variables for a runnable example
# export AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY
# export AWS_SECRET_ACCESS_KEY=YOUR_SECRET_KEY
# export AWS_SESSION_TOKEN=YOUR_SESSION_TOKEN (optional, for temporary 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', None)

# Example: Call AWS STS GetCallerIdentity
# Replace with your actual service endpoint and region if different
aws_service = 'sts'
aws_region = 'us-east-1'
url = f'https://sts.{aws_region}.amazonaws.com'

# Initialize AWSSigV4 with service and region. Credentials can be provided as parameters
# or will be automatically picked up from environment variables or boto3 if available.
auth = AWSSigV4(
    aws_service,
    aws_region,
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
    aws_session_token=aws_session_token
)

# Make a POST request with the SigV4 authentication
# For GetCallerIdentity, the body is typically simple XML or URL-encoded form data.
# Here, we simulate a simple POST with required parameters.
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {'Version': '2011-06-15', 'Action': 'GetCallerIdentity'}

try:
    response = requests.post(url, headers=headers, data=data, auth=auth)
    response.raise_for_status() # Raise an exception for HTTP errors
    print(f"Status Code: {response.status_code}")
    print(f"Response Body:\n{response.text}")
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")
    if e.response is not None:
        print(f"Error Response Body:\n{e.response.text}")

view raw JSON →