spring-boot - 如何将 "Example Value"添加到 Swagger 中的参数

标签 spring-boot swagger swagger-ui 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>
...

我拥有的代码是:
    @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);
    }

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

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

我错过了什么?

最佳答案

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

a single example for non-body type parameters



不管你用的是什么 @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);
    }

对于主体参数,有 examples属性。检查 Springfox Reference Documentation如何使用它。
...
examples = @io.swagger.annotations.Example(
        value = {
            @ExampleProperty(value = "{'property': 'test'}", mediaType = "application/json")
        })) 
}
...

关于spring-boot - 如何将 "Example Value"添加到 Swagger 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55949949/

相关文章:

spring - bootstrap.yml 未加载 Spring Boot 2

spring - 找不到mainClassName,不需要

c# - 如何在 C# ApiController 中发送字节数组

c# - 如何将自定义模型绑定(bind)器与 Swashbuckle、Swagger 和 NSwag 一起使用?

java - 从 Swagger 中删除额外的参数

Swagger springfox 在 POST 上隐藏模型属性

Azure Pipeline - 目标版本无效 : 11

javascript - thymeleaf 表达式

java - 如何配置 Swagger UI、Jersey 和文件上传?

asp.net-web-api - 无法运行 Swagger UI