跳到主要内容

Swagger 文档

前言

flask-restplus/restx 内置 Swagger 文档:创建 Api 后自动生成 /(或指定 doc 路径)下的文档页面,通过 @api.doc()@api.expect()@api.marshal_with() 等装饰器补充描述。

自动生成的文档

from flask import Flask
from flask_restplus import Api, Resource

app = Flask(__name__)
api = Api(
app,
version="1.0",
title="TodoMVC API",
description="A simple TodoMVC API",
doc="/swagger/", # 文档页面路径,默认是 /
)

@api.doc() 装饰器

@api.route("/my-resource/<id>", endpoint="my-resource")
@api.doc(params={"id": "An ID"})
class MyResource(Resource):
def get(self, id):
return {}

@api.doc(responses={403: "Not Authorized"})
def post(self, id):
api.abort(403)

请求体与响应模型

from flask_restplus import Api, Resource, fields

api = Api(app)

item_model = api.model(
"Item",
{
"name": fields.String(required=True, description="名称"),
"price": fields.Float(required=True, description="价格"),
},
)


@api.route("/items")
class ItemList(Resource):
@api.expect(item_model) # 声明请求体模型
@api.marshal_with(item_model, code=201) # 声明响应模型
@api.response(400, "参数错误")
def post(self):
return api.payload, 201

命名空间分组

ns = api.namespace("todos", description="TODO operations")


@ns.route("/")
@ns.response(404, "Todo not found")
class TodoList(Resource):
def get(self):
...

命名空间让文档按组展示,适合大型项目。

参考