【问题标题】:springdoc-openapi-ui + swagger don't understand @PathVariable required = false flagspringdoc-openapi-ui + swagger 不理解 @PathVariable required = false 标志
【发布时间】:2021-03-03 22:03:50
【问题描述】:

我使用这个库来生成文档:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.5.0</version>
</dependency>

我有这个控制器:

@RestController
public class TestController {

    @GetMapping("/test{hz}")
    public String test(@PathVariable(value = "hz", required = false) String hz) {
        return "test";
    }
}

但我得到了这份文件:

为什么required = false 不起作用?

我试过了:

@RestController
public class TestController {

    @GetMapping("/test{hz}")
    public String test(
            @Parameter(description = "foo", required = false)
            @PathVariable(value = "hz", required = false) String hz) {
        return "test";
    }
}

也不行

编辑:(@Helen 评论的答案)- 我当然知道:

@RestController
public class TestController {

    @GetMapping(value = {"/test", "/test{hz}"})
    public String test(
            @Parameter(description = "foo", required = false)
            @PathVariable(value = "hz", required = false) String hz) {
        return "test";
    }
}

我试过这个:

@PathVariable(value = "hz", required = false) Optional<String> hz

它使文档变得更糟。所以我没有添加这段代码。用{"/test", "/test{hz}"} 看起来是这样的:

【问题讨论】:

  • 始终需要路径参数。要拥有可选的路径参数,您需要 define two paths - 带有和不带有该参数。
  • @Helen 我在我的问题中添加了更多信息。
  • @PathVariable 必须有required = true,路径参数不能标记为可选。您需要定义 2 种单独的方法 - 一种带有 hz 参数,另一种没有。
  • @Helen 看起来很奇怪。你为什么这么断章取义? Spring注释public @interface PathVariable有一个参数boolean required() default true;,我可以设置required == false,它在Spring中工作。 Swagger 注释 public @interface Parameterboolean required() default false; 为什么我必须使用 2 个单独的方法? Spring 允许我使用一种方法@GetMapping(value = {"/test", "/test{hz}"})。你认为图书馆(swagger)必须规定规则吗?
  • OpenAPI Specification 声明路径参数必须有required: true。它们不能是可选的。可能 @PathVariable with required=false 是其他 API 描述格式的选项,但它与 OpenAPI 不兼容。您需要两个单独的方法,因为/test{hz} 的方法必须有一个必需的路径参数,而/test 的方法必须没有参数。

标签: spring swagger spring-restcontroller springdoc springdoc-openui


【解决方案1】:

这符合 OpenAPI 规范。

客户端进行 API 调用时,每个路径参数都必须替换为实际值。在 OpenAPI 中,使用 in: path 定义路径参数。参数名称必须与路径中指定的名称相同。还要记得添加required: true,因为路径参数总是需要的。

你可以看看文档:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2022-10-25
    • 2021-05-07
    • 2021-06-03
    • 1970-01-01
    • 2022-06-14
    • 2021-11-09
    相关资源
    最近更新 更多