3. In this tutorial, we will build a demo
application together; learn about the Flask
framework, Boto3 library, REST APIs, and
AWS DynamoDB. If you are new at using
AWS DynamoDB with Flask APIs and Boto3,
don’t worry! We are here to help you learn
through this tutorial.
7. Python3 Programming
pip
Flask
AWS and IAM
DynamoDB local
Python
IDE
We assume that you have prior knowledge
of the following:
To get started with this tutorial, make sure
you have the following as well:
9. Flask
Boto3
DynamoDB
Ubuntu 20.04 OS
Python 3.8+
Postman
We will be using the following technologies:
Let’s start the implementation of AWS
DynamoDB with Flask APIs and Boto3.
Here’s my system setup:
11. Flask
Boto3
Install the packages to build REST APIs
An efficient way: Create a requirements.txt
file and list all the packages into it. You can
also declare the versions of the packages
wherever necessary.
flask==1.1.2
boto3==1.17.52
Use the above file to install all the listed
packages with pip.
pip install -r requirements.txt
15. Create a new file named config.py
touch config.py
NOTE– it is advised to use a virtual
environment and perform all the setup and
installation inside it to avoid unnecessary
pollution of the Operating System.
However, it is not a mandatory process but
a healthy practice.
Now, include your AWS credentials in a
python file named config.py:
16. // config.py
AWS_ACCESS_KEY_ID = 'youraccessid'
AWS_SECRET_ACCESS_KEY =
'yoursecretaccesskey'
REGION_NAME = 'yourregionname'
AWS_ACCESS_KEY_ID: AWS access
key associated with an IAM role or user.
AWS_SECRET_ACCESS_KEY: A secret
key associated with the access key. This
is essentially the “password” for the
specified access key.
REGION_NAME: The default region
when creating new connections.
18. Create a new file named “controller.py.”
touch controller.py
NOTE– while executing these commands in
the terminal, make sure you do it inside the
virtual environment named “venv” we
created earlier.
Open the file and paste the following code.
// controller.py
from boto3 import resource
import config
The resource package provides higher-level
object-oriented service access. It provides
better abstraction and makes your code
easier to comprehend.
19. The config package will import all the AWS
configurations that we set in the config.py
file.
Now it’s time to configure settings for the
Movie API
// controller.py
AWS_ACCESS_KEY_ID =
config.AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY =
config.AWS_SECRET_ACCESS_KEY
REGION_NAME = config.REGION_NAME
resource = resource(
'dynamodb',
aws_access_key_id =
AWS_ACCESS_KEY_ID,
aws_secret_access_key =
AWS_SECRET_ACCESS_KEY,
region_name = REGION_NAME
)
21. def create_table_movie():
table = resource.create_table(
TableName = 'Movie', # Name of the
table
KeySchema = [
{
'AttributeName': 'id',
'KeyType' : 'HASH' #RANGE = sort
key, HASH = partition key
}
],
AttributeDefinitions = [
{
'AttributeName': 'id', # Name of the
attribute
'AttributeType': 'N' # N = Number
As part of the next step, let’s create a
function that would create a new table
called create_table().
// controller.py
22. (B= Binary, S = String)
}
],
ProvisionedThroughput={
'ReadCapacityUnits' : 10,
'WriteCapacityUnits': 10
}
)
return table
To access or modify the table’s entries, we
have to get the table using the resource.
MovieTable = resource.Table('Movie')
Once done, let’s get started for CRUD
operations using Flask APIs on DynamoDB.
24. CREATE
Now, let’s add a new entry in the Movie table.
def write_to_movie(id, title, director):
response = MovieTable.put_item(
Item = {
'id' : id,
'title' : title,
'director' : director,
'upvotes' : 0
}
)
return response
25. READ
Read an entry from the Movie table.
ddef read_from_movie(id):
response = MovieTable.get_item(
Key = {
'id' : id
},
AttributesToGet = [
'title,’,’’ 'director'
)
return response
26. def update_in_movie(id, data:dict):
response = MovieTable.update_item(
Key = {
'id': id
},
AttributeUpdates={
'title': {
'Value' : data['title'],
'Action' : 'PUT'
},
'director': {
'Value' : data['director'],
'Action' : 'PUT'
}
},
ReturnValues = "UPDATED_NEW" #
returns the new updated values
UPDATE
Update an entry in the Movie table
using the ‘id’ attribute.
27. ReturnValues = "UPDATED_NEW" #
returns the new updated values
)
return response
Update ‘upvotes’ property for an entry.
def upvote_a_movie(id):
response = MovieTable.update_item(
Key = {
'id': id
},
AttributeUpdates = {
'upvotes': {
'Value' : 1,
'Action' : 'ADD'
}
},
28. ReturnValues = "UPDATED_NEW"
)
response['Attributes']['upvotes'] =
int(response['Attributes']['upvotes'])
return response
DELETE
Delete an entry from the Movie collection.
def delete_from_movie(id):
response = MovieTable.delete_item(
Key = {
'id': id
}
)
return response
29. import controller as dynamodb
@app.route('/')
def root_route():
dynamodb.create_table_movie()
return 'Table created'
@app.route('/movie', methods=['POST'])
def add_movie():
data = request.get_json()
response =
dynamodb.write_to_movie(data['id'],
data['title'], data['director'])
if (response['ResponseMetadata']
Let’s create a linear flask application with
APIs to perform operations on the Movie
collection we will create using our
create_table_movie() function.
// app.py
33. 'msg' : 'Upvote successful',
'response' :
response['ResponseMetadata'],
'Upvotes' : response['Attributes']
['upvotes']
}
return {
'msg' : ‘error occurred',
'response' : response
}
Now run the app.py file by using the
following command inside the virtual
environment
python app.py
34. The entire source code is available here:
flask-dynamoDB-boto3-example. Feel free
to clone the repository and play around
with code.
36. I hope the tutorial for using AWS
DynamoDB with Flask APIs and Boto3 was
helpful, and you have developed your demo
application as well. For more such tutorials,
you can visit the Python tutorials page to
explore basic and advanced knowledge.
In case you need any further guidance or a
helping hand for your Python application
without wasting a second, contact Bacancy
and hire Python developer. We have
dedicated and experienced python
developers who have optimum problem-
solving skills.