Swagger 2.0中如何处理多个400响应

时间:2020-07-08 05:34:32

标签: api yaml swagger

对于400个HTTP状态代码,我有两种情况,其中第一个响应如下所示:

{
  "error": "No file uploaded!"
}

第二个响应如下:

{
  "error": "Wrong file format. Endpoint only accepts images and pdf file formats!"
}

在swagger 2.0 yaml文件定义中,我以这种方式记录了两个响应:

definitions:
     MultiError400:
        type: object
        properties:
          error:
            type: array
            items:
              enum:
              - $ref: '#/definitions/FirstError'
              - $ref: '#/definitions/SecondError'
      FirstError:
        type: string
        example: "No file uploaded!"
      SecondError:
        type: string
        example: "Wrong file format. Endpoint only accepts images and pdf file formats!"

在端点内部,我这样称呼它:

responses:
        "200":
          description: "Successful operation"
          schema:
            type: file
            example: image/png
        "400":
          description: Multiple 400 errors
          schema:
            $ref: '#/definitions/MultiError400'

但是当我对其进行测试时,它给了我这个未记录的错误:

Undocumented
TypeError: Failed to fetch

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

produces:
  - "application/json"
responses:
  "400":
    description: ""
    schema:
      type: "object"
      properties:
        error:
          type: "string"
          description: >
            error:
             * `First Error` - No file uploaded!
             * `Second Error` - Endpoint only accepts images and pdf file formats!
          enum:
          - "No file uploaded!"
          - "Wrong file format. Endpoint only accepts images and pdf file formats!"
          default: "Wrong file format. Endpoint only accepts images and pdf file formats!"

您可以设置任何default形式的enum来显示在示例值中,它看起来像这样:

enter image description here


您的模型视图如下:

enter image description here

有关更多详细信息,请参见https://swagger.io/docs/specification/2-0/describing-responses/


希望获得帮助。