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

PDF
Flask Basics
PDF
Rest API using Flask & SqlAlchemy
PDF
Flask SQLAlchemy
PDF
Flask patterns
PPTX
Flask – Python
PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
PDF
Flask Introduction - Python Meetup
PPTX
Build restful ap is with python and flask
Flask Basics
Rest API using Flask & SqlAlchemy
Flask SQLAlchemy
Flask patterns
Flask – Python
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Flask Introduction - Python Meetup
Build restful ap is with python and flask

What's hot (20)

KEY
LvivPy - Flask in details
PDF
Flask - Backend com Python - Semcomp 18
Β 
PDF
Filling the flask
PDF
Kyiv.py #17 Flask talk
PDF
Python RESTful webservices with Python: Flask and Django solutions
PPT
Learn flask in 90mins
PDF
Web develop in flask
PDF
Python Flask app deployed to OPenShift using Wercker CI
PDF
The new features of PHP 7
PDF
Denys Serhiienko "ASGI in depth"
Β 
PDF
Getting Started-with-Laravel
PDF
ι–’θ₯ΏPHPε‹‰εΌ·δΌš php5.4぀まみぐい
ODP
Developing Drizzle Replication Plugins
PDF
GrΓ’ce aux tags Varnish, j'ai switchΓ© ma prod sur Raspberry Pi
PDF
Quick flask an intro to flask
Β 
PPTX
Flask vs. Django
PDF
Datagrids with Symfony 2, Backbone and Backgrid
PDF
Rest api with Python
PDF
PPT
Red5 - PHUG Workshops
LvivPy - Flask in details
Flask - Backend com Python - Semcomp 18
Β 
Filling the flask
Kyiv.py #17 Flask talk
Python RESTful webservices with Python: Flask and Django solutions
Learn flask in 90mins
Web develop in flask
Python Flask app deployed to OPenShift using Wercker CI
The new features of PHP 7
Denys Serhiienko "ASGI in depth"
Β 
Getting Started-with-Laravel
ι–’θ₯ΏPHPε‹‰εΌ·δΌš php5.4぀まみぐい
Developing Drizzle Replication Plugins
GrΓ’ce aux tags Varnish, j'ai switchΓ© ma prod sur Raspberry Pi
Quick flask an intro to flask
Β 
Flask vs. Django
Datagrids with Symfony 2, Backbone and Backgrid
Rest api with Python
Red5 - PHUG Workshops
Ad

Similar to Flask RESTful Flask HTTPAuth (20)

PDF
Rest in flask
PPTX
Flask-RESTPlusで便利γͺREST APIι–‹η™Ί | Productive RESTful API development with Flask-...
PPTX
Flask & Flask-restx
PPTX
Flask restfulservices
PDF
Introduction to rest using flask
PDF
Rest API in my experience
PPTX
Introduction to HTTP - Hypertext Transfer Protocol
PPT
δΈ€η§ε€šε±ζ—Άδ»£ηš„ι€šη”¨ web εΊ”η”¨ζžΆζž„
PPT
PPTX
Flask-Python
PPTX
Python Flask WTF.pptx
PPTX
Flask_basics.pptx
PDF
Python and Flask introduction for my classmates ΠŸΡ€Π΅Π·Π΅Π½Ρ‚Π°Ρ†ΠΈΡ ΠΈ Π²Π²Π΅Π΄Π΅Π½ΠΈΠ΅ Π² flask
PDF
Service intergration
PPTX
Flask
PDF
Introduction to Flask Micro Framework
PDF
Rest api titouan benoit
PPTX
REST with Eve and Python
PPTX
Hammock, a Good Place to Rest
PDF
What The Flask? and how to use it with some Google APIs
Rest in flask
Flask-RESTPlusで便利γͺREST APIι–‹η™Ί | Productive RESTful API development with Flask-...
Flask & Flask-restx
Flask restfulservices
Introduction to rest using flask
Rest API in my experience
Introduction to HTTP - Hypertext Transfer Protocol
δΈ€η§ε€šε±ζ—Άδ»£ηš„ι€šη”¨ web εΊ”η”¨ζžΆζž„
Flask-Python
Python Flask WTF.pptx
Flask_basics.pptx
Python and Flask introduction for my classmates ΠŸΡ€Π΅Π·Π΅Π½Ρ‚Π°Ρ†ΠΈΡ ΠΈ Π²Π²Π΅Π΄Π΅Π½ΠΈΠ΅ Π² flask
Service intergration
Flask
Introduction to Flask Micro Framework
Rest api titouan benoit
REST with Eve and Python
Hammock, a Good Place to Rest
What The Flask? and how to use it with some Google APIs
Ad

More from Eueung Mulyana (20)

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

Recently uploaded (20)

PDF
SASE Traffic Flow - ZTNA Connector-1.pdf
PPTX
QR Codes Qr codecodecodecodecocodedecodecode
PPTX
international classification of diseases ICD-10 review PPT.pptx
PPTX
artificial intelligence overview of it and more
PDF
Unit-1 introduction to cyber security discuss about how to secure a system
PDF
Cloud-Scale Log Monitoring _ Datadog.pdf
PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
PDF
Triggering QUIC, presented by Geoff Huston at IETF 123
Β 
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
Β 
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PDF
The Internet -By the Numbers, Sri Lanka Edition
Β 
PDF
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
DOCX
Unit-3 cyber security network security of internet system
PPTX
Introuction about WHO-FIC in ICD-10.pptx
PDF
RPKI Status Update, presented by Makito Lay at IDNOG 10
Β 
PDF
WebRTC in SignalWire - troubleshooting media negotiation
PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PDF
Testing WebRTC applications at scale.pdf
PPTX
Digital Literacy And Online Safety on internet
SASE Traffic Flow - ZTNA Connector-1.pdf
QR Codes Qr codecodecodecodecocodedecodecode
international classification of diseases ICD-10 review PPT.pptx
artificial intelligence overview of it and more
Unit-1 introduction to cyber security discuss about how to secure a system
Cloud-Scale Log Monitoring _ Datadog.pdf
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
Triggering QUIC, presented by Geoff Huston at IETF 123
Β 
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
Β 
INTERNET------BASICS-------UPDATED PPT PRESENTATION
The Internet -By the Numbers, Sri Lanka Edition
Β 
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
Slides PDF The World Game (s) Eco Economic Epochs.pdf
Unit-3 cyber security network security of internet system
Introuction about WHO-FIC in ICD-10.pptx
RPKI Status Update, presented by Makito Lay at IDNOG 10
Β 
WebRTC in SignalWire - troubleshooting media negotiation
522797556-Unit-2-Temperature-measurement-1-1.pptx
Testing WebRTC applications at scale.pdf
Digital Literacy And Online Safety on internet

Flask RESTful Flask HTTPAuth