2. • Sample code canbe found here:
https://gist.github.com/kiakiraki/a1e352afeb79792d39e86bfd49
d46654
• Sample project can be found here:
https://github.com/kiakiraki/flask-restplus-template
4. Flask is Fun
A Minimal Application URL Parameters and Routing
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
return 'Subpath %s' % subpath
5. Flask is not Fun
Handle HTTP Methods
• Handle HTTP method with
if statement
• Endpoints and Methods
correspond one-on-one
• Difficult to divide up,
the method is bloated
• Not bad, but a better way ...
@app.route('/login', methods=['GET',
'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return
show_the_login_form()
8. Good things of Flask-RESTPlus
• The endpoint corresponds to the Python Class
• HTTP method corresponds to Python method
• Validation of parameters
• Swagger document can be generated automatically
9. A Minimal Example
from flask import Flask
from flask_restplus import
(Api, Namespace, Resource)
app = Flask(__name__)
api = Api(
app,
title='Hello World!',
version='1.0',
description='てすとだよ')
hello_namespace = Namespace('helloworld',
description='end point of Hello World!’)
@hello_namespace.route('')
class HelloWorld(Resource):
def get(self):
return 'Hello World!', 200
def post(self):
return f'Hello {arguments}!', 200
if __name__ == '__main__':
api.add_namespace(hello_namespace)
app.run()