boto3 is the Amazon Web Services (AWS) SDK for Python, allowing Python developers to write software that makes use of AWS services like Amazon S3, Amazon EC2, Amazon DynamoDB, and many more. It provides an object-oriented API as well as a low-level client API to interact with AWS services.
Key features of boto3 include:
- Ease of Use: It simplifies interaction with AWS by abstracting the underlying API calls, handling authentication, request signing, and error retries.
- Client Interface: Provides a low-level interface to AWS services, mapping directly to the underlying AWS API calls. This is useful for direct control over API parameters.
- Resource Interface: Offers a higher-level, more object-oriented interface for many services, representing AWS resources (like S3 buckets or EC2 instances) as Python objects. This makes code more readable and Pythonic.
- Comprehensive Service Support: boto3 supports almost all AWS services, allowing developers to automate and manage their AWS infrastructure programmatically.
- Session Management: Allows for different AWS credential profiles and regions to be used within the same application.
Common use cases for boto3 involve:
- Automating Infrastructure: Programmatically creating, managing, and deleting EC2 instances, S3 buckets, RDS databases, etc.
- Building Serverless Applications: Integrating Lambda functions with other AWS services.
- Data Processing: Working with S3 for data storage, DynamoDB for NoSQL databases, or Kinesis for streaming data.
- DevOps and CI/CD: Scripting AWS operations for deployment, monitoring, and maintenance.
To use boto3, you typically install it via pip (`pip install boto3`) and configure your AWS credentials (e.g., via environment variables, `~/.aws/credentials` file, or IAM roles for EC2 instances/Lambda functions).
Example Code
import boto3
import os
--- Configuration ---
Ensure your AWS credentials are configured (e.g., via environment variables,
~/.aws/credentials file, or IAM role if running on AWS infrastructure).
Example: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION
You can specify a region directly or let boto3 pick from environment/config
region_name = 'us-east-1' Replace with your desired region
--- S3 Client Example ---
Create a low-level S3 client
s3_client = boto3.client('s3', region_name=region_name)
print("--- Listing S3 Buckets (Client Interface) ---")
try:
response = s3_client.list_buckets()
print("Existing S3 buckets:")
for bucket in response['Buckets']:
print(f" - {bucket['Name']}")
except Exception as e:
print(f"Error listing buckets: {e}")
--- S3 Resource Example ---
Create a high-level S3 resource
s3_resource = boto3.resource('s3', region_name=region_name)
Define a bucket name for operations (must be globally unique)
IMPORTANT: Replace 'your-unique-boto3-test-bucket-12345' with an actual
existing bucket you own, or create a new one manually if you wish to upload.
Creating buckets programmatically requires appropriate permissions.
bucket_name = 'your-existing-boto3-test-bucket-12345'
file_content = "Hello from boto3! This is a test file."
file_name = "boto3_test_file.txt"
print(f"\n--- Uploading a file to '{bucket_name}' (Resource Interface) ---")
try:
Get the bucket object
bucket = s3_resource.Bucket(bucket_name)
Upload the string content to a file in the bucket
bucket.put_object(Key=file_name, Body=file_content)
print(f"Successfully uploaded '{file_name}' to bucket '{bucket_name}'.")
--- Listing Objects in the Bucket (Resource Interface) ---
print(f"\n--- Listing objects in '{bucket_name}' ---")
for obj in bucket.objects.all():
print(f" - {obj.key} (Last Modified: {obj.last_modified})")
--- Downloading the file (Client Interface) ---
print(f"\n--- Downloading '{file_name}' from '{bucket_name}' (Client Interface) ---")
download_path = f"downloaded_{file_name}"
s3_client.download_file(bucket_name, file_name, download_path)
print(f"File downloaded to '{download_path}'. Content:")
with open(download_path, 'r') as f:
print(f.read())
os.remove(download_path) Clean up the downloaded file
print(f"Cleaned up local file '{download_path}'.")
except boto3.exceptions.botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NoSuchBucket':
print(f"Error: Bucket '{bucket_name}' does not exist or you don't have access. Please update 'bucket_name'.")
else:
print(f"An AWS error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")








boto3