CRUD operations on DynamoDB with Flask APIs

Sharmila S
featurepreneur
Published in
3 min readJun 19, 2021

Flask with DynamoDB using boto3 module.

Technologies we’ll be using:

  • Flask — Python Web Framework
  • boto3 — Python module with necessary functions to work with AWS services like dynamoDB, S3.
  • DynamoDB — Document based database service by AWS.

Install the dependencies for the project using pip in the terminal.

$ pip install flask$ pip install boto3$ pip install python-decouple
  • Let’s create a python file to contain all our dynamoDB handler functions.
$ touch dynamodb_handler.py
  • In the dynamodb_handler.py file, import the boto3 module.
import boto3
  • Pass the credentials as environment variables

Create a .env file and include all the credentials in key=value format. E.g.,

AWS_ACCESS_KEY_ID='someaccessid'
AWS_SECRET_ACCESS_KEY='somesecretaccesskey'
REGION_NAME='us-west-1'

Now import the credentials to our python file

from decouple import configAWS_ACCESS_KEY_ID     = config("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY")
REGION_NAME = config("REGION_NAME")
  • Set Client and Resource
client = boto3.client(
'dynamodb',
aws_access_key_id = AWS_ACCESS_KEY_ID,
aws_secret_access_key = AWS_SECRET_ACCESS_KEY,
region_name = REGION_NAME,
)
resource = boto3.resource(
'dynamodb',
aws_access_key_id = AWS_ACCESS_KEY_ID,
aws_secret_access_key = AWS_SECRET_ACCESS_KEY,
region_name = REGION_NAME,
)

To create a new table, use create_table()

def CreatATableBook():

client.create_table(
AttributeDefinitions = [ # Name and type of the attributes
{
'AttributeName': 'id', # Name of the attribute
'AttributeType': 'N' # N -> Number (S -> String, B-> Binary)
}
],
TableName = 'Book', # Name of the table
KeySchema = [ # Partition key/sort key attribute
{
'AttributeName': 'id',
'KeyType' : 'HASH'
# 'HASH' -> partition key, 'RANGE' -> sort key
}
],
BillingMode = 'PAY_PER_REQUEST',
Tags = [ # OPTIONAL
{
'Key' : 'test-resource',
'Value': 'dynamodb-test'
}
]
)

In order to access and modify the entries of the table, we have to get the table using the resource.

BookTable = resource.Table('Book')

CREATE

Add a new entry in the Book table.

def addItemToBook(id, title, author):    response = BookTable.put_item(
Item = {
'id' : id,
'title' : title,
'author' : author,
'likes' : 0
}
)
return response

READ

Read an entry from the Book collection.

def GetItemFromBook(id):    response = BookTable.get_item(
Key = {
'id' : id
},
AttributesToGet=[
'title', 'author'
]
)
return response

UPDATE

Update an entry in the Book collection using the ‘id’ attribute.

def UpdateItemInBook(id, data:dict):    response = BookTable.update_item(
Key = {
'id': id
},
AttributeUpdates={
'title': {
'Value' : data['title'],
'Action' : 'PUT' # available options -> DELETE(delete), PUT(set), ADD(increment)
},
'author': {
'Value' : data['author'],
'Action' : 'PUT'
}
},
ReturnValues = "UPDATED_NEW" # returns the new updated values
)
return response

Update (increment) ‘likes’ property for an entry.

def LikeABook(id):    response = BookTable.update_item(
Key = {
'id': id
},
AttributeUpdates = {
'likes': {
'Value' : 1, # Add '1' to the existing value
'Action' : 'ADD'
}
},
ReturnValues = "UPDATED_NEW"
)
# The 'likes' value will be of type Decimal, which should be converted to python int type, to pass the response in json format. response['Attributes']['likes'] = int(response['Attributes']['likes']) return response

DELETE

Delete an entry from the collection

def DeleteAnItemFromBook(id):    response = BookTable.delete_item(
Key = {
'id': id
}
)
return response

Flask APIs to handle dynamoDB operations

Let’s create a simple flask application with APIs to perform operations on our Book table.

Try running the app, using

$ python app.py

Click here to view Boto3 Documentation

Github repo — https://github.com/SharmilaS22/aws-dynamodb-flask

Happy Learning!

--

--

Sharmila S
featurepreneur

Software Engineer | Writes about Full Stack Web Development | 1 X AWS | CKA http://sharmilas.bio.link/