Creating DynamoDB Table using Boto3

lasanthasilva

Lasantha Sanjeewa Silva

Posted on February 26, 2023

Creating DynamoDB Table using Boto3

Amazon DynamoDB is a fully managed NoSQL database service offered by Amazon Web Services (AWS). It is a fast, flexible, and scalable database service that allows users to store and retrieve data in a highly available and durable manner.

Boto3 is a Python library that provides an easy-to-use interface for interacting with various AWS services, allowing developers to automate tasks and integrate AWS services into their Python applications.

Now we going to setup step by step.

Image description

Step 1 - Go to the AWS management console and create a Cloud9 environment and create one empty folder. You can also use this GitHub repo to clone files.

Git Repo

Step 2 - Create a new file called BooksTableCreate.py and paste this content to create DynamoDB Table. After that Run the python BooksTableCreate.py command to run this file.

BooksTableCreate.py



import boto3

dynamodb = boto3.resource('dynamodb', region_name='us-east-2')

table = dynamodb.create_table(
    TableName='Books',
    KeySchema=[
        {
            'AttributeName': 'year',
            'KeyType': 'HASH'  #Partition_key
        },
        {
            'AttributeName': 'title',
            'KeyType': 'RANGE'  #Sort_key
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'year',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'title',
            'AttributeType': 'S'
        },

    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10
    }
)

print("Table status:", table.table_status)


Enter fullscreen mode Exit fullscreen mode

Create Table

After that go to the AWS console and search DynamoDB. After that in DynamoDB Dashboard you can see your DyanmoDB tables are created.
Table Create Success

Step 3 - Create a file called bookdata.json and paste the following content.

bookdata.json



[
    {
        "year": 2023,
        "title": "DevSecOps",
        "info": {
            "release_date": "2023-01-03",
            "rank": 2,
            "authors": [
                "Daniel Bruhl",
                "Chris Hemsworth",
                "Olivia Wilde"
            ]
        }
    },
    {
        "year": 2022,
        "title": "IaaS Tools",
        "info": {
            "release_date": "2022-12-01",
            "rank": 3,
            "authors": [
                "Daniel Bruhl",
                "Chris Hemsworth",
                "Olivia Wilde"
            ]
        }
    }

]


Enter fullscreen mode Exit fullscreen mode

After that create the BooksLoadData.py file and paste the following content. Finally, run the python BooksLoadData.py command for execution.

BooksLoadData.py



import boto3
import json
import decimal

dynamodb = boto3.resource('dynamodb', region_name='us-east-2')

table = dynamodb.Table('Books')

with open("bookdata.json") as json_file:
    books = json.load(json_file, parse_float = decimal.Decimal)
    for book in books:
        year = int(book['year'])
        title = book['title']
        info = book['info']

        print("Add Book:", year, title)

        table.put_item(
           Item={
               'year': year,
               'title': title,
               'info': info,
            }
        )



Enter fullscreen mode Exit fullscreen mode

Load data

Finally, go to the AWS management console and in the DynamoDB dashboard you can see your table added the following values.

DynamoDb Dashboard

Step 4 - Next, add new content to the table. Create an AddNewBook.py file and add the following content. After that run the python AddNewBook.py command.

AddNewBook.py



import boto3
import json
import decimal

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if abs(o) % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='us-east-2')

table = dynamodb.Table('Books')

title = "Docker"
year = 2019

response = table.put_item(
   Item={
        'year': year,
        'title': title,
        'info': {
            "release_date": "2029-12-01",
            "rank": 5,
            "authors": "Daniel Bruhl"
        }
    }
)

print("Add New Book:")
print(json.dumps(response, indent=4, cls=DecimalEncoder))


Enter fullscreen mode Exit fullscreen mode

Add New Values

Next, go to the AWS management console and in the DynamoDB dashboard you can see your latest added value in your dashboard.

AWS DynamoDB Dashboard

Step 5 - Next, get values from tables. Next, create a ReadBook.py file and add the following values. Run the python ReadBook.py command.

ReadBook.py



import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource("dynamodb", region_name='us-east-2')

table = dynamodb.Table('Books')

title = "DevSecOps"
year = 2023

try:
    response = table.get_item(
        Key={
            'year': year,
            'title': title
        }
    )
except ClientError as e:
    print(e.response['Error']['Message'])
else:
    item = response['Item']
    print("GetBook")
    print(json.dumps(item, indent=4, cls=DecimalEncoder))


Enter fullscreen mode Exit fullscreen mode

Get values

Step 6 - Next, query the values. Create BooksQuery.py and add the following values. Run the python BooksQuery.py command.

BooksQuery.py



import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr


class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='us-east-2')

table = dynamodb.Table('Books')

print("Books From 2023")

response = table.query(
    KeyConditionExpression=Key('year').eq(2023)
)

for i in response['Items']:
    print(i['year'], ":", i['title'])


Enter fullscreen mode Exit fullscreen mode

Run Query

Step 7 - Finally, delete the DyanamoDB table. Because it helps to save our costs. As well as delete Cloud9 Environment. Create DeleteTable.py and add the following values. Next, run the python DeleteTable.py command.

DeleteTable.py



import boto3
dynamodb = boto3.resource('dynamodb', region_name='us-east-2')
table = dynamodb.Table('Books')
table.delete()


Enter fullscreen mode Exit fullscreen mode

Delete DynamoDB Tables

Thanks for reading the Article.

💖 💪 🙅 🚩
lasanthasilva
Lasantha Sanjeewa Silva

Posted on February 26, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related