Python
Amazon DynamoDB
AWS SDK
Boto3
Database Access

How can I access Amazon DynamoDB via Python?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Accessing Amazon DynamoDB via Python

Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. Accessing DynamoDB through Python is a common requirement for developers who are working with AWS services. In this article, we'll explore how to set up and interact with DynamoDB using Python, with technical explanations and examples.

Prerequisites

Before diving into DynamoDB, ensure you have the following:

  • An AWS account.
  • Python installed on your local machine.
  • AWS Command Line Interface (CLI) installed and configured with your credentials.
  • The boto3 library installed in your Python environment.

Install boto3 using pip if you haven't already:

bash
pip install boto3

Configuring AWS CLI

Configure your AWS credentials using the AWS CLI. Run:

bash
aws configure

Prompted inputs will include your AWS Access Key and Secret Key, along with the default region and output format. This configuration is crucial for boto3 to authenticate your requests to AWS services.

Creating a DynamoDB Table

To access DynamoDB, you may start by creating a table. Here’s a basic Python script to create a table using boto3:

python
1import boto3
2
3dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
4
5table = dynamodb.create_table(
6    TableName='Movies',
7    KeySchema=[
8        {
9            'AttributeName': 'year',
10            'KeyType': 'HASH'  # Partition key
11        },
12        {
13            'AttributeName': 'title',
14            'KeyType': 'RANGE'  # Sort key
15        }
16    ],
17    AttributeDefinitions=[
18        {
19            'AttributeName': 'year',
20            'AttributeType': 'N'
21        },
22        {
23            'AttributeName': 'title',
24            'AttributeType': 'S'
25        },
26    ],
27    ProvisionedThroughput={
28        'ReadCapacityUnits': 10,
29        'WriteCapacityUnits': 10
30    }
31)
32
33print("Table status:", table.table_status)

Working with Data

Once you have created your table, you can insert, read, update, and delete items.

Inserting Data

Here's how to add an item to your Movies table:

python
1table = dynamodb.Table('Movies')
2
3table.put_item(
4   Item={
5        'year': 2015,
6        'title': 'The Big New Movie',
7        'info': {
8            'actors': ['Actor 1', 'Actor 2'],
9            'rating': 5.5
10        }
11    }
12)

Reading Data

You can retrieve items using the get_item or query methods.

python
1response = table.get_item(
2    Key={
3        'year': 2015,
4        'title': 'The Big New Movie'
5    }
6)
7
8item = response['Item']
9print(item)

Additional Operations

  • Updating Data: Use update_item to modify existing data.
  • Deleting Data: Use delete_item to remove items.

Querying & Scanning

  • Query: Retrieves items based on primary key values.
  • Scan: Retrieves all items in a table, which can be resource-intensive.

Query Example

python
1response = table.query(
2    KeyConditionExpression=Key('year').eq(2015)
3)
4
5items = response['Items']
6for item in items:
7    print(item['title'])

Scan Example

python
1response = table.scan()
2data = response['Items']
3
4while 'LastEvaluatedKey' in response:
5    response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
6    data.extend(response['Items'])
7
8print(data)

Summary

Here’s a summary table highlighting key operations with boto3:

OperationMethodExplanation
Create Tablecreate_tableDefine table schema and capacity.
Insert Itemput_itemAdd a new item to the table.
Read Itemget_itemRetrieve data using primary keys.
Update Itemupdate_itemModify attributes of an item.
Delete Itemdelete_itemRemove an item from the table.
Query DataqueryGet items by primary key.
Scan TablescanRetrieve all items (costly).

Conclusion

In this tutorial, you learned how to perform basic operations with Amazon DynamoDB using the boto3 library in Python. Whether you're managing a small or a large dataset, boto3 provides a convenient interface for interacting with DynamoDB, enabling you to handle your data operations efficiently. Additionally, consider utilizing AWS IAM roles to manage your permissions and access securely.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.