how.wtf

Resource vs Client in Python Boto3

· Thomas Taylor

Resource and Client are two different abstractions in the Boto3 SDK. What are the differences between the two?

Clients

Clients provide lower-level access to AWS Services. They typically represent a 1:1 functionality mapping of any AWS service API and are generated via JSON service definition files such as the one for DynamoDB. The botocore library is shared between the AWS CLI & Boto3.

For example, the DynamoDB PutItem API call requires TableName and Item parameters to be supplied. The Item parameter is required to be a PutItemAttributeMap which forces the user to add typing for each value. In addition to handling the strict input types, users are required to handle pagination.

1import boto3
2
3dynamodb = boto3.Client("dynamodb")
4dynamodb.put_item(
5    TableName="table_name",
6    Item={
7        "id": { "S": "test" }
8    }
9)

Resources

Resources provide higher-level access to AWS Services and reside within boto3. They are only supported for a subset of AWS services and are generated via JSON resource definition files such as the one for DynamoDB

For example, the DynamoDB PutItem API call is completed using the Table object.

1import boto3
2
3dynamodb = boto3.Resource("dynamodb")
4table = dynamodb.Table("table_name")
5table.put_item(
6    Item={
7        "id": "test"
8    }
9)

As opposed to the clients, resources typically handle marshalling data and pagination.

Should I use a client or resource?

If resources are available for the service your application is interfacing with, use them. Otherwise, use clients. The full list of services are here.

Note

Per the boto3 resources documentation,

The AWS Python SDK team does not intend to add new features to the resources interface in boto3. Existing interfaces will continue to operate during boto3’s lifecycle. Customers can find access to newer service features through the client interface.

The AWS Python SDK team will not be adding new resource abstractions; however, the resources that are supported will function in perpetuity.

#aws   #python  

Reply to this post by email ↪