【问题标题】:Provide sample value for request parameter in Swagger在 Swagger 中为请求参数提供示例值
【发布时间】:2017-01-10 18:06:56
【问题描述】:

我在 Spring-Boot RestController 中有一个 rest 方法的方法签名,如下所示:

@RequestMapping(
        value = "/path",
        method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE
)
@ApiImplicitParams({
        @ApiImplicitParam(
                name = "message", 
                value = "Message that is sent to the method", 
                required = true, 
                dataType = "string", 
                paramType = "body"
        )
})
public @ResponseBody String receiveMessage(@RequestBody String message) {
    // ...

    return "{\"success\": true}";
}

我想为 message 参数提供一个“样本”值,它是一个 JSON 字符串(例如 {"key" : "value"})。有人知道我如何使用 Swagger 注释来做到这一点吗?我试过了

@ApiImplicitParams({
        @ApiImplicitParam(
                // ...
                example = "...JSON value..."
        )
})

但它没有用。我想要的是文档中的“示例值”,读者可以单击以使文档中的参数值字段填充给定的示例值。这可能吗?

这是它的外观截图:

只是为了防止“无用”的答案:由于我的业务逻辑,我无法将参数的类型从 String 更改为某些类类型。

【问题讨论】:

  • 为什么不使用@ApiModelProperty将数据类作为参数和文档?

标签: java rest spring-boot swagger


【解决方案1】:

很遗憾,您无法为原子参数 (String, Number, ...) 提供示例或示例值。

如果参数是带有模式的对象,您只能提供示例,您只需在属性描述中添加example属性:

properties:
  firstName:
    description: first name
    type: string
    example: John

作为最后的手段,您可以在参数描述中添加一个示例值(ApiImplicitParam 注释中的value)。

    @ApiImplicitParam(
            name = "message", 
            value = "Message that is sent to the method. Example: value", 
            required = true, 
            dataType = "string", 
            paramType = "body"
    )

【讨论】:

    【解决方案2】:

    对于 Spring Boot 用户,假设您有一个 REST 方法,接受 json 正文,但由于某些原因没有明确使用 @RequestBody。按照以下步骤生成正确的 Swagger 文档

    更新 SpringFox 配置 bean 以获取其他模型

    @Bean
    public Docket apiDocket() {
         return new Docket(DocumentationType.SWAGGER_2)
                 // ...
                 .additionalModels(new TypeResolver().resolve(YourRequestModel.class));
    }
    

    更新@ApiImplicitParams的控制器API

    @PostMapping("/your-api")
    @ApiOperation(value = "brief description", notes = "Greater details come here")
    @ApiImplicitParams({
       @ApiImplicitParam(paramType = "header", name = "x-locale", example = "en"),
       @ApiImplicitParam(paramType = "body", dataType = "YourRequestModel")
    })
    public YourResponsetModel processRequest() {
       // ...
       return null;
    }
    

    这将为我们生成带有可选标题 x-localebody 类型为 YourRequestModel 的 Swagger。

    【讨论】:

      【解决方案3】:

      你可以试试这个:

      public MyObject myController(@ApiParam(example = "examplestring") @RequestParam("name") String name,
                  @ApiParam(example = "1")@RequestParam("eventNo") int eventNo, @ApiParam(example = "2")@RequestParam("halRequestNo") int halRequestNo){
      

      【讨论】: