SlideShare a Scribd company logo
2
About this Presetation
• This guide will walk you through building a Restful APi with Flask . At
the end, you'll build a simple Crud APIs. The API will have endpoints
that can be used to add user, view users, update user, delete user &
view user.
Most read
11
Create a Api.py with following code
//code
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
//code
Description : On this part we import all module that needed by our application.
We import Flask to create instance of web application, request to get request
data, jsonify to turns the JSON output into a Response object with the
application/json mimetype, SQAlchemy from flask_sqlalchemy to accessing
database, and Marshmallow from flask_marshmallow to serialized object.
Most read
20
Before Running Actions Now
• enter into python interactive shell using following command in your
terminal:
> python
• import db object and generate SQLite database
Use following code in python interactive shell
> from api import db
> db.create_all()
Api.sqlite will be generated inside your project folder
Most read
Build Restful APIs with
Python and Flask
Presented by : Jeetendra Singh
About this Presetation
• This guide will walk you through building a Restful APi with Flask . At
the end, you'll build a simple Crud APIs. The API will have endpoints
that can be used to add user, view users, update user, delete user &
view user.
At the end , following endpints will be available:
• GET - /user => Retrieve all users
• POST - /user - Add a new user
• GET - /user/<id> - get single user by id
• PUT - /user/<id> - Update a user
• DELETE - /user/<id> - Delete a user
Install Python
Debian or Ubuntu
> sudo apt install python3
Fedora
> sudo dnf install python3
Opensuse
> sudo zypper install python3
Windows:
Download latest python from python.org and install it
Verify Version
> python3 --version
it will show version like : Python 3.6.1
Install virtualenv
virtualenv is a virtual Python environment builder. It helps a user to
create multiple Python environments side-by-side. Thereby, it can avoid
compatibility issues between the different versions of the libraries.
The following command installs virtualenv
pip install virtualenv
or
Sudo apt-get install virtualenv
Create and Run Virtual Env
• Once installed, new virtual environment is created in a folder.
>mkdir newproj
>cd newproj
>virtualenv venv
• To activate corresponding environment, on Linux/OS X, use the following −
> venv/bin/activate
• On Windows, following can be used
> venvscriptsactivate
Install Flask
> pip install Flask
# pip is a package manager in python, it will available bydefault once
you install python
“Hello World” In Flask
• create a file index.py with following code:
> python index.py
now run on http://localhost:5000 (5000 is default port you may change
it)
Installing flask-sqlalchemy and flask-marshmallow
• SQLAlchemy is python SQL toolkit and ORM that gives developer the
full power and flexibility of SQL. Where flask-sqlalchemy is flask
extension that adds support for SQLAlchemy to flask
application(http://flask-sqlalchemy.pocoo.org/2.1/).
• In other hand flask-marshmallow is flask extension to integrate flask
with marshmallow(an object serialization/deserialization library). In
this presentation we use flask-marshmallow to rendered json
response
Turn next to install above
Installation
• $ pip install flask_sqlalchemy
• $ pip install flask_marshmallow
• $ pip install marshmallow-sqlalchemy
Create a Api.py with following code
//code
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
//code
Description : On this part we import all module that needed by our application.
We import Flask to create instance of web application, request to get request
data, jsonify to turns the JSON output into a Response object with the
application/json mimetype, SQAlchemy from flask_sqlalchemy to accessing
database, and Marshmallow from flask_marshmallow to serialized object.
CreateInstance & Set Sqlite Path and flask object
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,
'api.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)
Create a app instance and set sqlite path in app config,after it binding SQLAlchemy
and Marshmallow into our flask application.
Declare Model Class and constructor
//code
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
//code
Create a Response Schema
//code
class UserSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('id','username', 'email')
user_schema = UserSchema()
users_schema = UserSchema(many=True)
//code
//This part defined structure of response of our endpoint. We want that all of our endpoint will have JSON
response. Here we define that our JSON response will have 3 keys(id, username, and email). Also we defined
user_schema as instance of UserSchema, and user_schemas as instances of list of UserSchema.
Create a New User Api
# endpoint to create new user
//code
@app.route("/user", methods=["POST"])
def add_user():
username = request.json['username']
email = request.json['email']
new_user = User(username, email)
db.session.add(new_user)
db.session.commit()
return user_schema.jsonify(new_user)
//code
On this part we define endpoint to create new user. First we set the route to “/user” and set HTTP methods to POST. After set the route
and methods we define function that will executed if we access this endpoint. On this function first we get username and email from
request data. After that we create new user using data from request data. Last we add new user to data base and show new user in JSON
form as response.
Show All users Api
# endpoint to show all users
//code
@app.route("/user", methods=["GET"])
def get_user():
all_users = User.query.all()
result = users_schema.dump(all_users)
return jsonify(result.data)
//code
//On this part we define endpoint to get list of all users and show the result as
JSON response.
View user Api
# endpoint to get user detail by id
//code
@app.route("/user/<id>", methods=["GET"])
def user_detail(id):
user = User.query.get(id)
return user_schema.jsonify(user)
//code
//on this part we define endpoint to get user data, but instead of get all the
user here we just get data from one user based on id. If you look carefully at the
route, you can see different pattern on the route of this endpoint. Patern like
“<id>” is parameter, so you can change it with everything you want. This
parameter should put on function parameter(in this case def user_detail(id)) so
we can get this parameter value inside function.
Update User Api
# endpoint to update user
//code
@app.route("/user/<id>", methods=["PUT"])
def user_update(id):
user = User.query.get(id)
username = request.json['username']
email = request.json['email']
user.email = email
user.username = username
db.session.commit()
return user_schema.jsonify(user)
//code
we define endpoint to update user. First we call user that related with given id on parameter. Then we update username and email value
of this user with value from request data using put method.
Delete user Api
# endpoint to delete user
//code
@app.route("/user/<id>", methods=["DELETE"])
def user_delete(id):
user = User.query.get(id)
db.session.delete(user)
db.session.commit()
return user_schema.jsonify(user)
//code
#endpoint to delete user. First we call user that related with given id on
parameter. Then we delete it.
Before Running Actions Now
• enter into python interactive shell using following command in your
terminal:
> python
• import db object and generate SQLite database
Use following code in python interactive shell
> from api import db
> db.create_all()
Api.sqlite will be generated inside your project folder
Run Application
> python crud.py
Now apis are in action , try via postman
Screenshot Attached in Next Slide
Build restful ap is with python and flask
Thanks
• Thanks to Bear With Me

More Related Content

What's hot (20)

Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
Larry Cai
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flask
juzten
 
Python Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIPython Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CI
Bruno Rocha
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talkKyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
Alexey Popravka
 
Flask SQLAlchemy
Flask SQLAlchemy Flask SQLAlchemy
Flask SQLAlchemy
Eueung Mulyana
 
Flask vs. Django
Flask vs. DjangoFlask vs. Django
Flask vs. Django
Rachel Sanders
 
Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010
Binh Nguyen
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
Sudip Simkhada
 
170517 damien gérard framework facebook
170517 damien gérard   framework facebook170517 damien gérard   framework facebook
170517 damien gérard framework facebook
Geeks Anonymes
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTP
Mykhailo Kolesnyk
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
Zend by Rogue Wave Software
 
2 introduction-php-mvc-cakephp-m2-installation-slides
2 introduction-php-mvc-cakephp-m2-installation-slides2 introduction-php-mvc-cakephp-m2-installation-slides
2 introduction-php-mvc-cakephp-m2-installation-slides
MasterCode.vn
 
4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides
MasterCode.vn
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
Christopher Pecoraro
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
Brendan Sera-Shriar
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
Samantha Geitz
 
CakePHP
CakePHPCakePHP
CakePHP
Walther Lalk
 
Resting with OroCRM Webinar
Resting with OroCRM WebinarResting with OroCRM Webinar
Resting with OroCRM Webinar
Oro Inc.
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
Larry Cai
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flask
juzten
 
Python Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIPython Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CI
Bruno Rocha
 
Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010
Binh Nguyen
 
170517 damien gérard framework facebook
170517 damien gérard   framework facebook170517 damien gérard   framework facebook
170517 damien gérard framework facebook
Geeks Anonymes
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTP
Mykhailo Kolesnyk
 
2 introduction-php-mvc-cakephp-m2-installation-slides
2 introduction-php-mvc-cakephp-m2-installation-slides2 introduction-php-mvc-cakephp-m2-installation-slides
2 introduction-php-mvc-cakephp-m2-installation-slides
MasterCode.vn
 
4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides
MasterCode.vn
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
Christopher Pecoraro
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
Samantha Geitz
 
Resting with OroCRM Webinar
Resting with OroCRM WebinarResting with OroCRM Webinar
Resting with OroCRM Webinar
Oro Inc.
 

Similar to Build restful ap is with python and flask (20)

SW Security Lec4 Securing architecture.pptx
SW Security Lec4 Securing architecture.pptxSW Security Lec4 Securing architecture.pptx
SW Security Lec4 Securing architecture.pptx
KhalidShawky1
 
FastAPI - Rest Architecture - in english.pdf
FastAPI - Rest Architecture - in english.pdfFastAPI - Rest Architecture - in english.pdf
FastAPI - Rest Architecture - in english.pdf
inigraha
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
Flask-Python
Flask-PythonFlask-Python
Flask-Python
Triloki Gupta
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
Katy Slemon
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
postrational
 
Google app-engine-with-python
Google app-engine-with-pythonGoogle app-engine-with-python
Google app-engine-with-python
Deepak Garg
 
Flask Application ppt to understand the flask
Flask Application ppt to understand the flaskFlask Application ppt to understand the flask
Flask Application ppt to understand the flask
vijoho5545
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
Christopher Foresman
 
Enterprise-Ready FastAPI: Beyond the Basics
Enterprise-Ready FastAPI: Beyond the BasicsEnterprise-Ready FastAPI: Beyond the Basics
Enterprise-Ready FastAPI: Beyond the Basics
Alexander Ptakhin
 
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkEasy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Inexture Solutions
 
Flask & Flask-restx
Flask & Flask-restxFlask & Flask-restx
Flask & Flask-restx
ammaraslam18
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
Gaurav Bhardwaj
 
Introduction to App Engine Development
Introduction to App Engine DevelopmentIntroduction to App Engine Development
Introduction to App Engine Development
Ron Reiter
 
Flask docs
Flask docsFlask docs
Flask docs
Kunal Sangwan
 
Web Dev 21-01-2024.pptx
Web Dev 21-01-2024.pptxWeb Dev 21-01-2024.pptx
Web Dev 21-01-2024.pptx
PARDHIVANNABATTULA
 
Webapp2 2.2
Webapp2 2.2Webapp2 2.2
Webapp2 2.2
Sergi Duró
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with Flask
Make School
 
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Akira Tsuruda
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
DEVCON
 
SW Security Lec4 Securing architecture.pptx
SW Security Lec4 Securing architecture.pptxSW Security Lec4 Securing architecture.pptx
SW Security Lec4 Securing architecture.pptx
KhalidShawky1
 
FastAPI - Rest Architecture - in english.pdf
FastAPI - Rest Architecture - in english.pdfFastAPI - Rest Architecture - in english.pdf
FastAPI - Rest Architecture - in english.pdf
inigraha
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
Katy Slemon
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
postrational
 
Google app-engine-with-python
Google app-engine-with-pythonGoogle app-engine-with-python
Google app-engine-with-python
Deepak Garg
 
Flask Application ppt to understand the flask
Flask Application ppt to understand the flaskFlask Application ppt to understand the flask
Flask Application ppt to understand the flask
vijoho5545
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
Christopher Foresman
 
Enterprise-Ready FastAPI: Beyond the Basics
Enterprise-Ready FastAPI: Beyond the BasicsEnterprise-Ready FastAPI: Beyond the Basics
Enterprise-Ready FastAPI: Beyond the Basics
Alexander Ptakhin
 
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkEasy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Inexture Solutions
 
Flask & Flask-restx
Flask & Flask-restxFlask & Flask-restx
Flask & Flask-restx
ammaraslam18
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
Gaurav Bhardwaj
 
Introduction to App Engine Development
Introduction to App Engine DevelopmentIntroduction to App Engine Development
Introduction to App Engine Development
Ron Reiter
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with Flask
Make School
 
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Akira Tsuruda
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
DEVCON
 
Ad

Recently uploaded (20)

Video Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptxVideo Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptx
HadiBadri1
 
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 / HIFLUX Co., Ltd.
 
Air Filter Flat Sheet Media-Catalouge-Final.pdf
Air Filter Flat Sheet Media-Catalouge-Final.pdfAir Filter Flat Sheet Media-Catalouge-Final.pdf
Air Filter Flat Sheet Media-Catalouge-Final.pdf
FILTRATION ENGINEERING & CUNSULTANT
 
Influence line diagram for truss in a robust
Influence line diagram for truss in a robustInfluence line diagram for truss in a robust
Influence line diagram for truss in a robust
ParthaSengupta26
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha TasnuvaSoftware Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
sebastianku31
 
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra OpticaPruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
OmarAlfredoDelCastil
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDINGMODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning ModelEnhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
IRJET Journal
 
fy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
fy06_46f6-ht30_22_oil_gas_industry_guidelines.pptfy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
fy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
sukarnoamin
 
ISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdf
ISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdfISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdf
ISO 4548-7 Filter Vibration Fatigue Test Rig Catalogue.pdf
FILTRATION ENGINEERING & CUNSULTANT
 
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
ManiMaran230751
 
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCHUNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
Sridhar191373
 
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDINGMODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...
cyhuutjdoazdwrnubt
 
Fresh concrete Workability Measurement
Fresh concrete  Workability  MeasurementFresh concrete  Workability  Measurement
Fresh concrete Workability Measurement
SasiVarman5
 
[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)
[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)
[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)
하이플럭스 / HIFLUX Co., Ltd.
 
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete ColumnsAxial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Journal of Soft Computing in Civil Engineering
 
Video Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptxVideo Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptx
HadiBadri1
 
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 락피팅 카달로그 2025 (Lok Fitting Catalog 2025)
하이플럭스 / HIFLUX Co., Ltd.
 
Influence line diagram for truss in a robust
Influence line diagram for truss in a robustInfluence line diagram for truss in a robust
Influence line diagram for truss in a robust
ParthaSengupta26
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha TasnuvaSoftware Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
May 2025: Top 10 Cited Articles in Software Engineering & Applications Intern...
sebastianku31
 
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra OpticaPruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
OmarAlfredoDelCastil
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDINGMODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning ModelEnhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
Enhanced heart disease prediction using SKNDGR ensemble Machine Learning Model
IRJET Journal
 
fy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
fy06_46f6-ht30_22_oil_gas_industry_guidelines.pptfy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
fy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
sukarnoamin
 
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
ManiMaran230751
 
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCHUNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
UNIT-4-PPT UNIT COMMITMENT AND ECONOMIC DISPATCH
Sridhar191373
 
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDINGMODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...
cyhuutjdoazdwrnubt
 
Fresh concrete Workability Measurement
Fresh concrete  Workability  MeasurementFresh concrete  Workability  Measurement
Fresh concrete Workability Measurement
SasiVarman5
 
Ad

Build restful ap is with python and flask

  • 1. Build Restful APIs with Python and Flask Presented by : Jeetendra Singh
  • 2. About this Presetation • This guide will walk you through building a Restful APi with Flask . At the end, you'll build a simple Crud APIs. The API will have endpoints that can be used to add user, view users, update user, delete user & view user.
  • 3. At the end , following endpints will be available: • GET - /user => Retrieve all users • POST - /user - Add a new user • GET - /user/<id> - get single user by id • PUT - /user/<id> - Update a user • DELETE - /user/<id> - Delete a user
  • 4. Install Python Debian or Ubuntu > sudo apt install python3 Fedora > sudo dnf install python3 Opensuse > sudo zypper install python3 Windows: Download latest python from python.org and install it Verify Version > python3 --version it will show version like : Python 3.6.1
  • 5. Install virtualenv virtualenv is a virtual Python environment builder. It helps a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries. The following command installs virtualenv pip install virtualenv or Sudo apt-get install virtualenv
  • 6. Create and Run Virtual Env • Once installed, new virtual environment is created in a folder. >mkdir newproj >cd newproj >virtualenv venv • To activate corresponding environment, on Linux/OS X, use the following − > venv/bin/activate • On Windows, following can be used > venvscriptsactivate
  • 7. Install Flask > pip install Flask # pip is a package manager in python, it will available bydefault once you install python
  • 8. “Hello World” In Flask • create a file index.py with following code: > python index.py now run on http://localhost:5000 (5000 is default port you may change it)
  • 9. Installing flask-sqlalchemy and flask-marshmallow • SQLAlchemy is python SQL toolkit and ORM that gives developer the full power and flexibility of SQL. Where flask-sqlalchemy is flask extension that adds support for SQLAlchemy to flask application(http://flask-sqlalchemy.pocoo.org/2.1/). • In other hand flask-marshmallow is flask extension to integrate flask with marshmallow(an object serialization/deserialization library). In this presentation we use flask-marshmallow to rendered json response Turn next to install above
  • 10. Installation • $ pip install flask_sqlalchemy • $ pip install flask_marshmallow • $ pip install marshmallow-sqlalchemy
  • 11. Create a Api.py with following code //code from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow import os //code Description : On this part we import all module that needed by our application. We import Flask to create instance of web application, request to get request data, jsonify to turns the JSON output into a Response object with the application/json mimetype, SQAlchemy from flask_sqlalchemy to accessing database, and Marshmallow from flask_marshmallow to serialized object.
  • 12. CreateInstance & Set Sqlite Path and flask object app = Flask(__name__) basedir = os.path.abspath(os.path.dirname(__file__)) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'api.sqlite') db = SQLAlchemy(app) ma = Marshmallow(app) Create a app instance and set sqlite path in app config,after it binding SQLAlchemy and Marshmallow into our flask application.
  • 13. Declare Model Class and constructor //code class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email //code
  • 14. Create a Response Schema //code class UserSchema(ma.Schema): class Meta: # Fields to expose fields = ('id','username', 'email') user_schema = UserSchema() users_schema = UserSchema(many=True) //code //This part defined structure of response of our endpoint. We want that all of our endpoint will have JSON response. Here we define that our JSON response will have 3 keys(id, username, and email). Also we defined user_schema as instance of UserSchema, and user_schemas as instances of list of UserSchema.
  • 15. Create a New User Api # endpoint to create new user //code @app.route("/user", methods=["POST"]) def add_user(): username = request.json['username'] email = request.json['email'] new_user = User(username, email) db.session.add(new_user) db.session.commit() return user_schema.jsonify(new_user) //code On this part we define endpoint to create new user. First we set the route to “/user” and set HTTP methods to POST. After set the route and methods we define function that will executed if we access this endpoint. On this function first we get username and email from request data. After that we create new user using data from request data. Last we add new user to data base and show new user in JSON form as response.
  • 16. Show All users Api # endpoint to show all users //code @app.route("/user", methods=["GET"]) def get_user(): all_users = User.query.all() result = users_schema.dump(all_users) return jsonify(result.data) //code //On this part we define endpoint to get list of all users and show the result as JSON response.
  • 17. View user Api # endpoint to get user detail by id //code @app.route("/user/<id>", methods=["GET"]) def user_detail(id): user = User.query.get(id) return user_schema.jsonify(user) //code //on this part we define endpoint to get user data, but instead of get all the user here we just get data from one user based on id. If you look carefully at the route, you can see different pattern on the route of this endpoint. Patern like “<id>” is parameter, so you can change it with everything you want. This parameter should put on function parameter(in this case def user_detail(id)) so we can get this parameter value inside function.
  • 18. Update User Api # endpoint to update user //code @app.route("/user/<id>", methods=["PUT"]) def user_update(id): user = User.query.get(id) username = request.json['username'] email = request.json['email'] user.email = email user.username = username db.session.commit() return user_schema.jsonify(user) //code we define endpoint to update user. First we call user that related with given id on parameter. Then we update username and email value of this user with value from request data using put method.
  • 19. Delete user Api # endpoint to delete user //code @app.route("/user/<id>", methods=["DELETE"]) def user_delete(id): user = User.query.get(id) db.session.delete(user) db.session.commit() return user_schema.jsonify(user) //code #endpoint to delete user. First we call user that related with given id on parameter. Then we delete it.
  • 20. Before Running Actions Now • enter into python interactive shell using following command in your terminal: > python • import db object and generate SQLite database Use following code in python interactive shell > from api import db > db.create_all() Api.sqlite will be generated inside your project folder
  • 21. Run Application > python crud.py Now apis are in action , try via postman Screenshot Attached in Next Slide
  • 23. Thanks • Thanks to Bear With Me