提问者:小点点

如何在Swagger中添加几个响应示例而不破坏Codecen?


根据官方文档,我一直在尝试将示例添加到我的SwaggerAPI中(请参阅请求和响应体示例的最后一个代码库),但它似乎没有按预期工作。

考虑以下最小示例:

swagger: "2.0"
info:
  description: Desc
  version: "1"
  title: Title
paths:
  /stuff:
    post:
      produces:
      - application/json
      responses:
        201:
          description: It worked
          content:
            application/json:
              schema:
                $ref: "#/definitions/StatusMessage"
              examples:
                Success without message:
                  value:
                    code: "00000"
                Success with message:
                  value:
                    code: "00000"
                    message: "All right"
definitions:
  StatusMessage:
    type: object
    description: Response with code and optional message
    properties:
      code:
        type: string
      message:
        type: string
    required:
    - code

我想提供示例响应,一个具有可选属性message,另一个没有。但是,上述YAML文件在生成的APIClass中产生错误的结果:

@ApiOperation(value = "", nickname = "stuffPost", notes = "", tags={  })
@ApiResponses(value = { 
    @ApiResponse(code = 201, message = "It worked") })
@RequestMapping(value = "/stuff",
    method = RequestMethod.POST)
default ResponseEntity<Void> stuffPost() { /*default implementation*/ }

产生属性不存在并且返回类型错误!此外,这在Swagger Editor中无法编译:响应属性不应具有其他属性

我将其更改为在Swagger Editor中获取“有效”示例,但生成的代码也错误。见下文:

paths:
  /stuff:
    post:
      produces:
      - application/json
      responses:
        201:
          description: It worked
          schema:
            $ref: "#/definitions/StatusMessage"
          examples:
            Success without message:
              code: "00000"
            Success with message:
              code: "00000"
              message: "All right"

生成方法为:

@ApiOperation(value = "", nickname = "stuffPost", notes = "", response = StatusMessage.class, tags={  })
@ApiResponses(value = { 
    @ApiResponse(code = 201, message = "It worked", response = StatusMessage.class) })
@RequestMapping(value = "/stuff",
    produces = { "application/json", "Success without message", "Success with message" }, 
    method = RequestMethod.POST)
default ResponseEntity<StatusMessage> stuffPost() { /*default implementation*/ }

这一次,产生属性就在那里,但完全关闭了!

我如何让它工作?如果我使用带有application/json的第二个版本作为示例标题的键,它会起作用,但由于重复的键,这会阻止我添加更多示例。


共1个答案

匿名用户

来自海伦的评论:

此示例混合了OpenAPI 2.0(swagger:'2.0')和OpenAPI 3.0(openapi: 3.0.0)语法。例如,content示例是OpenAPI 3.0关键字,但定义是2.0关键字。

OpenAPI 2.0不支持示例(复数形式),仅支持example-查看2.0添加示例指南。

我在OpenAPI 2.0中找到的解决此问题的方法如下:

paths:
  /stuff:
    post:
      produces:
      - application/json
      responses:
        201:
          description: It worked
          schema:
            $ref: "#/definitions/StatusMessage"
          examples:
            - code: "00000"
              message: "All right"
            - code: "00000"

这显示了两个示例(以01作为标题)并且不会破坏Codesen。