【问题标题】:Swagger documentation for API response with flask-restx使用 flask-restx 进行 API 响应的 Swagger 文档
【发布时间】:2021-11-05 08:10:47
【问题描述】:

我正在阅读 the documentation 以获取带有 flask-restx 的 swagger 文档,并遵循示例。 我知道为了为 API 采用的参数生成 swagger 文档,我应该这样做

@api.doc(params={'id': 'An ID'})

但是,我找不到有关如何记录 API 响应正文的说明。不是响应代码,而是由例如返回的结果。获取方法。我正在寻找的是如下内容:

class MyResource(Resource):
    @api.doc(returns={"info": "Some very interesting information"})
    def get(self, id):
        res = some_function_of_id(id)
        return {"info": res}

有人知道这是否可行,如果可以,怎么做?

【问题讨论】:

    标签: flask swagger flask-restplus flask-restx


    【解决方案1】:

    试试 api.response 装饰器

    model = api.model('Model', {
        'name': fields.String,
    })
    @api.route('/my-resource/')
    class MyResource(Resource):
        @api.response(200, 'Success', model)
        @api.response(400, 'Validation Error')
        def get(self):
            pass
    

    请注意,@api.marshal_with() 装饰器会自动记录响应。

    https://flask-restx.readthedocs.io/en/latest/swagger.html#documenting-with-the-api-response-decorator

    【讨论】:

    • 这会记录响应代码,而不是 API 在成功调用时返回的结果。
    • 不,它也会记录响应结果。我将模型作为第三个参数传递,如果您传递模型,则应记录在案
    • 这是我尝试使用响应代码 400 的照片:imgur.com/AlsSlgl
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2021-10-30
    • 1970-01-01
    相关资源
    最近更新 更多