SlideShare a Scribd company logo

Flask-RESTful
Flask-HTTPAuth
Eueung Mulyana
http://eueung.github.io/python/flask-restful
Python CodeLabs | Attribution-ShareAlike CC BY-SA
1 / 20
 Flask-RESTful
2 / 20
Example #1
fromflaskimportFlask
fromflask.extimportrestful
app=Flask(__name__)
api=restful.Api(app)
#----------------------------------
classHelloWorld(restful.Resource):
defget(self):
return{'hello':'world'}
#----------------------------------
api.add_resource(HelloWorld,'/')
#----------------------------------
if__name__=='__main__':
app.run(debug=True)
3 / 20
fromflaskimportFlask,request
fromflask.ext.restfulimportResource,Api
app=Flask(__name__)
api=Api(app)
todos={}
#----------------------------------
classTodoSimple(Resource):
defget(self,todo_id):
return{todo_id:todos[todo_id]}
defput(self,todo_id):
todos[todo_id]=request.form['data']
return{todo_id:todos[todo_id]}
#----------------------------------
api.add_resource(TodoSimple,'/<string:todo_id>')
#----------------------------------
if__name__=='__main__':
app.run(debug=True)
127.0.0.1--[23/Nov/201504:41:41]"PUT/todo1HTTP/1.1"
127.0.0.1--[23/Nov/201504:47:57]"GET/todo1HTTP/1.1"
Example #2
$curlhttp://localhost:5000/todo1-d"data=Rememberthemilk"
{"todo1":"Rememberthemilk"}
$curlhttp://localhost:5000/todo1
{"todo1":"Rememberthemilk"}
4 / 20
Notes
Using requests
fromrequestsimportput,get
put('http://localhost:5000/todo1',data={'data':'Rememberthe
#{u'todo1':u'Rememberthemilk'}
get('http://localhost:5000/todo1').json()
#{u'todo1':u'Rememberthemilk'}
5 / 20
fromflaskimportFlask
fromflask.ext.restfulimportreqparse,abort,Api,Resource
app=Flask(__name__)
api=Api(app)
TODOS={
'todo1':{'task':'buildanAPI'},
'todo2':{'task':'?????'},
'todo3':{'task':'profit!'},
}
#----------------------------------
defabort_if_todo_doesnt_exist(todo_id):
iftodo_idnotinTODOS:
abort(404,message="Todo{}doesn'texist".format(todo_id))
parser=reqparse.RequestParser()
parser.add_argument('task',type=str)
#----------------------------------
classTodoList(Resource):
defget(self):
returnTODOS
defpost(self):
args=parser.parse_args()
todo_id=int(max(TODOS.keys()).lstrip('todo'))+1
todo_id='todo%i'%todo_id
TODOS[todo_id]={'task':args['task']}
returnTODOS[todo_id],201
Example #3
#singleitem;get,updateanddelete
classTodo(Resource):
defget(self,todo_id):
abort_if_todo_doesnt_exist(todo_id)
returnTODOS[todo_id]
defdelete(self,todo_id):
abort_if_todo_doesnt_exist(todo_id)
delTODOS[todo_id]
return'',204
defput(self,todo_id):
args=parser.parse_args()
task={'task':args['task']}
TODOS[todo_id]=task
returntask,201
#----------------------------------
api.add_resource(TodoList,'/todos')
api.add_resource(Todo,'/todos/<todo_id>')
#----------------------------------
if__name__=='__main__':
app.run(debug=True)
6 / 20
127.0.0.1--[23/Nov/201505:15:54]"GET/todosHTTP/1.1"
127.0.0.1--[23/Nov/201505:17:14]"GET/todos/todo3HTTP/1.
127.0.0.1--[23/Nov/201505:17:36]"DELETE/todos/todo2HTTP
127.0.0.1--[23/Nov/201505:17:59]"GET/todos/todo2HTTP/1.
127.0.0.1--[23/Nov/201507:38:07]"POST/todosHTTP/1.1"
127.0.0.1--[23/Nov/201507:38:56]"GET/todos/todo4HTTP/1.
127.0.0.1--[23/Nov/201507:39:41]"PUT/todos/todo4HTTP/1.
$curlhttp://localhost:5000/todos
$curlhttp://localhost:5000/todos/todo3
#verbose
$curlhttp://localhost:5000/todos/todo2-XDELETE-v
$curlhttp://localhost:5000/todos-d"task=somethingnew"-X
$curlhttp://localhost:5000/todos/todo3-d"task=somethingdi
7 / 20
fromsimplexmlimportdumps
fromflaskimportmake_response,Flask
fromflask_restfulimportApi,Resource
#------------------------------------------
defoutput_xml(data,code,headers=None):
resp=make_response(dumps({'response':data}),code)
resp.headers.extend(headersor{})
returnresp
#------------------------------------------
app=Flask(__name__)
api=Api(app,default_mediatype='application/xml')
api.representations['application/xml']=output_xml
#------------------------------------------
classHello(Resource):
defget(self,entry):
return{'hello':entry}
#------------------------------------------
api.add_resource(Hello,'/<string:entry>')
#------------------------------------------
if__name__=='__main__':
app.run(debug=True)
Example #4
fromrequestsimportget
get('http://localhost:5000/me').content#default_mediatype
#Chromeok,Postmandefaultjson
get('http://localhost:5000/me',headers={"accept":"application
get('http://localhost:5000/me',headers={"accept":"application
8 / 20
References
Flask-RESTful
Flask-RESTful Documentation
Flask-RESTful @github
9 / 20
 Flask-HTTPAuth
10 / 20
fromflaskimportFlask
fromflask_httpauthimportHTTPBasicAuth
app=Flask(__name__)
auth=HTTPBasicAuth()
users={
"john":"hello",
"susan":"bye"
}
#----------------------------------
@auth.get_password
defget_pw(username):
ifusernameinusers:
returnusers.get(username)
returnNone
#----------------------------------
@app.route('/')
@auth.login_required
defindex():
return"Hello,%s!"%auth.username()
#----------------------------------
if__name__=='__main__':
app.run(debug=True)
Example #1
127.0.0.1--[23/Nov/201518:24:07]"GET/HTTP/1.1"401-
127.0.0.1--[23/Nov/201518:24:32]"POST/HTTP/1.1"405-
127.0.0.1--[23/Nov/201518:26:37]"GET/HTTP/1.1"401-
127.0.0.1--[23/Nov/201518:27:30]"GET/HTTP/1.1"200-
127.0.0.1--[23/Nov/201518:27:42]"GET/HTTP/1.1"401-
127.0.0.1--[23/Nov/201518:27:49]"GET/HTTP/1.1"200-
11 / 20
Example #2
#http://john:hello@localhost:5000
127.0.0.1--[24/Nov/201515:47:55]"GET/HTTP/1.1"401-
127.0.0.1--[24/Nov/201515:47:55]"GET/HTTP/1.1"200-
#Notes
#Postmanfailed!
#Todos:HTTPie,requests
fromflaskimportFlask
fromflask_httpauthimportHTTPDigestAuth
app=Flask(__name__)
app.config['SECRET_KEY']='secretkeyhere'
auth=HTTPDigestAuth()
#----------------------------------
users={
"john":"hello",
"susan":"bye"
}
#----------------------------------
@auth.get_password
defget_pw(username):
ifusernameinusers:
returnusers.get(username)
returnNone
#----------------------------------
@app.route('/')
@auth.login_required
defindex():
return"Hello,%s!"%auth.username()
#----------------------------------
if__name__=='__main__':
app.run()
12 / 20
References
Flask-HTTPAuth
Flask-HTTPAuth Documentation
Flask-HTTPAuth @github
13 / 20
 Tuts by @miguelgrinberg
14 / 20
fromflaskimportFlask,jsonify,abort,make_response
fromflask.ext.restfulimportApi,Resource,reqparse,fields,marshal
fromflask.ext.httpauthimportHTTPBasicAuth
#app=Flask(__name__,static_url_path="")->404
app=Flask(__name__)
api=Api(app)
auth=HTTPBasicAuth()
#--------------------------------------------------
@auth.get_password
defget_password(username):
ifusername=='miguel':
return'python'
returnNone
@auth.error_handler
defunauthorized():
#return403insteadof401topreventbrowsersfromdisplayingthedefault
#authdialog
returnmake_response(jsonify({'message':'Unauthorizedaccess'
#--------------------------------------------------
#--------------------------------------------------
api.add_resource(TaskListAPI,'/todo/api/v1.0/tasks',endpoint=
api.add_resource(TaskAPI,'/todo/api/v1.0/tasks/<int:id>',endpoint=
#--------------------------------------------------
if__name__=='__main__':
app.run(debug=True)
Example #1
Part 1,2
tasks=[
{
'id':1,
'title':u'Buygroceries',
'description':u'Milk,Cheese,Pizza,Fruit,Tylenol'
'done':False
},
{
'id':2,
'title':u'LearnPython',
'description':u'NeedtofindagoodPythontutorialo
'done':False
}
]
#--------------------------------------------------
task_fields={
'title':fields.String,
'description':fields.String,
'done':fields.Boolean,
'uri':fields.Url('task')
}
15 / 20
Part 3,4
classTaskListAPI(Resource):
decorators=[auth.login_required]
def__init__(self):
self.reqparse=reqparse.RequestParser()
self.reqparse.add_argument('title',type=str,required=
help='Notasktitleprovided'
location='json')
self.reqparse.add_argument('description',type=str,default=
location='json')
super(TaskListAPI,self).__init__()
defget(self):
return{'tasks':[marshal(task,task_fields)fortask
defpost(self):
args=self.reqparse.parse_args()
task={
'id':tasks[-1]['id']+1,
'title':args['title'],
'description':args['description'],
'done':False
}
tasks.append(task)
return{'task':marshal(task,task_fields)},201
classTaskAPI(Resource):
decorators=[auth.login_required]
def__init__(self):
self.reqparse=reqparse.RequestParser()
self.reqparse.add_argument('title',type=str,location
self.reqparse.add_argument('description',type=str,lo
self.reqparse.add_argument('done',type=bool,location
super(TaskAPI,self).__init__()
defget(self,id):
task=[taskfortaskintasksiftask['id']==id]
iflen(task)==0:abort(404)
return{'task':marshal(task[0],task_fields)}
defput(self,id):
task=[taskfortaskintasksiftask['id']==id]
iflen(task)==0:abort(404)
task=task[0]
args=self.reqparse.parse_args()
fork,vinargs.items():
ifvisnotNone:
task[k]=v
return{'task':marshal(task,task_fields)}
defdelete(self,id):
task=[taskfortaskintasksiftask['id']==id]
iflen(task)==0:abort(404)
tasks.remove(task[0])
return{'result':True}
16 / 20
The APIs
 
HTTP Method URI Endpoint Action
GET /todo/api/v1.0/tasks tasks Retrieve list of tasks
POST /todo/api/v1.0/tasks tasks Create a new task
GET /todo/api/v1.0/tasks/[task_id] task Retrieve a task
PUT /todo/api/v1.0/tasks/[task_id] task Update an existing task
DELETE /todo/api/v1.0/tasks/[task_id] task Delete a task
17 / 20
Notes
Marshalling
RequestParser: define the arguments and how to
validate them.
A side benefit of letting Flask-RESTful do the validation is
that now there is no need to have a handler for the bad
request code 400 error, this is all taken care of by the
extension.
Example #1
 
18 / 20
References
Designing a RESTful API using Flask-RESTful
Code Repo @github
19 / 20

END
Eueung Mulyana
http://eueung.github.io/python/flask-restful
Python CodeLabs | Attribution-ShareAlike CC BY-SA
20 / 20

More Related Content

What's hot (20)

KEY
LvivPy - Flask in details
Max Klymyshyn
 
PDF
Flask - Backend com Python - Semcomp 18
Lar21
 
PDF
Filling the flask
Jason Myers
 
PDF
Kyiv.py #17 Flask talk
Alexey Popravka
 
PDF
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
PPT
Learn flask in 90mins
Larry Cai
 
PDF
Web develop in flask
Jim Yeh
 
PDF
Python Flask app deployed to OPenShift using Wercker CI
Bruno Rocha
 
PDF
The new features of PHP 7
Zend by Rogue Wave Software
 
PDF
Denys Serhiienko "ASGI in depth"
Fwdays
 
PDF
Getting Started-with-Laravel
Mindfire Solutions
 
PDF
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
ODP
Developing Drizzle Replication Plugins
Padraig O'Sullivan
 
PDF
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Jérémy Derussé
 
PDF
Quick flask an intro to flask
juzten
 
PPTX
Flask vs. Django
Rachel Sanders
 
PDF
Datagrids with Symfony 2, Backbone and Backgrid
eugenio pombi
 
PDF
Rest api with Python
Santosh Ghimire
 
PPT
Red5 - PHUG Workshops
Brendan Sera-Shriar
 
LvivPy - Flask in details
Max Klymyshyn
 
Flask - Backend com Python - Semcomp 18
Lar21
 
Filling the flask
Jason Myers
 
Kyiv.py #17 Flask talk
Alexey Popravka
 
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Learn flask in 90mins
Larry Cai
 
Web develop in flask
Jim Yeh
 
Python Flask app deployed to OPenShift using Wercker CI
Bruno Rocha
 
The new features of PHP 7
Zend by Rogue Wave Software
 
Denys Serhiienko "ASGI in depth"
Fwdays
 
Getting Started-with-Laravel
Mindfire Solutions
 
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
Developing Drizzle Replication Plugins
Padraig O'Sullivan
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Jérémy Derussé
 
Quick flask an intro to flask
juzten
 
Flask vs. Django
Rachel Sanders
 
Datagrids with Symfony 2, Backbone and Backgrid
eugenio pombi
 
Rest api with Python
Santosh Ghimire
 
Red5 - PHUG Workshops
Brendan Sera-Shriar
 

Similar to Flask RESTful Flask HTTPAuth (20)

PDF
Rest in flask
Hamid Feizabadi
 
PPTX
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Akira Tsuruda
 
PPTX
Flask & Flask-restx
ammaraslam18
 
PPTX
Flask restfulservices
Marcos Lin
 
PDF
Introduction to rest using flask
Wekanta
 
PDF
Rest API in my experience
tamim-subeen
 
PPTX
Introduction to HTTP - Hypertext Transfer Protocol
Santiago Basulto
 
PPT
一种多屏时代的通用 web 应用架构
勇浩 赖
 
PPT
Tp web
勇浩 赖
 
PPTX
Flask-Python
Triloki Gupta
 
PPTX
Python Flask WTF.pptx
SudhanshiBakre1
 
PPTX
Flask_basics.pptx
AkshayRevankar16
 
PDF
Python and Flask introduction for my classmates Презентация и введение в flask
Nikita Lozhnikov
 
PDF
Service intergration
재민 장
 
PPTX
Flask
Mamta Kumari
 
PDF
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
PDF
Rest api titouan benoit
Titouan BENOIT
 
PPTX
REST with Eve and Python
PiXeL16
 
PPTX
Hammock, a Good Place to Rest
Stratoscale
 
PDF
What The Flask? and how to use it with some Google APIs
Bruno Rocha
 
Rest in flask
Hamid Feizabadi
 
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Akira Tsuruda
 
Flask & Flask-restx
ammaraslam18
 
Flask restfulservices
Marcos Lin
 
Introduction to rest using flask
Wekanta
 
Rest API in my experience
tamim-subeen
 
Introduction to HTTP - Hypertext Transfer Protocol
Santiago Basulto
 
一种多屏时代的通用 web 应用架构
勇浩 赖
 
Tp web
勇浩 赖
 
Flask-Python
Triloki Gupta
 
Python Flask WTF.pptx
SudhanshiBakre1
 
Flask_basics.pptx
AkshayRevankar16
 
Python and Flask introduction for my classmates Презентация и введение в flask
Nikita Lozhnikov
 
Service intergration
재민 장
 
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
Rest api titouan benoit
Titouan BENOIT
 
REST with Eve and Python
PiXeL16
 
Hammock, a Good Place to Rest
Stratoscale
 
What The Flask? and how to use it with some Google APIs
Bruno Rocha
 
Ad

More from Eueung Mulyana (20)

PDF
FGD Big Data
Eueung Mulyana
 
PDF
Hyper-Connectivity and Data Proliferation - Ecosystem Perspective
Eueung Mulyana
 
PDF
Industry 4.0 And Beyond The A.I* For Surviving A Tech-Accelerated World
Eueung Mulyana
 
PDF
Blockchain Introduction
Eueung Mulyana
 
PDF
Bringing Automation to the Classroom: A ChatOps-Based Approach
Eueung Mulyana
 
PDF
FinTech & Cryptocurrency Introduction
Eueung Mulyana
 
PDF
Open Source Networking Overview
Eueung Mulyana
 
PDF
ONOS SDN Controller - Clustering Tests & Experiments
Eueung Mulyana
 
PDF
Open stack pike-devstack-tutorial
Eueung Mulyana
 
PDF
Basic onos-tutorial
Eueung Mulyana
 
PDF
ONOS SDN Controller - Introduction
Eueung Mulyana
 
PDF
OpenDaylight SDN Controller - Introduction
Eueung Mulyana
 
PDF
Mininet Basics
Eueung Mulyana
 
PDF
Android Programming Basics
Eueung Mulyana
 
PDF
Cloud Computing: Overview and Examples
Eueung Mulyana
 
PDF
selected input/output - sensors and actuators
Eueung Mulyana
 
PDF
Connected Things, IoT and 5G
Eueung Mulyana
 
PDF
Connectivity for Local Sensors and Actuators Using nRF24L01+
Eueung Mulyana
 
PDF
NodeMCU with Blynk and Firebase
Eueung Mulyana
 
PDF
Trends and Enablers - Connected Services and Cloud Computing
Eueung Mulyana
 
FGD Big Data
Eueung Mulyana
 
Hyper-Connectivity and Data Proliferation - Ecosystem Perspective
Eueung Mulyana
 
Industry 4.0 And Beyond The A.I* For Surviving A Tech-Accelerated World
Eueung Mulyana
 
Blockchain Introduction
Eueung Mulyana
 
Bringing Automation to the Classroom: A ChatOps-Based Approach
Eueung Mulyana
 
FinTech & Cryptocurrency Introduction
Eueung Mulyana
 
Open Source Networking Overview
Eueung Mulyana
 
ONOS SDN Controller - Clustering Tests & Experiments
Eueung Mulyana
 
Open stack pike-devstack-tutorial
Eueung Mulyana
 
Basic onos-tutorial
Eueung Mulyana
 
ONOS SDN Controller - Introduction
Eueung Mulyana
 
OpenDaylight SDN Controller - Introduction
Eueung Mulyana
 
Mininet Basics
Eueung Mulyana
 
Android Programming Basics
Eueung Mulyana
 
Cloud Computing: Overview and Examples
Eueung Mulyana
 
selected input/output - sensors and actuators
Eueung Mulyana
 
Connected Things, IoT and 5G
Eueung Mulyana
 
Connectivity for Local Sensors and Actuators Using nRF24L01+
Eueung Mulyana
 
NodeMCU with Blynk and Firebase
Eueung Mulyana
 
Trends and Enablers - Connected Services and Cloud Computing
Eueung Mulyana
 
Ad

Recently uploaded (20)

PPTX
Networking_Essentials_version_3.0_-_Module_5.pptx
ryan622010
 
PDF
Digital burnout toolkit for youth workers and teachers
asociatiastart123
 
PDF
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
PDF
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
PPTX
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
PDF
FutureCon Seattle 2025 Presentation Slides - You Had One Job
Suzanne Aldrich
 
PPTX
Orchestrating things in Angular application
Peter Abraham
 
PPTX
Metaphysics_Presentation_With_Visuals.pptx
erikjohnsales1
 
PPTX
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 
PDF
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
PPTX
西班牙巴利阿里群岛大学电子版毕业证{UIBLetterUIB文凭证书}文凭复刻
Taqyea
 
PDF
Enhancing Parental Roles in Protecting Children from Online Sexual Exploitati...
ICT Frame Magazine Pvt. Ltd.
 
PDF
The Internet - By the numbers, presented at npNOG 11
APNIC
 
PPTX
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
PDF
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PDF
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
 
PDF
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
PPTX
Networking_Essentials_version_3.0_-_Module_3.pptx
ryan622010
 
Networking_Essentials_version_3.0_-_Module_5.pptx
ryan622010
 
Digital burnout toolkit for youth workers and teachers
asociatiastart123
 
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
FutureCon Seattle 2025 Presentation Slides - You Had One Job
Suzanne Aldrich
 
Orchestrating things in Angular application
Peter Abraham
 
Metaphysics_Presentation_With_Visuals.pptx
erikjohnsales1
 
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
西班牙巴利阿里群岛大学电子版毕业证{UIBLetterUIB文凭证书}文凭复刻
Taqyea
 
Enhancing Parental Roles in Protecting Children from Online Sexual Exploitati...
ICT Frame Magazine Pvt. Ltd.
 
The Internet - By the numbers, presented at npNOG 11
APNIC
 
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
 
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
Networking_Essentials_version_3.0_-_Module_3.pptx
ryan622010
 

Flask RESTful Flask HTTPAuth