Building Beautiful Restful Apis Using Flask 1
Building Beautiful Restful Apis Using Flask 1
• I blog at http://michal.karzynski.pl
Short URL: karzyn.com
• I wrote a book for Linux admins, I write code in Python and JavaScript
Web (JavaScript)
API
(JSON)
Server
(Python)
Phone (Swift, Java)
WHAT IS A REST API?
REPRESENTATIONAL STATE TRANSFER
Headers Headers
Body Body
Request Response
GET ?search=Moby Dick
POST
PUT /api/books Cookies… 200 OK
DELETE
404 Not Found
Headers Headers
Body Body
flask.pocoo.org
FLASK-RESTPlus
• define and document endpoints
• validate input
• Tools:
• Swagger UI
• Swagger Editor
• Code generators
openapis.org swagger.io
OPEN API SPECIFICATION
• Standard language to describe REST APIs
• Tools:
• Swagger UI
• Swagger Editor
• Code generators
openapis.org swagger.io
Method Path Query
Headers
Body
Request
Method Path Query
@api.route('/<int:id>/borrow')
class BorrowBookController(Resource):
def post(self, id):
""" Borrow book from library.
Allows the current user to borrow
the book out of the library.
"""
...
return {'message': 'OK'}
Method Path Query
@api.route('/<int:id>/borrow')
class BorrowBookController(Resource):
class Resource:
def post(self, id):
""" Borrow book from library.
def get(self)...
def post(self)...
Allows the current user to borrow def put(self)...
the book out of the library.
def delete(self)...
"""
def patch(self)...
... def options(self)...
return {'message': 'OK'} def head(self)...
Method Path Query
@api.route(‘/books/<int:id>/borrow’)
@api.route('/articles/<title>')
@api.route('/wiki/<path:wikipage>')
@api.route('/values/<float:value>')
@api.route('/object/<uuid:identifier>')
Method Path Query
@api.expect(blog_post)
def post(self):
...
Method Path Query
Headers
Body
Response
Status Code
Headers
@api.route('/<int:id>')
@api.response(404, 'Post not found.')
class PostItem(Resource):
@api.response(204, 'Post successfully deleted.')
def delete(self, id):
"""
Deletes blog post.
"""
delete_post(id)
return None, 204
Status Code
Headers
@api.marshal_with(blog_post)
@api.marshal_list_with(blog_post)
def get(self):
def get(self):
... ...
EXCEPTION HANDLING
karzyn.com
THANK YOU