boto3 Basics
10 examples to get you started with Cloud SDKs - 7 basic and 3 intermediate.
Search across all documentation pages
10 examples to get you started with Cloud SDKs - 7 basic and 3 intermediate.
uv venv && source .venv/bin/activate
uv pip install "boto3>=1.35"
aws configure --profile dev # or export AWS_PROFILE=dev~/.aws/credentials, environment variables, or instance/task IAM role.boto3.Session is the entry point for region, profile, and credential resolution.
import boto3
session = boto3.Session(profile_name="dev", region_name="us-east-1")
print(session.region_name)profile_name maps to ~/.aws/credentials sections.region_name - global clients still need a signing region.Related: Credential & Session Patterns - least privilege setups
Clients expose the raw AWS API - one method per API action.
import boto3
s3 = boto3.client("s3")
resp = s3.list_buckets()
print([b["Name"] for b in resp.get("Buckets", [])])Related: S3 - uploads, downloads, presigned URLs
Resources provide an object-oriented layer over clients.
import boto3
s3 = boto3.resource("s3")
for bucket in s3.buckets.all():
print(bucket.name)Bucket, Object, Table classes wrap common workflows.Related: S3 - streaming and object operations
Pin region to avoid surprising cross-region latency or wrong partition behavior.
import boto3
session = boto3.Session(region_name="eu-west-1")
dynamodb = session.client("dynamodb")
print(dynamodb.meta.region_name)meta.region_name confirms where requests sign.endpoint_url only for LocalStack, VPC endpoints, or custom gateways.Related: Retry, Pagination & Throttling - robust calls at scale
boto3 resolves credentials automatically when you do not pass keys in code.
import boto3
session = boto3.Session()
creds = session.get_credentials()
print(creds.method if creds else "no credentials")AWS_PROFILE selects a named profile without hardcoding in source.Related: Secrets Manager & SSM - runtime secret fetch
AWS errors arrive as botocore.exceptions.ClientError with structured codes.
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client("s3")
try:
s3.head_bucket(Bucket="definitely-missing-bucket-xyz")
except ClientError as exc:
code = exc.response["Error"]["Code"]
print(code)Error.Code (404, NoSuchBucket, AccessDenied) not message strings.response dict mirrors AWS XML/JSON error payloads.ResponseMetadata for AWS support tickets.Related: Cloud SDK Best Practices - safe error handling rules
Create clients once per process, not per request in hot loops.
import boto3
_SESSION = boto3.Session()
_SQS = _SESSION.client("sqs")
def send_message(queue_url: str, body: str) -> None:
_SQS.send_message(QueueUrl=queue_url, MessageBody=body)Related: SQS & SNS - queue and topic patterns
Stop hand-rolling NextToken loops - use built-in paginators.
import boto3
s3 = boto3.client("s3")
paginator = s3.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket="my-bucket", Prefix="logs/"):
for obj in page.get("Contents", []):
print(obj["Key"], obj["Size"])PaginationConfig={"MaxItems": 100} to cap dev scripts.Related: DynamoDB - query pagination
Wait until AWS finishes asynchronous creation before dependent steps.
import boto3
ec2 = boto3.client("ec2")
waiter = ec2.get_waiter("instance_running")
instance_id = "i-0123456789abcdef0"
waiter.wait(InstanceIds=[instance_id])time.sleep guesses in provisioning scripts.WaiterConfig={"Delay": 5, "MaxAttempts": 40} for long-running resources.Related: Provisioning Cloud Resources - bootstrap workflows
Tune retries and timeouts for production traffic patterns.
import boto3
from botocore.config import Config
config = Config(
retries={"max_attempts": 10, "mode": "standard"},
connect_timeout=5,
read_timeout=60,
)
s3 = boto3.client("s3", config=config)mode: adaptive helps under sustained throttling; standard is predictable default.Config object to every client in a service class.Related: Retry, Pagination & Throttling - throttling strategies
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 19, 2026