Introduction

AWS’ Boto3 library is used commonly to integrate Python applications with various AWS services. The two most commonly used features of boto3 are Clients and Resources. In this article, we will look into each one of these and explain how they work and when to use them.

Client

Clients provide a low-level interface to the AWS service. Their definitions are generated by a JSON service description present in the botocore library. The botocore package is shared between boto3 as well as the AWS CLI.

The service definition for AWS S3 is stored as a JSON under the botocore package.

The main benefit of using the Boto3 client are:

  • It maps 1:1 with the actual AWS service API.
  • All AWS service operations supported by clients

E.g. if you want to list all S3 buckets in your AWS account, you could use the S3 client like this:


import boto3

# Retrieve the list of existing buckets
s3 = boto3.client("s3")
response = s3.list_buckets()

# Output the bucket names
print("Existing buckets:")
for bucket in response['Buckets']:
    print(f'{bucket["Name"]}')

Under the hood, when you create a boto3 client, it uses the botocore package to create a client using the service definition.

Resource

Resources are a higher-level abstraction compared to clients. They are generated from a JSON resource description that is present in the boto library itself. E.g. this is the resource definition for S3.

Resources provide an object-oriented interface for interacting with various AWS services. Resources can be instantiated like the following:

import boto3

s3 = boto3.resource("s3")

Every resource instance is composed of the following:

Identifiers

An identifier is a unique value that is used to uniquely identify a particular resource. Some examples of identifiers are:


# S3 bucket identifier
bucket = s3.Bucket(name="my_bucket")

# S3 object identifier
obj = s3.Object(bucket_name="my_bucket", key="test.py")

Attributes

Resources can also have attributes associated with them. E.g., an S3 object has these attributes associated with it.

Actions

An action is a method which makes a call to the underlying AWS service. An example would be:


obj = s3.Object(bucket_name="my_bucket", key="test.py")
# action on S3 Object
response = obj.get()

Clients vs Resources

To summarize, resources are higher-level abstractions of AWS services compared to clients. Resources are the recommended pattern to use boto3 as you don’t have to worry about a lot of the underlying details when interacting with AWS services. As a result, code written with Resources tends to be simpler.

However, Resources aren’t available for all AWS services. In such cases, there is no other choice but to use a Client instead.