CRUD Operations Using AWS DynamoDB with Flask APIs and Boto3
www.bacancytechnology.com
Introduction
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.
Goal: Using AWS DynamoDB with Flask APIs and Boto3
Before knowing how to implement CRUD operations on DynamoDB using Flask APIs, let’s see the video and know what we will build.
Prerequisites
We assume that you have prior knowledge of the following:
Python3 Programming pip Flask AWS and IAM
To get started with this tutorial, make sure you have the following as well:
DynamoDB local Python IDE
Technologies to use
We will be using the following technologies: Flask Boto3 DynamoDB
Let’s start the implementation of AWS DynamoDB with Flask APIs and Boto3. Here’s my system setup: Ubuntu 20.04 OS Python 3.8+ Postman
Installing Flask and Boto3 using pip
Install the packages to build REST APIs Flask Boto3
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
Create new directory
Create a new directory and navigate to it using the below commands
mkdir mydynamoDBflaskproject cd mydynamoDBflaskproject
Set Up AWS Credentials
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:
// 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.
Configuration Set Up for APIs
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.
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 )
Create a Table using create_table()
As part of the next step, let’s create a function that would create a new table called create_table().
// controller.py 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.
CRUD Operations using AWS DynamoDB with Flask APIs and Boto3
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
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
UPDATE 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
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 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.
Conclusion
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 problemsolving skills.
Thank You
www.bacancytechnology.com