Skip to content

Storage KeyValue DynamoDB Python

Braden Hitchcock edited this page Jan 30, 2020 · 7 revisions

Python SDK for AWS DynamoDB

The Python SDK for interacting with DynamoDB is available automatically in your deployment. The primary SDK for Python is the Boto 3 AWS SDK. To use it, simply add an import statement at the top of your compute instance code:

import boto3

You can grab an instance of the DynamoDB SDK client using the resource method. You can access a specific table by using the Table method on the SDK client instance. The table name is provided by the Scootr runtime library in the environment as the name of the reference connection our compute instance to the storage instance. In the example below, we are assuming we have named our reference StorageReferenceName:

import boto3
import os

client = boto3.resource('dynamodb')
table = client.Table(os.getenv('StorageReferenceName'))

Below are some examples of using the Python SDK to interact with DynamoDB. If you are interested, there is also a more comprehensive documentation of the API online.

An important thing to take note of is that the Boto 3 SDK doesn't provide much documentation on error handling. However, you can catch exceptions of the type ClientError that result when a request fails by importing the botocore.exceptions.ClientError type:

from botocore.exceptions import ClientError

This ClientError type will be used in the examples below.

Note: Some data types in Python are not support natively by the SDK. Check out the documentation for a list of supported types

Creating An Item

You can add a new item to DynamoDB using the put_item method:

# from random import random
# from math import floor

# ...

# Generate a (non-secure) random ID for our new item
id = floor(random() * 10000)

# Create the item
item = {
    "id": id,
    "name": "Alice",
    "username": "alice",
    "email": "alice@example.com"
}

try:
    # Add the item to the database
    table.put_item(
        Item=item
    )
    print("Successfully created item")
except ClientError as e:
    print(e)

Getting An Item

You can get an existing item from DynamoDB using the get_item method:

# Assume the value generated in our "create" example above is 1234.
id = 1234

try:
    # Get the item with the above ID from the database.
    response = table.get_item(
        Key={
            "id": id
        }
    )
    print(response["Item"])
except ClientError as e:
    print(e)

The resulting item will exist on the Item key of the response.

Getting All Items

You can get all items in the DynamoDB table using the scan method:

try:
    # Scan the database to get a list of all items.
    response = table.scan()
    print(*response["Items"], sep="\n")
except ClientError as e:
    print(e)

The resulting items will exist on the Items key of the response.

Updating An Item

You can update a single existing item in DynamoDB using the update_item method:

id = 1234
updated_username = "alice121"
updated_email = "alice.dev@example.com

try:
    # Update the item with the id above using an update expression in DynamoDB.
    table.update_item(
        Key={
            "id": id
        },
        UpdateExpression='set username = :u, email = :e',
        ExpressionAttributeValues={
            ":u": updated_username,
            ":e": updated_email
        }
    )
    print("Successfully update the item with ID %d" % id)
except ClientError as e:
    print(e)

Deleting An Item

You can delete an existing item in DynamoDB using the delete_item method:

id = 1234

try:
    # Delete the item from the database.
    table.delete_item(
        Key={
            "id": id
        }
    )
    print("Successfully deleted item with ID %d" % id)
except ClientError as e:
    print(e)

Clone this wiki locally