To interact directly with Amazon S3 via its API without using Boto3, you can use the requests library for HTTP requests in Python. However, you will also need to handle AWS's signature version 4 request signing process to authenticate your requests.
Below is a Python script that demonstrates how to implement the basic S3 operations (create object, remove object, update object, list buckets, list objects, and get object) using the AWS S3 API endpoints directly. You'll need to install the requests library if you haven't already:
pip install requests
Here's an implementation using the requests library:
import requests
import datetime
import hashlib
import hmac
import json
import os
class S3FileSystemInterface:
def __init__(self, aws_access_key_id, aws_secret_access_key, region_name='us-east-1'):
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.region_name = region_name
self.service = 's3'
self.endpoint = f'https://{self.region_name}.amazonaws.com'
def _get_signature(self, method, canonical_uri, canonical_querystring, canonical_headers, payload, date, amz_date):
# Create the canonical request
canonical_request = f"{method}\n{canonical_uri}\n{canonical_querystring}\n{canonical_headers}\n\n"
canonical_request += 'UNSIGNED-PAYLOAD'
# Create the string to sign
string_to_sign = f"AWS4-HMAC-SHA256\n{amz_date}\n{date}/{self.region_name}/{self.service}/aws4_request\n" + \
hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()
# Calculate the signature
k_date = hmac.new(f'AWS4{self.aws_secret_access_key}'.encode('utf-8'), date.encode('utf-8'), hashlib.sha256).digest()
k_region = hmac.new(k_date, self.region_name.encode('utf-8'), hashlib.sha256).digest()
k_service = hmac.new(k_region, self.service.encode('utf-8'), hashlib.sha256).digest()
k_signing = hmac.new(k_service, 'aws4_request'.encode('utf-8'), hashlib.sha256).digest()
signature = hmac.new(k_signing, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()
return signature
def create_object(self, bucket_name, object_name, file_content):
method = 'PUT'
canonical_uri = f'/{bucket_name}/{object_name}'
canonical_querystring = ''
date = datetime.datetime.utcnow().strftime('%Y%m%d')
amz_date = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
headers = {
'Content-Length': str(len(file_content)),
'Content-Type': 'text/plain',
'Host': f'{bucket_name}.s3.amazonaws.com',
'x-amz-content-sha256': 'UNSIGNED-PAYLOAD',
'x-amz-date': amz_date,
}
canonical_headers = ''.join([f"{k}:{v}\n" for k, v in headers.items()])
signature = self._get_signature(method, canonical_uri, canonical_querystring, canonical_headers, file_content, date, amz_date)
headers['Authorization'] = f"AWS4-HMAC-SHA256 Credential={self.aws_access_key_id}/{date}/{self.region_name}/{self.service}/aws4_request, SignedHeaders={';'.join(headers.keys())}, Signature={signature}"
response = requests.put(f'https://{bucket_name}.s3.amazonaws.com/{object_name}', data=file_content, headers=headers)
if response.status_code == 200:
print(f"Object '{object_name}' created in bucket '{bucket_name}'.")
else:
print(f"Failed to create object '{object_name}'. Status Code: {response.status_code}, Response: {response.text}")
def remove_object(self, bucket_name, object_name):
method = 'DELETE'
canonical_uri = f'/{bucket_name}/{object_name}'
canonical_querystring = ''
date = datetime.datetime.utcnow().strftime('%Y%m%d')
amz_date = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
headers = {
'Host': f'{bucket_name}.s3.amazonaws.com',
'x-amz-date': amz_date,
}
canonical_headers = ''.join([f"{k}:{v}\n" for k, v in headers.items()])
signature = self._get_signature(method, canonical_uri, canonical_querystring, canonical_headers, '', date, amz_date)
headers['Authorization'] = f"AWS4-HMAC-SHA256 Credential={self.aws_access_key_id}/{date}/{self.region_name}/{self.service}/aws4_request, SignedHeaders={';'.join(headers.keys())}, Signature={signature}"
response = requests.delete(f'https://{bucket_name}.s3.amazonaws.com/{object_name}', headers=headers)
if response.status_code == 204:
print(f"Object '{object_name}' removed from bucket '{bucket_name}'.")
else:
print(f"Failed to remove object '{object_name}'. Status Code: {response.status_code}, Response: {response.text}")
def update_object(self, bucket_name, object_name, new_file_content):
# Updating an object can be done by creating a new one with the same name.
self.create_object(bucket_name, object_name, new_file_content)
print(f"Object '{object_name}' updated in bucket '{bucket_name}'.")
def list_buckets(self):
method = 'GET'
canonical_uri = '/'
canonical_querystring = ''
date = datetime.datetime.utcnow().strftime('%Y%m%d')
amz_date = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
headers = {
'Host': 's3.amazonaws.com',
'x-amz-date': amz_date,
}
canonical_headers = ''.join([f"{k}:{v}\n" for k, v in headers.items()])
signature = self._get_signature(method, canonical_uri, canonical_querystring, canonical_headers, '', date, amz_date)
headers['Authorization'] = f"AWS4-HMAC-SHA256 Credential={self.aws_access_key_id}/{date}/{self.region_name}/{self.service}/aws4_request, SignedHeaders={';'.join(headers.keys())}, Signature={signature}"
response = requests.get('https://s3.amazonaws.com/', headers=headers)
if response.status_code == 200:
buckets = json.loads(response.text)
print("Buckets:")
for bucket in buckets.get('Buckets', []):
print(f" - {bucket['Name']}")
return buckets
else:
print(f"Failed to list buckets. Status Code: {response.status_code}, Response: {response.text}")
return []
def list_objects(self, bucket_name):
method = 'GET'
canonical_uri = f'/{bucket_name}'
canonical_querystring = ''
date = datetime.datetime.utcnow().strftime('%Y%m%d')
amz_date = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
headers = {
'Host': f'{bucket_name}.s3.amazonaws.com',
'x-amz-date': amz_date,
}
canonical_headers = ''.join([f"{k}:{v}\n" for k, v in headers.items()])
signature = self._get_signature(method, canonical_uri, canonical_querystring, canonical_headers, '', date, amz_date)
headers['Authorization'] = f"AWS4-HMAC-SHA256 Credential={self.aws_access_key_id}/{date}/{self.region_name}/{self.service}/aws4_request, SignedHeaders={';'.join(headers.keys())}, Signature={signature}"
response = requests.get(f'https://{bucket_name}.s3.amazonaws.com/', headers=headers)
if response.status_code == 200:
objects = xmltodict.parse(response.content)
print(f"Objects in bucket '{bucket_name}':")
for obj in objects.get('ListBucketResult', {}).get('Contents', []):
print(f" - {obj['Key']}")
return objects
else:
print(f"Failed to list objects in bucket '{bucket_name}'. Status Code: {response.status_code}, Response: {response.text}")
return []
def get_object(self, bucket_name, object_name):
method = 'GET'
canonical_uri = f'/{bucket_name}/{object_name}'
canonical_querystring = ''
date = datetime.datetime.utcnow().strftime('%Y%m%d')
amz_date = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
headers = {
'Host': f'{bucket_name}.s3.amazonaws.com',
'x-amz-date': amz_date,
}
canonical_headers = ''.join([f"{k}:{v}\n" for k, v in headers.items()])
signature = self._get_signature(method, canonical_uri, canonical_querystring, canonical_headers, '', date, amz_date)
headers['Authorization'] = f"AWS4-HMAC-SHA256 Credential={self.aws_access_key_id}/{date}/{self.region_name}/{self.service}/aws4_request, SignedHeaders={';'.join(headers.keys())}, Signature={signature}"
response = requests.get(f'https://{bucket_name}.s3.amazonaws.com/{object_name}', headers=headers)
if response.status_code == 200:
return response.content
else:
print(f"Failed to get object '{object_name}'. Status Code: {response.status_code}, Response: {response.text}")
# Example usage
if __name__ == "__main__":
# Replace with your AWS credentials
AWS_ACCESS_KEY_ID = 'your_access_key_id'
AWS_SECRET_ACCESS_KEY = 'your_secret_access_key'
REGION_NAME = 'us-east-1' # or whatever region you're working in
s3_interface = S3FileSystemInterface(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, REGION_NAME)
# Example Operations
bucket_name = 'your_bucket_name'
object_name = 'example.txt'
file_content = 'Hello, this is a test content.'
# Create object
s3_interface.create_object(bucket_name, object_name, file_content)
# List buckets
s3_interface.list_buckets()
# List objects in the bucket
s3_interface.list_objects(bucket_name)
# Get object
content = s3_interface.get_object(bucket_name, object_name)
if content:
print(content.decode('utf-8'))
# Update object
new_content = 'Updated content.'
s3_interface.update_object(bucket_name, object_name, new_content)
# Remove object
s3_interface.remove_object(bucket_name, object_name)
Important Points to Consider:
- Credentials: Replace
your_access_key_id and your_secret_access_key with your actual AWS credentials.
- Error Handling: This script includes basic error handling, but you might want to develop it further to cover specific cases.
- Regions: Make sure the region you set matches where your S3 bucket resides.
- XML Processing: Note that the
list_objects method expects xmltodict to convert the XML Alice response to a dictionary. You would need to install it with pip install xmltodict.
- Signing Process: The script manually creates the AWS Signature Version 4, which is necessary for the API to accept requests. This process involves creating a canonical string and calculating the HMAC signature.
- Permissions: Ensure your IAM user has the necessary permissions to perform these actions on the specified S3 bucket.
- Networking: Ensure that your network configuration allows outbound requests to AWS S3 endpoints.
This code provides a basic S3 filesystem-like interface using direct HTTP calls to AWS S3, handling create, delete, update, list, and get operations.