Creating DynamoDB Table using Boto3
Tags: aws, python, boto3, dynamodb
Published: 2023-02-26 20:01:04

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jl80dd0wjwd6m4148xbw.gif)

**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](https://github.com/sanju2/30_DaysOfAWS/tree/main/DynamoDB_Boto3) 

**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)
```

![Create Table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/61zowxzildl2btr3pmt1.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtw3t2bnlfa8tw3d4944.png)

**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"
            ]
        }
    }
    
]
```

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,
            }
        )

```
![Load data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/znlua97h5jxunpvy9gmx.png)

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

![DynamoDb Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c620uwxbuz44aae4ivnt.png)

**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))
```

![Add New Values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzgd8yv7stqnx8e8emf2.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6fiw8tgqvwd47kd5vpc7.png)

**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))
```

![Get values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4xw3afcbsoaazt8zb9dd.png)

**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'])
```

![Run Query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y9u1w9q9wblechdnmjqg.png)

**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()
```

![Delete DynamoDB Tables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pdpikhkxgwdqwlnavkhg.png)

Thanks for reading the Article.