首页 文章

Swagger - 如何编写常见的响应字段?

提问于
浏览
1

我有几个API,所有这些API都返回JSON,其中包含一个名为 success 的布尔字段 .

API 1 {"success": true, "data": "some data"}

API 2 {"success": false, "error": "error message"}

我可以用模板之类的东西编写swagger 2.0文档,所以我不需要像这样在每个API中复制和粘贴成功字段部分吗?

responses:
    200:
      schema:
        properties:
          success:
            type: boolean
             description: true if the request is successful.
          data:
             ...

responses:
    200:
      schema:
        properties:
          success:
            type: boolean
             description: true if the request is successful.
          error:
             ...

谢谢!

1 回答

  • 5

    是的,使用 allOf 作为公共字段:

    responses:
      200:
        schema:
          allOf:
            - $ref: '#/definitions/common'
            - properties:
                data:
                # your details here
    
    definitions:
      Common:
        type: object
        properties:
          success:
            type: boolean
             description: true if the request is successful.
    

    也:

    schema:
            allOf:
              - $ref: '#/definitions/Common'
              - properties:
                  data:
                    $ref: '#/definitions/Another'
    

相关问题