You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Flask-RESTPlus为POST接口返回值生成Swagger文档

Flask-RESTPlus POST端点返回数据文档配置方法

你可以通过框架自带的字段定义和响应装饰器实现返回结构的Swagger文档生成,具体操作如下:

1. 基础使用(适配你直接返回整数数组的场景)

直接使用@api.marshal_list_with装饰器绑定返回字段即可,完整示例代码如下:

import random
from flask_restplus import Api, Resource, fields

# 替换为你项目中已初始化的Api实例
api = Api()

class MyResource(Resource):
    # 绑定返回数组的元素类型、描述、响应状态码
    @api.marshal_list_with(fields.Integer(description='coin flip'), code=200, description="请求成功返回整数数组")
    def post(self):
        return [i for i in range(random.randrange(100))]

2. 多状态码返回配置

如果需要为不同HTTP状态码定义不同的返回结构,可以使用@api.response装饰器,示例如下:

import random
from flask_restplus import Api, Resource, fields

api = Api()

# 定义错误场景的返回模型
error_resp = api.model('ErrorResponse', {
    "error_msg": fields.String(description="错误提示信息")
})

class MyResource(Resource):
    @api.response(200, "请求成功", [fields.Integer(description='coin flip')])
    @api.response(400, "请求参数错误", error_resp)
    @api.response(500, "服务端异常", error_resp)
    def post(self):
        return [i for i in range(random.randrange(100))]

配置完成后启动服务,在Swagger UI的对应接口详情页的Responses区域,就可以看到你定义的返回类型、字段描述和自动生成的示例值。

内容的提问来源于stack exchange,提问作者francistheturd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:54:02