0
0
DynamoDBquery~5 mins

Boto3 (Python) client vs resource in DynamoDB

Choose your learning style9 modes available
Introduction

We use Boto3 to talk to AWS services like DynamoDB. The client and resource are two ways to do this. The client is low-level and direct, while the resource is easier and more Python-friendly.

When you want full control over AWS DynamoDB API calls.
When you prefer simple and readable Python code to work with DynamoDB tables and items.
When you need to perform complex operations not yet supported by the resource interface.
When you want to quickly write code for common DynamoDB tasks without handling low-level details.
Syntax
DynamoDB
import boto3

# Create client
client = boto3.client('dynamodb')

# Create resource
resource = boto3.resource('dynamodb')

The client gives you direct access to DynamoDB API methods.

The resource provides higher-level, object-oriented access to DynamoDB.

Examples
Using client to list all DynamoDB tables.
DynamoDB
client = boto3.client('dynamodb')
response = client.list_tables()
Using resource to get a table object and scan its items.
DynamoDB
resource = boto3.resource('dynamodb')
table = resource.Table('MyTable')
response = table.scan()
Using client to add an item with explicit attribute types.
DynamoDB
client.put_item(TableName='MyTable', Item={'Id': {'S': '123'}, 'Name': {'S': 'Alice'}})
Using resource to add an item with simple Python dict.
DynamoDB
table.put_item(Item={'Id': '123', 'Name': 'Alice'})
Sample Program

This program lists DynamoDB tables using both client and resource methods and prints the results.

DynamoDB
import boto3

# Using client
client = boto3.client('dynamodb')
tables_client = client.list_tables()['TableNames']

# Using resource
resource = boto3.resource('dynamodb')
tables_resource = [table.name for table in resource.tables.all()]

print('Tables from client:', tables_client)
print('Tables from resource:', tables_resource)
OutputSuccess
Important Notes

The client requires you to handle data types explicitly (e.g., {'S': 'string'} for strings).

The resource automatically converts Python types to DynamoDB types, making code cleaner.

Some advanced DynamoDB features might only be available via the client.

Summary

The client is low-level and matches AWS API calls exactly.

The resource is higher-level and easier to use with Python objects.

Choose client for full control and resource for simplicity.