๐ง Understanding Boto3: Overview
Boto3 is the official AWS SDK for Python, used to interact with AWS services like S3, EC2, Lambda, DynamoDB, etc.
⚙️ 1. boto3.client()
vs boto3.resource()
vs boto3.session()
✅ boto3.client(service_name, ...)
-
Low-level client.
-
Maps 1:1 to AWS service APIs.
-
Returns response dicts (JSON-like).
-
Example:
client('s3')
✅ boto3.resource(service_name, ...)
-
High-level abstraction.
-
Uses Python objects.
-
Easier for common operations (like
bucket.upload_file(...)
)
⚠️ Not available for all AWS services.
✅ boto3.session.Session(...)
-
Used to manage configuration: profiles, credentials, and regions.
-
You can have multiple sessions, for example for multi-account or multi-region setups.
๐ When to Use What
Feature | Use client() | Use resource() | Use session() |
---|---|---|---|
Needs raw API access | ✅ Yes | ❌ No | ❌ Use session.client() |
Object-based actions | ❌ Too verbose | ✅ Ideal | ✅ For multi-profile access |
Working across profiles | ❌ Only default or env vars | ❌ Same | ✅ Fully supported |
Need flexibility | ✅ Advanced control | ❌ Less control | ✅ Multi-region and credential flexibility |
✅ Example 1: Using boto3.client
to List S3 Buckets
Why use client?
We want direct access to AWS API to fetch raw data like bucket names.
✅ Example 2: Using boto3.resource
to Upload File to S3
Why use resource?
This is a high-level operation (upload_file
) which is easier with resource
than calling put_object()
manually with client
.
✅ Example 3: Using boto3.session
for Multiple Profiles
Let's say you have 2 AWS profiles: dev
and prod
.
Why use session?
Each session uses its own credentials and region. Useful for multi-account management.
✅ Example 4: Using boto3.session
to Assume Role into Another Account
Why use session?
You can create temporary sessions with assumed roles — essential in enterprise, multi-account setups.
๐งช Quick Summary Table
Use Case | Method Used | Why? |
---|---|---|
List S3 buckets | boto3.client() | Raw API for precise data |
Upload files to S3 | boto3.resource() | High-level object methods |
Switch between dev and prod accounts | boto3.session() | Supports multiple profiles |
Cross-account access with STS assume role | boto3.session() | Use temporary credentials via STS |
๐งฐ Pro Tip
Use session.client()
or session.resource()
like this:
It gives you flexibility + cleaner multi-env support.
✅ 1. S3 File Operations (Upload, List, Download)
✅ Use
resource
for S3 when you want file operations, cleaner syntax, and auto-pagination.
✅ 2. EC2: Launch Instance, List Instances
✅
boto3.resource('ec2')
is great for managing instances in an object-oriented way.
✅ 3. EKS: List Clusters and Get Cluster Info
❗ EKS supports only
client
, notresource
.
✅ 4. Lambda: List and Invoke a Function
❗
client
is required for AWS Lambda.
✅ 5. DynamoDB: Add Item, Query Table
✅
resource
is perfect for table access in DynamoDB.