boto3: programming AWS in Python
Practical study notes on using boto3 (the AWS SDK for Python) to program AWS services: sessions, clients vs resources, credentials, paginators, waiters, error handling, and common tasks (S3 upload, listing EC2).
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Programming AWS from Python is common for automation, testing, CI/CD scripts, and backend services. boto3 is the official AWS SDK for Python; engineers use it to call AWS APIs reliably from scripts or applications, replacing manual console steps and enabling repeatable infrastructure code.
Key ideas
- API: Application Programming Interface — the HTTP endpoints and JSON payload format that AWS services expose. boto3 calls these APIs for you.
- Credentials: credentials are an AWS access key ID and secret access key (and optionally a session token) used to authenticate API requests. boto3 uses credentials from several sources (environment variables, shared credentials file, config file, IAM roles). Always follow least-privilege practice: give the script only the IAM permissions it needs. Default credential provider chain searches environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN), then shared credentials (
/.aws/credentials) and shared config (/.aws/config) including SSO or assume-role profiles, and finally role credentials from ECS/EC2/EKS metadata; select a profile with AWS_PROFILE and a default region with AWS_REGION or AWS_DEFAULT_REGION. - Region: the AWS geographical area where resources live (for example, ap-south-1). Most AWS requests are region-specific and boto3 resolves the region from your Session or configuration; some services are effectively global (for example, IAM, Route 53).
- Session: A boto3 Session is an object that holds configuration (credentials, region, profile). You can create multiple Sessions to talk to different accounts or regions.
- Client vs Resource: boto3 provides two programming styles.
- Client: low-level, direct mapping to AWS service API operations. Methods return dictionaries that match the JSON API. Use clients when you need every API feature or maximum control.
- Resource: higher-level, object-oriented interface built on clients. Resources provide Python objects with methods and attributes (for example, an S3 Object resource with .upload_file). Not all services have resources; resources are convenience layers.
- Paginator: a paginator handles API operations that return results in pages (limited by MaxResults / page size). Use boto3 paginators to iterate safely over large result sets.
- Waiter: a waiter polls a resource until it reaches a desired state (for example, EC2 instance reaches 'running'). Waiters avoid manual sleep loops.
- Retries and Exceptions: boto3 uses botocore for request logic and retries. Common exceptions are botocore.exceptions.ClientError and botocore.exceptions.NoCredentialsError. Handle errors and use exponential backoff where appropriate.
- Presigned URLs and multipart upload: for S3, you can create presigned URLs to allow temporary upload/download, and use multipart upload for large files.
Draw to explain (diagram description):
- Draw a box labelled "Your Python app" connected by an arrow to a box labelled "boto3 Session". From the Session draw two arrows: one to a box labelled "Client('s3') or Resource('s3')" and another to "Client('ec2')". From each client box draw arrows to boxes labelled respective AWS service endpoints (S3 API endpoint, EC2 API endpoint). Annotate the Session with "credentials (env/shared file/IAM role) and region".
Formulas
For programming, these are the syntax lines to remember (each line is a separate syntax with a short meaning):
import boto3 — import the boto3 library.
session = boto3.Session(profile_name='myprofile', region_name='ap-south-1') — create a Session with a named profile and region.
s3_client = boto3.client('s3') — create a low-level client for S3 using default session.
resource = boto3.resource('s3') — create a high-level resource for S3.
s3 = session.client('s3') — create a client from a specific Session (profile/region).
ec2_res = session.resource('ec2') — create a resource from a specific Session.
s3_client.upload_file('local.txt', 'my-bucket', 'remote.txt') — upload a file using client helper (handles multipart automatically for large files).
presigned = s3_client.generate_presigned_url('get_object', Params={'Bucket':'b','Key':'k'}, ExpiresIn=3600) — create a presigned URL.
paginator = ec2_client.get_paginator('describe_instances') — get a paginator for a list API.
for page in paginator.paginate(Filters=[...]): — iterate through pages.
waiter = ec2_client.get_waiter('instance_running') — get a waiter for EC2.
waiter.wait(InstanceIds=['i-0123456789abcdef0']) — block until the instance is 'running'.
from botocore.exceptions import ClientError — import common exception type for error handling.
from botocore.config import Config — configure retries/timeouts.
s3_client = boto3.client('s3', config=Config(retries={'mode':'standard','max_attempts':10})) — example of increasing max retry attempts.
Explain each symbol where needed: in boto3.client('s3') the string 's3' is the AWS service name; client is the low-level interface. In Session(...) the parameters are optional; if omitted, boto3 uses the default configuration and credentials.
Worked examples
Example 1 — Upload a local file to S3 (step-by-step with client and resource) Task: Upload ./report.pdf to bucket my-student-bucket with key reports/report.pdf. Steps (client style):
import boto3and create a client:s3 = boto3.client('s3').- Call upload_file:
s3.upload_file('report.pdf', 'my-student-bucket', 'reports/report.pdf'). - On success, the API returns None — check for exceptions.
Trace details (what boto3 does): it creates a PUT request to the S3 endpoint, signs it with credentials, and for files over a threshold it uses multipart upload automatically.
Important checks: ensure bucket exists and your IAM permissions include
s3:PutObjecton the key or bucket. Single PUT (put_object) is limited to 5 GB; multipart upload supports objects up to 5 TB;upload_fileuses multipart automatically above a threshold (~8 MB by default).
Example 2 — List EC2 instances with filters and paginator Task: List instance IDs and state for instances with tag "Env=dev". Steps:
ec2 = boto3.client('ec2', region_name='ap-south-1').- Create paginator:
p = ec2.get_paginator('describe_instances'). - Iterate pages:
for page in p.paginate(Filters=[{'Name':'tag:Env','Values':['dev']}]):then for each reservation inpage['Reservations']and each instance inreservation['Instances'], printInstanceIdandState['Name']. Step-by-step example output for a small input (two instances):
- Page 1 contains Reservations [R1], R1 -> Instances I-a (running), I-b (stopped). Your loop prints those two lines.
Notes:
describe_instancesreturns nested structure Reservations -> Instances. Paginator ensures you see all results even if AWS paginates.
Example 3 — Generate a presigned URL for downloading an S3 object
s3 = boto3.client('s3')url = s3.generate_presigned_url('get_object', Params={'Bucket':'my-bucket','Key':'reports/report.pdf'}, ExpiresIn=600)- Share the URL (valid for 10 minutes). aws SDK signs it so recipient can GET without credentials. With Signature Version 4, the maximum expiry is 7 days.
Common mistakes
- Not handling pagination: calling list APIs without paginators returns only the first page and misses results.
- Ignoring exceptions: APIs often return partial failures or throttling errors; always catch ClientError and implement retry/backoff for retryable errors.
- Privilege issues: using overly-permissive IAM credentials in scripts. Use fine-grained policies or temporary credentials.
- Hardcoding credentials in source code — never commit access keys; use environment variables, shared credentials file, or IAM roles.
- Misunderstanding put vs upload semantics in S3:
put_objectuploads a bytes-like object or small file;upload_fileis a helper that handles multipart and retries.
For your exam
Types of questions you will see:
- Definitions: define boto3, Session, client, resource, paginator, waiter. A full-marks answer names the concept, gives the exact purpose, and an example syntax line.
- Short notes: differences between client and resource, credential precedence, how to create presigned URLs, explain paginators/waiters.
- Small programs: write a short Python script using boto3 to list S3 buckets, upload a file, or describe EC2 instances. A full-marks script includes imports, creating session/client, necessary calls, and minimal error handling.
- Traces/algorithms: step through what happens when boto3.upload_file calls multipart upload. A complete answer explains the multipart steps (create multipart upload, upload parts, complete multipart upload) and how retries apply.
- Diagrams: draw the flow from Python -> boto3 Session -> client/resource -> AWS endpoints and show where credentials/region are applied. Label boxes and arrows and annotate with credential sources.
What to include for full marks in code answers:
- Correct import and client/resource creation.
- Explicit mention of credentials and region resolution or show explicit Session with profile.
- Use of paginator or waiter where appropriate.
- Basic error handling using botocore.exceptions.ClientError.
Quick check
- What is the difference between a boto3 client and a resource?
- How do you iterate all results returned by an AWS list API that paginates?
- How do you create a presigned URL for an S3 object valid for 5 minutes?
Answers: 1) Client is low-level direct API mapping (dicts); Resource is high-level object-oriented wrapper (objects with methods). 2) Use a paginator from
client.get_paginator('operation')and loopfor page in paginator.paginate(...):. 3)s3.generate_presigned_url('get_object', Params={'Bucket':'BUCKET','Key':'KEY'}, ExpiresIn=300)
(Notes for reviewer: I tried to be concise and include the commands students must remember. I did not re-teach IAM or EC2 in detail; I referred to them by name as required.)
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?