SlideShare a Scribd company logo
1 of 37
Download to read offline
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
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:
Technologies
to use
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:
Installing
Flask and
Boto3 using
pip
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
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()
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
(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
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.
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
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
['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 problem-
solving skills.
Thank You
www.bacancytechnology.com

More Related Content

What's hot

Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Fabien Potencier
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objectswebhostingguy
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappersPositive Hack Days
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO ObjectsAJINKYA N
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design PrinciplesJon Kruger
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkMichael Peacock
 
PHP And Web Services: Perfect Partners
PHP And Web Services: Perfect PartnersPHP And Web Services: Perfect Partners
PHP And Web Services: Perfect PartnersLorna Mitchell
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Kris Wallsmith
 
Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservicesMarcos Lin
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 
The symfony platform: Create your very own framework (PHP Quebec 2008)
The symfony platform: Create your very own framework (PHP Quebec 2008)The symfony platform: Create your very own framework (PHP Quebec 2008)
The symfony platform: Create your very own framework (PHP Quebec 2008)Fabien Potencier
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用Felinx Lee
 

What's hot (20)

Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
 
New in php 7
New in php 7New in php 7
New in php 7
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO Objects
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
 
PHP And Web Services: Perfect Partners
PHP And Web Services: Perfect PartnersPHP And Web Services: Perfect Partners
PHP And Web Services: Perfect Partners
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
 
Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservices
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
The symfony platform: Create your very own framework (PHP Quebec 2008)
The symfony platform: Create your very own framework (PHP Quebec 2008)The symfony platform: Create your very own framework (PHP Quebec 2008)
The symfony platform: Create your very own framework (PHP Quebec 2008)
 
Intro to PHP
Intro to PHPIntro to PHP
Intro to PHP
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
 

Similar to Crud operations using aws dynamo db with flask ap is and boto3

Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexyananelson
 
-Kotlin_Camp_Unit2.pptx
-Kotlin_Camp_Unit2.pptx-Kotlin_Camp_Unit2.pptx
-Kotlin_Camp_Unit2.pptxRishiGandhi19
 
Download and restrict video files in android app
Download and restrict video files in android appDownload and restrict video files in android app
Download and restrict video files in android appKaty Slemon
 
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...Amazon Web Services
 
What Is AWS Elastic Kubernetes Service
 What Is AWS Elastic Kubernetes Service What Is AWS Elastic Kubernetes Service
What Is AWS Elastic Kubernetes ServiceAMELIAOLIVIA2
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbsAWS Chicago
 
Flutter movie apps tutor
Flutter movie apps tutorFlutter movie apps tutor
Flutter movie apps tutorHerry Prasetyo
 
Firebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopFirebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopPeter Friese
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorialKaty Slemon
 
Silicon Valley Code Camp 2019 - Reaching the Cloud Native World
Silicon Valley Code Camp 2019 - Reaching the Cloud Native WorldSilicon Valley Code Camp 2019 - Reaching the Cloud Native World
Silicon Valley Code Camp 2019 - Reaching the Cloud Native WorldChris Bailey
 
Replacing ActiveRecord callbacks with Pub/Sub
Replacing ActiveRecord callbacks with Pub/SubReplacing ActiveRecord callbacks with Pub/Sub
Replacing ActiveRecord callbacks with Pub/Subnburkley
 
Viktor Tsykunov "Microsoft AI platform for every Developer"
Viktor Tsykunov "Microsoft AI platform for every Developer"Viktor Tsykunov "Microsoft AI platform for every Developer"
Viktor Tsykunov "Microsoft AI platform for every Developer"Lviv Startup Club
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flaskJeetendra singh
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In PyEric ShangKuan
 
From System Engineer to Gopher
From System Engineer to GopherFrom System Engineer to Gopher
From System Engineer to GopherI-Fan Wang
 

Similar to Crud operations using aws dynamo db with flask ap is and boto3 (20)

Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexy
 
-Kotlin_Camp_Unit2.pptx
-Kotlin_Camp_Unit2.pptx-Kotlin_Camp_Unit2.pptx
-Kotlin_Camp_Unit2.pptx
 
-Kotlin Camp Unit2.pptx
-Kotlin Camp Unit2.pptx-Kotlin Camp Unit2.pptx
-Kotlin Camp Unit2.pptx
 
Download and restrict video files in android app
Download and restrict video files in android appDownload and restrict video files in android app
Download and restrict video files in android app
 
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
 
What Is AWS Elastic Kubernetes Service
 What Is AWS Elastic Kubernetes Service What Is AWS Elastic Kubernetes Service
What Is AWS Elastic Kubernetes Service
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 
Python3 (boto3) for aws
Python3 (boto3) for awsPython3 (boto3) for aws
Python3 (boto3) for aws
 
Flutter movie apps tutor
Flutter movie apps tutorFlutter movie apps tutor
Flutter movie apps tutor
 
Firebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopFirebase & SwiftUI Workshop
Firebase & SwiftUI Workshop
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
 
Silicon Valley Code Camp 2019 - Reaching the Cloud Native World
Silicon Valley Code Camp 2019 - Reaching the Cloud Native WorldSilicon Valley Code Camp 2019 - Reaching the Cloud Native World
Silicon Valley Code Camp 2019 - Reaching the Cloud Native World
 
Replacing ActiveRecord callbacks with Pub/Sub
Replacing ActiveRecord callbacks with Pub/SubReplacing ActiveRecord callbacks with Pub/Sub
Replacing ActiveRecord callbacks with Pub/Sub
 
Viktor Tsykunov "Microsoft AI platform for every Developer"
Viktor Tsykunov "Microsoft AI platform for every Developer"Viktor Tsykunov "Microsoft AI platform for every Developer"
Viktor Tsykunov "Microsoft AI platform for every Developer"
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
ALL NEW OOP 2014
ALL NEW OOP 2014ALL NEW OOP 2014
ALL NEW OOP 2014
 
Code Igniter 2
Code Igniter 2Code Igniter 2
Code Igniter 2
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
 
From System Engineer to Gopher
From System Engineer to GopherFrom System Engineer to Gopher
From System Engineer to Gopher
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfKaty Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfKaty Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfKaty Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfKaty Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfKaty Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfKaty Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfKaty Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfKaty Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfKaty Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfKaty Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfKaty Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfKaty Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfKaty Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfKaty Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfKaty Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfKaty Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfKaty Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfKaty Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfKaty Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfKaty Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Crud operations using aws dynamo db with flask ap is and boto3

  • 1. CRUD Operations Using AWS DynamoDB with Flask APIs and Boto3 www.bacancytechnology.com
  • 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.
  • 5. Before knowing how to implement CRUD operations on DynamoDB using Flask APIs, let’s see the video and know what we will build.
  • 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
  • 13. Create a new directory and navigate to it using the below commands mkdir mydynamoDBflaskproject cd mydynamoDBflaskproject
  • 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
  • 30. ['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 }
  • 31. @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']
  • 32. ['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 {
  • 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.