Accessing Amazon DynamoDB using AWS SDK for Python (Boto3)

In this blog, we will see how an item in Amazon DynamoDB can be accessed using AWS CLI and AWS SDK for Python (Boto3).

Amazon DynamoDB is a managed NoSQL database with predictable and consistent performance that cover users from difficulties of manual setup. In the time of traffic, it can scale up automatically and improves the performance with reduced cost. The data objects can be stored in inconsistent schemas, which is why it can handle less structured data more efficiently.

It can also create backup of the data on the cloud for security and safety purposes. DynamoDB allows to set a timestamp for expired data in the table so once it expires, the data is marked to expire. This helps to keep in track of expired data and delete it automatically avoiding manual deletion. The most important feature is to have specific access control that allows table owners to set high level of control over the data in the table.

Amazon DynamoDB can be accessed using the AWS Management Console, the AWS Command Line Interface (AWS CLI), or the DynamoDB API. In this blog, we will see how an item in Amazon DynamoDB can be accessed using AWS CLI and AWS SDK for Python (Boto3).

The package manager for python, pip is required for installing AWS CLI and boto3. Then for installation use the following commands:

  • $pip install awscli
  • $pip install boto3

The configuration of the credentials can be done by providing aws_secret_access_key_id, aws_secret_access_key_id and region details:

  • $aws configure
  • AWS Access Key ID [****************]:
  • AWS Secret Access Key [****************]:
  • Default region name [ap-south-1]:
  • Default output format [json]:

We will see how CRUD operations (Create, Read/Write, Update, Delete) works on Amazon DynamoDB.

  • Creating Table in DynamoDB:
    • import boto3
    • def create table():
    •    dynamodb = boto3.resource('dynamodb')
    •    table = dynamodb.create_table(
    •            TableName='Rainbow',
    •            KeySchema=[
    •              {
    •               'AttributeName': 'Table', 
    •               'KeyType': 'HASH'
    •              },
    •              {
    •               'AttributeName': 'Category'
    •               'KeyType': 'RANGE'
    •              }
    •             ], 
    •             AttributeDefinitions=[
    •              {
    •               'AttributeName': 'vibgyor', 
    •               'AttributeType': 'S'
    •              },
    •              {
    •               'AttributeName': 'colours',
    •               'AttributeType': 'S'
    •              },
    •             ],
    •             ProvisionedThroughput={
    •              'ReadCapacityUnits': 1,
    •              'WriteCapacityUnits': 1
    •             }
    •            )
    •            return table.table_status

Amazon DynamoDB shows the status of creation of the table and only when the status is active, the other operations can be performed.

  • Writing to Table in DynamoDB:
    • def write_to_table():
    •       table = dynamodb.Table('Rainbow')
    •       response = table.put_item(
    •     Item = {
    •           'Table': 'vibgyor',
    •           'Category':'colours'
    •           ‘V’: ‘violet',
    •           'I': 'indigo',
    •           'B': 'blue',
    •           'G': 'green',
    •           'Y': 'yellow',
    •           ‘O’: ‘orange',
    •           'R': 'red'
    •            }
    •       )
    • return response

With the Partition key and the Sort key (which is mandatory for accessing the table), the items can be added to the table.

  • Reading an item from DynamoDB Table:
    • def get_data():
    •     table = dynamodb.Table('Rainbow')
    •     response = table.get_item(
    •     Key = {
    •            'Table': 'vibgyor',
    •            'Category':'colours'
    •            }
    •          )
    •         return response['Item']

To get the data from the table by calling the table with the keys – Partition key and Sort key, returns the items in the table.

  • Updating an item in DynamoDB Table:
    • def update_data():
    •       table = dynamodb.Table('Rainbow')
    •       response = table.update_item(
    •        Key = {
    •              'Table': 'vibgyor',
    •              'Category':'colours'
    •              },
    •       UpdateExpression='SET B = :values',
    •       ExpressionAttributeValues={
    •        ':values': 'black'
    •       }
    •    )
    •       return response['Item']

Here, the item B’ s value is being updated to black which was blue earlier.

  • Deletion an item in DynamoDB Table:
    • def delete_data():
    •       table = dynamodb.Table('mytable')
    •       response = table.delete_item(
    •        Key = {
    •              'Table': 'vibgyor',
    •              'Category':'colours'
    •               }
    •          )
    •         return response['Item']

If you have any questions or suggestions, please reach out to us at contactus@1cloudhub.com

Written by :  Sowmya  &   Umashankar N

Updated on March 10, 2021

Sharing is caring!

Tags:

In Blog
Subscribe to our Newsletter1CloudHub