# 建立項目目錄 mkdir helloworld cd helloworld # 建立虛擬環境 python -m virtualenv venv # 激活虛擬環境 venv\Scripts\activate # 安裝環境包 pip install flask flask-restplus # 啓動 VS Code code .
from flask import Flask from flask_restplus import Api, Resource app = Flask(__name__) api_app = Api(app=app, version='1.0', title='Main', description='Main APIs') name_space = api_app.namespace(name='helloworld', description='The helloworld APIs EndPoint.') @name_space.route('/') class HelloWorld(Resource): def get(self): return { 'status': 'you get a request.' } def post(self): return { 'status': 'you post a request.' } if __name__ == "__main__": app.run(debug=True)
程序運行效果以下圖所示:python
此時,咱們能夠經過 Swagger UI 或者 curl 來請求咱們上面建立的 一個 get
和 一個 post
請求接口。git
參數傳遞,咱們只須要將咱們的接口定義添加參數配置便可,以下示例代碼所示:github
@name_space.route('/<int:id>') class HelloWorld(Resource): @api_app.doc(responses={ 200: 'ok', 400: 'not found', 500: 'something is error' }, params={ 'id': 'the task identifier' }) def get(self, id): return { 'status': 'you get a request.', 'id': id } def post(self, id): return { 'status': 'you post a request.' }
運行結構以下圖所示:數據庫
在上述兩個示例代碼中,咱們知道了如何定義 WebAPI 和 參數傳遞,下面咱們摘錄一個官方首頁的 Todo 示例,來完整展現如何使用:flask
from flask import Flask from flask_restplus import Api, Resource, fields app = Flask(__name__) api = Api(app, version='1.0', title='TodoMVC API', description='A simple TodoMVC API', ) # 配置 API 空間節點 ns = api.namespace('todos', description='TODO operations') # 配置接口數據模型(此數據模型是面向對外服務的,在實際項目中應與數據庫中的數據模型區分開) todo = api.model('Todo', { 'id': fields.Integer(readOnly=True, description='The task unique identifier'), 'task': fields.String(required=True, description='The task details') }) # 定義接口實體 class TodoDAO(object): def __init__(self): self.counter = 0 self.todos = [] def get(self, id): for todo in self.todos: if todo['id'] == id: return todo api.abort(404, "Todo {} doesn't exist".format(id)) def create(self, data): todo = data todo['id'] = self.counter = self.counter + 1 self.todos.append(todo) return todo def update(self, id, data): todo = self.get(id) todo.update(data) return todo def delete(self, id): todo = self.get(id) self.todos.remove(todo) # 建立種子數據 DAO = TodoDAO() DAO.create({'task': 'Build an API'}) DAO.create({'task': '?????'}) DAO.create({'task': 'profit!'}) # 定義服務接口 @ns.route('/') class TodoList(Resource): '''Shows a list of all todos, and lets you POST to add new tasks''' @ns.doc('list_todos') @ns.marshal_list_with(todo) def get(self): '''List all tasks''' return DAO.todos @ns.doc('create_todo') @ns.expect(todo) @ns.marshal_with(todo, code=201) def post(self): '''Create a new task''' return DAO.create(api.payload), 201 # 定義服務接口 @ns.route('/<int:id>') @ns.response(404, 'Todo not found') @ns.param('id', 'The task identifier') class Todo(Resource): '''Show a single todo item and lets you delete them''' @ns.doc('get_todo') @ns.marshal_with(todo) def get(self, id): '''Fetch a given resource''' return DAO.get(id) @ns.doc('delete_todo') @ns.response(204, 'Todo deleted') def delete(self, id): '''Delete a task given its identifier''' DAO.delete(id) return '', 204 @ns.expect(todo) @ns.marshal_with(todo) def put(self, id): '''Update a task given its identifier''' return DAO.update(id, api.payload) if __name__ == '__main__': app.run(debug=True)
程序運行效果以下圖所示:api
基於 Flask 而建立 Swagger UI 風格的 WebAPI 包有不少,如bash
它們都各有各的優缺點,可是就我目前使用狀況來講,仍是 Flask-RESTPlus 的構建方式我更喜歡一些,因此我就在這裏分享一下。app
最後的最後,安利一下我我的站點:hippiezhou,裏面的 必應壁紙 板塊收錄了天天的必應壁紙,但願你能喜歡。curl