Table of Contents
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.
Before knowing how to implement CRUD operations on DynamoDB using Flask APIs, let’s see the video and know what we will build.
We assume that you have prior knowledge of the following:
To get started with this tutorial, make sure you have the following as well:
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:
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
Hire flask developers for your project, and let them help you bring your vision to life with the power of Flask and DynamoDB.
Create a new directory and navigate to it using the below commands
mkdir mydynamoDBflaskproject cd mydynamoDBflaskproject
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:
AWS_ACCESS_KEY_ID = 'youraccessid' AWS_SECRET_ACCESS_KEY = 'yoursecretaccesskey' REGION_NAME = 'yourregionname'
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.
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.
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
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 )
As part of the next step, let’s create a function that would create a new table called create_table().
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 (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.
Supercharge your projects with our elite AWS developers!
Elevate your business to new heights with cutting-edge solutions and unparalleled expertise. Let’s transform your vision into reality— hire AWS developers from us today for a journey of innovation and success!
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
Read an entry from the Movie table.
def read_from_movie(id):
response = MovieTable.get_item(
Key = {
'id' : id
},
AttributesToGet = [
'title,’,’’ 'director'
)
return response
Update an entry in the Movie table using the ‘id’ attribute.
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
)
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'
}
},
ReturnValues = "UPDATED_NEW"
)
response['Attributes']['upvotes'] = int(response['Attributes']['upvotes'])
return response
Delete an entry from the Movie collection.
def delete_from_movie(id):
response = MovieTable.delete_item(
Key = {
'id': id
}
)
return response
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
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']['HTTPStatusCode'] == 200):
return {
'msg': 'Add Movie successful',
}
return {
'msg': 'error occurred',
'response': response
}
@app.route('/movie/', methods=['GET'])
def get_movie(id):
response = dynamodb.read_from_movie(id)
if (response['ResponseMetadata']['HTTPStatusCode'] == 200):
if ('Item' in response):
return { 'Item': response['Item'] }
return { 'msg' : 'Item not found!' }
return {
'msg': 'error occurred',
'response': response
}
@app.route('/movie/', methods=['DELETE'])
def delete_movie(id):
response = dynamodb.delete_from_movie(id)
if (response['ResponseMetadata']['HTTPStatusCode'] == 200):
return {
'msg': 'Delete successful',
}
return {
'msg': 'error occurred',
'response': response
}
@app.route('/movie/', methods=['PUT'])
def update_movie(id):
data = request.get_json()
response = dynamodb.update_in_movie(id, data)
if (response['ResponseMetadata']['HTTPStatusCode'] == 200):
return {
'msg' : update successful',
'response' : response['ResponseMetadata'],
'ModifiedAttributes' : response['Attributes']
}
return {
'msg' : ‘error occurred',
'response' : response
}
@app.route('/upvote/movie/', methods=['POST'])
def upvote_movie(id):
response = dynamodb.upvote_a_movieMovie(id)
if (response['ResponseMetadata']['HTTPStatusCode'] == 200):
return {
'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
The entire source code is available here: flask-dynamoDB-boto3-example. Feel free to clone the repository and play around with code.
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.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.