[Python] Flask RESTful API 筆記
Flask-RESTful 是一個簡單的 Flask 套件,可以讓 Flask 簡單提供 RESTful API,最簡單回傳 json
的方式如下:
import time
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/api/')
if __name__ == '__main__':
app.run(debug=True)
但當然 RESTful API 最重要還是要可以使用 GET
(取資料)、POST
(新增資料)、PUT
(更新資料)、DELETE
(刪除資料)
而且要可以透過 /source/id
這種方式取得單筆資料或進一步取得子欄位。
像下面這個例子就比較完整了:
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
TODOS = {
'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'},
}
def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id))
parser = reqparse.RequestParser()
parser.add_argument('task')
# Todo
# shows a single todo item and lets you delete a todo item
class Todo(Resource):
def get(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
return TODOS[todo_id]
def delete(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
del TODOS[todo_id]
return '', 204
def put(self, todo_id):
args = parser.parse_args()
task = {'task': args['task']}
TODOS[todo_id] = task
return task, 201
# TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
def get(self):
return TODOS
def post(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']}
return TODOS[todo_id], 201
##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')
if __name__ == '__main__':
app.run(debug=True)
Reference
-
https://github.com/flask-restful/flask-restful/blob/master/docs/quickstart.rst
-
http://seanlin.logdown.com/posts/239771-use-flask-to-create-restful-api
-
http://seanlin.logdown.com/posts/247554-introduction-to-rest