SlideShare une entreprise Scribd logo
1  sur  23
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
Thanks
• Thanks to Bear With Me

Contenu connexe

Tendances

Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90minsLarry Cai
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flaskjuzten
 
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 CIBruno 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 2010Binh Nguyen
 
170517 damien gérard framework facebook
170517 damien gérard   framework facebook170517 damien gérard   framework facebook
170517 damien gérard framework facebookGeeks 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 solutionsSolution4Future
 
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 HTTPMykhailo 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-slidesMasterCode.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-slidesMasterCode.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 PecoraroChristopher Pecoraro
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Resting with OroCRM Webinar
Resting with OroCRM WebinarResting with OroCRM Webinar
Resting with OroCRM WebinarOro Inc.
 

Tendances (20)

Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flask
 
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
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talkKyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
 
Flask SQLAlchemy
Flask SQLAlchemy Flask SQLAlchemy
Flask SQLAlchemy
 
Flask vs. Django
Flask vs. DjangoFlask vs. Django
Flask vs. Django
 
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
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
170517 damien gérard framework facebook
170517 damien gérard   framework facebook170517 damien gérard   framework facebook
170517 damien gérard framework facebook
 
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
 
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
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
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
 
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
 
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
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
CakePHP
CakePHPCakePHP
CakePHP
 
Resting with OroCRM Webinar
Resting with OroCRM WebinarResting with OroCRM Webinar
Resting with OroCRM Webinar
 

Similaire à Build restful ap is with python and flask

Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorialKaty Slemon
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLaurence Svekis ✔
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Serverhendrikvb
 
Sencha Touch - Introduction
Sencha Touch - IntroductionSencha Touch - Introduction
Sencha Touch - IntroductionABC-GROEP.BE
 
IPaste SDK v.1.0
IPaste SDK v.1.0IPaste SDK v.1.0
IPaste SDK v.1.0xrebyc
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)Amazon Web Services
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)James Titcumb
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and PythonPiXeL16
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)James Titcumb
 
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/4DEVCON
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfAppweb Coders
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Symfony2 Introduction Presentation
Symfony2 Introduction PresentationSymfony2 Introduction Presentation
Symfony2 Introduction PresentationNerd Tzanetopoulos
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Method and decorator
Method and decoratorMethod and decorator
Method and decoratorCeline George
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2markstory
 

Similaire à Build restful ap is with python and flask (20)

18.register login
18.register login18.register login
18.register login
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Server
 
Sencha Touch - Introduction
Sencha Touch - IntroductionSencha Touch - Introduction
Sencha Touch - Introduction
 
IPaste SDK v.1.0
IPaste SDK v.1.0IPaste SDK v.1.0
IPaste SDK v.1.0
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Flask-Python
Flask-PythonFlask-Python
Flask-Python
 
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
 
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
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Symfony2 Introduction Presentation
Symfony2 Introduction PresentationSymfony2 Introduction Presentation
Symfony2 Introduction Presentation
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Method and decorator
Method and decoratorMethod and decorator
Method and decorator
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2
 

Dernier

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdfEr. Suman Jyoti
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 

Dernier (20)

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 

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
  • 22.
  • 23. Thanks • Thanks to Bear With Me