如何将“示例值”添加到 Swagger 中的参数

frm*_*frm 5 swagger swagger-ui spring-boot springfox

我正在使用 Swagger 用 Spring Boot 创建一个新的 Rest API 来记录它,但我无法更改 Web 上显示的示例值。我可以在模型中更改它,但不能在 POST 参数中更改。

这些是我的依赖项:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>
...
        <swagger.version>2.9.2</swagger.version>
...
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
...
Run Code Online (Sandbox Code Playgroud)

我拥有的代码是:

    @PostMapping("events")
    @ApiOperation(value = "Get events")
    public ResponseEntity<List<Event>> events(
            @ApiParam(value = "Event type", required = true, example = "sent") final @RequestBody String type) {
        return new ResponseEntity<List<Event>>(getEvents.get(type), HttpStatus.OK);
    }
Run Code Online (Sandbox Code Playgroud)

而不是在示例值“已发送”下看到,而是看到“字符串”。

此注释适用于 Event 模型,但不适用于这里。

我错过了什么?

Vla*_*ier 5

根据@ApiParam-example属性的文档是

非主体类型参数的单个示例

但是,您@RequestBody对字符串参数使用了注释。在您的情况下:将@RequestBody注释更改为@RequestParam,您应该能够在 Swagger UI 中看到提供的示例:

@PostMapping("events")
@ApiOperation(value = "Get events")
public ResponseEntity<List<Event>> events(
    @ApiParam(value = "Event type", required = true, example = "sent") final @RequestParam String type) {
        return new ResponseEntity<List<Event>>(getEvents.get(type), HttpStatus.OK);
    }
Run Code Online (Sandbox Code Playgroud)

对于主体参数,有examples属性。查看Springfox 参考文档如何使用它。

...
examples = @io.swagger.annotations.Example(
        value = {
            @ExampleProperty(value = "{'property': 'test'}", mediaType = "application/json")
        })) 
}
...
Run Code Online (Sandbox Code Playgroud)