如何在flask-restx的Swagger文档中定义API接口返回体结构?
flask-restx接口返回体Swagger标注方法
这个需求完全可以实现,flask-restx官方没有提供@api.doc(returns=xxx)的写法,而是通过响应模型定义 + 对应装饰器的方式实现返回体内容的标注,具体操作如下:
方法1:使用@api.marshal_with(带自动序列化校验)
这是最常用的写法,既可以在Swagger中生成返回体说明,也可以自动对接口返回结果做序列化、字段过滤:
- 首先用
api.model定义你需要标注的返回体结构,每个字段可以单独加描述:
from flask_restx import fields # 定义返回体模型,第一个参数是Swagger中显示的模型名称,第二个参数是字段定义 response_model = api.model('Demo返回结果', { 'info': fields.String(description="Some very interesting information") })
- 把模型绑定到对应的接口方法上:
class MyResource(Resource): @api.doc(params={'id': 'An ID'}) @api.marshal_with(response_model, code=200, description="请求成功返回结果") def get(self, id): res = some_function_of_id(id) return {"info": res}
方法2:使用@api.response(仅标注结构不做序列化)
如果你不需要框架自动处理返回结果的序列化,只需要在Swagger文档上显示返回体说明,可以用这个方法:
class MyResource(Resource): @api.doc(params={'id': 'An ID'}) # 参数依次是:响应状态码、状态描述、对应的返回体模型 @api.response(200, '请求成功', response_model) def get(self, id): res = some_function_of_id(id) return {"info": res}
补充说明
- 如果接口存在多个状态码对应不同返回结构的场景,叠加多个
@api.response装饰器即可,每个状态码可以绑定独立的模型和描述 - 嵌套结构、列表结构的返回体也可以通过
fields.Nested()、fields.List()来定义,示例如下:
# 嵌套子结构 user_model = api.model('用户信息', { 'name': fields.String(description="用户名"), 'age': fields.Integer(description="用户年龄") }) # 外层返回结构 list_response_model = api.model('用户列表返回结果', { 'code': fields.Integer(description="业务状态码"), 'msg': fields.String(description="业务提示"), 'data': fields.List(fields.Nested(user_model), description="用户列表数据") })
内容的提问来源于stack exchange,提问作者bjarkemoensted
相关产品推荐
相关产品推荐

