簡介
flask-restx
是一個支持RESTFul
的flask
插件。
用於規范化接口的編寫,並且支持 swagger
文檔。
使用說明
下載
pip install flask-restx
示例代碼
示例代碼以一個使用藍圖的程序為例。其他小的應用可參看 flask-restx官方示例
項目結構
.
├── config.py
├── log
├── manage.py # 啟動入口
├── server
│ ├── __init__.py
│ ├── api.py
│ ├── apis
│ │ └── test
│ │ ├── api.py
│ │ └── web.py
│ ├── static
│ └── templates
└── utils
└── db.py
實踐代碼:
# server __init__.py
from flask import Flask
def create_app():
# 創建Flask對象
app = Flask(__name__)
# 注冊藍圖
from server.api import api_v1
app.register_blueprint(api_v1)
return app
# server api.py
from flask import Blueprint
from flask_restx import Api
from server.apis.test.web import ns as test_ns
api_v1 = Blueprint('api1', __name__, url_prefix='/api')
api = Api(
api_v1,
version='1.0',
title='test flask',
description='test flask'
)
api.add_namespace(test_ns)
# server apis test web.py
import json
from flask import request, render_template, make_response, jsonify
from flask_restx import Namespace, Resource, fields
ns = Namespace('test', description='test')
@ns.route("", strict_slashes=False) # 實際訪問地址 /api/test/
class TestHandler(Resource):
def get(self):
# 如果使用模板的塊,需要使用 make_response
# return make_response(render_template('index.html', data=res), 200)
# 使用 jsonify 是為了返回json數據的同時,相比於 json.dumps() 其會自動修改 content-type 為 application/json
# 另外,如果使用 jsonify()的同時,還想自定義返回狀態碼,可以使用 make_response(jsonify(data=data), 201)
return jsonify()
def post(self):
pass
def put(self):
pass
def delete(self):
pass
代碼說明
- 使用
flask-restx
之后,可以使用類視圖的方式定義接口. - 可以訪問
localhost:5000/api
訪問swagger
接口文檔頁面。 - 接口文檔可以在編寫代碼的地方一起定義。
swagger文檔編寫方式
以上面 TestHandler
類方法為基礎,定義以下較為常用的文檔。
通常情況下,
restful
接口默認返回的都是json
數據。因此以下文檔針對json
數據。所有定義文檔都可以在瀏覽器訪問
/api/
查看對於前后端不分離的
templates
等模板文檔,可能有不正確的地方。
1. 參數以url形式
@ns.route("/<id>", strict_slashes=False) # 實際訪問地址 /api/test/1
@ns.doc(params={'id': 'An ID'})
class TestHandler(Resource):
def get(self, id):
return jsonify()
@ns.doc(response={403: 'Not Authorized'})
def post(self, id):
pass
2. 參數以json body的形式
parent = ns.model('Parent', {
'name': fields.String,
'age': fields.Integer(discriminator=True),
'addr': fields.String(description='地址'),
'gender': fields.String(description='性別', required=True, enum=['男', '女', '未知'])
})
child = ns.inherit('Child', parent, {
'extra': fields.String
})
@ns.route("/test3", strict_slashes=False) # /api/test/test3
class Test2Handler(Resource):
@ns.marshal_with(child, as_list=True) # 等價於 @api.marshal_list_with(resource_fields)
def get(self):
return "返回一個對象"
@ns.marshal_with(child, code=201) # 201 代表創建成功
def post(self):
return '創建一個對象成功', 201
3. 其他
flask-restx
提供了許多文檔定制功能。每個功能都有不同的寫法。如:
- 某個請求默認需要某些參數,並且要驗證 ===>
@ns.expect(resource_fields, validate=True)
- 給已知響應定義默認響應--
@ns.response()
- url路徑文檔===》
@ns.route('', doc='')
或者@ns.doc()
- 可使用多個
@ns.route()
裝飾一個函數,使得多個url
定位到一個Handler處理 - 給參數定義文檔。如上文的
json body
形式中的parent
- 給
method
定義文檔 - 定義
headers
定義文檔 - 隱藏某些文檔
- 文檔授權
- 其他
具體文檔可點flask-restx官方文檔了解
RESTful接口風格說明
具體說明可參看阮一峰博客
坑點:此接口風格對批量處理的支持並不友好。解決此問題可參看RESTful API批量操作的實現