SlideShare a Scribd company logo
2
Most read
9
Most read
20
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

PDF
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
PPT
Java naming conventions
Lovely Professional University
 
PDF
Methods in Java
Jussi Pohjolainen
 
PPTX
StringBuffer.pptx
meenakshi pareek
 
PPT
Learn REST API with Python
Larry Cai
 
PPTX
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
PDF
Function arguments In Python
Amit Upadhyay
 
PPTX
RESTful API Testing using Postman, Newman, and Jenkins
QASymphony
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
Java naming conventions
Lovely Professional University
 
Methods in Java
Jussi Pohjolainen
 
StringBuffer.pptx
meenakshi pareek
 
Learn REST API with Python
Larry Cai
 
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Function arguments In Python
Amit Upadhyay
 
RESTful API Testing using Postman, Newman, and Jenkins
QASymphony
 

What's hot (20)

PPTX
Payroll management system for Employee
Chhabi Lal Garhewal
 
PPTX
Typescript ppt
akhilsreyas
 
PPTX
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
Aaqib Hussain
 
PPTX
JAVA PROGRAMMING
Niyitegekabilly
 
PPTX
Security Testing Training With Examples
Alwin Thayyil
 
PDF
Functional programming
ijcd
 
PDF
Py.test
soasme
 
PDF
javacollections.pdf
ManojKandhasamy1
 
PPTX
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
PDF
What is Performance Testing?
QA InfoTech
 
PDF
Python-Tuples
Krishna Nanda
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PPTX
Java Data Types
Spotle.ai
 
PPTX
Express JS Middleware Tutorial
Simplilearn
 
PPTX
Exception handling in ASP .NET
baabtra.com - No. 1 supplier of quality freshers
 
PDF
javascript objects
Vijay Kalyan
 
PPT
Exception handling
Tata Consultancy Services
 
PDF
Postman 101 for Students
Postman
 
PPTX
Payroll management
Anita Yadav
 
PPT
Equivalence partitions analysis
Vadym Muliavka
 
Payroll management system for Employee
Chhabi Lal Garhewal
 
Typescript ppt
akhilsreyas
 
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
Aaqib Hussain
 
JAVA PROGRAMMING
Niyitegekabilly
 
Security Testing Training With Examples
Alwin Thayyil
 
Functional programming
ijcd
 
Py.test
soasme
 
javacollections.pdf
ManojKandhasamy1
 
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
What is Performance Testing?
QA InfoTech
 
Python-Tuples
Krishna Nanda
 
JDBC – Java Database Connectivity
Information Technology
 
Java Data Types
Spotle.ai
 
Express JS Middleware Tutorial
Simplilearn
 
Exception handling in ASP .NET
baabtra.com - No. 1 supplier of quality freshers
 
javascript objects
Vijay Kalyan
 
Exception handling
Tata Consultancy Services
 
Postman 101 for Students
Postman
 
Payroll management
Anita Yadav
 
Equivalence partitions analysis
Vadym Muliavka
 
Ad

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

PPTX
SW Security Lec4 Securing architecture.pptx
KhalidShawky1
 
PDF
FastAPI - Rest Architecture - in english.pdf
inigraha
 
PDF
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
PDF
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
PPTX
Flask-Python
Triloki Gupta
 
PDF
Flask jwt authentication tutorial
Katy Slemon
 
PDF
Scalable web application architecture
postrational
 
PDF
Google app-engine-with-python
Deepak Garg
 
PPTX
Flask Application ppt to understand the flask
vijoho5545
 
PDF
Building an API with Django and Django REST Framework
Christopher Foresman
 
PDF
Enterprise-Ready FastAPI: Beyond the Basics
Alexander Ptakhin
 
KEY
LvivPy - Flask in details
Max Klymyshyn
 
PDF
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Inexture Solutions
 
PDF
Flask Web Development 1st Edition Miguel Grinberg
cjvsgfu2766
 
PDF
Flask patterns
it-people
 
PPTX
Flask & Flask-restx
ammaraslam18
 
PDF
Pinterest like site using REST and Bottle
Gaurav Bhardwaj
 
PDF
Introduction to App Engine Development
Ron Reiter
 
PDF
Flask docs
Kunal Sangwan
 
PPTX
Web Dev 21-01-2024.pptx
PARDHIVANNABATTULA
 
SW Security Lec4 Securing architecture.pptx
KhalidShawky1
 
FastAPI - Rest Architecture - in english.pdf
inigraha
 
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
Flask-Python
Triloki Gupta
 
Flask jwt authentication tutorial
Katy Slemon
 
Scalable web application architecture
postrational
 
Google app-engine-with-python
Deepak Garg
 
Flask Application ppt to understand the flask
vijoho5545
 
Building an API with Django and Django REST Framework
Christopher Foresman
 
Enterprise-Ready FastAPI: Beyond the Basics
Alexander Ptakhin
 
LvivPy - Flask in details
Max Klymyshyn
 
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Inexture Solutions
 
Flask Web Development 1st Edition Miguel Grinberg
cjvsgfu2766
 
Flask patterns
it-people
 
Flask & Flask-restx
ammaraslam18
 
Pinterest like site using REST and Bottle
Gaurav Bhardwaj
 
Introduction to App Engine Development
Ron Reiter
 
Flask docs
Kunal Sangwan
 
Web Dev 21-01-2024.pptx
PARDHIVANNABATTULA
 
Ad

Recently uploaded (20)

PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PDF
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PPT
Ppt for engineering students application on field effect
lakshmi.ec
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PDF
JUAL EFIX C5 IMU GNSS GEODETIC PERFECT BASE OR ROVER
Budi Minds
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PPTX
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
Ppt for engineering students application on field effect
lakshmi.ec
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
JUAL EFIX C5 IMU GNSS GEODETIC PERFECT BASE OR ROVER
Budi Minds
 
Information Retrieval and Extraction - Module 7
premSankar19
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
Inventory management chapter in automation and robotics.
atisht0104
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 

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