OpenAPI无法正确处理同路径多控制器方法及参数重复问题
同路径不同请求参数的GET接口OpenAPI解析异常问题
场景说明
在Spring Boot项目的Controller层定义多个路径完全相同的GET接口,各接口仅通过@RequestParam参数做区分是非常常见的合法开发场景:
- Spring框架与Java本身不会对该写法抛出任何异常
- OpenAPI运行时调用接口也不会报错
但该写法会被OpenAPI错误解析,同时伴随Custom-Authorization请求头参数相关的异常。Swagger 2可通过原生@ApiParameter注解正常兼容该场景,且Spring、Java、Swagger 2、OpenAPI规范本身均未将该写法判定为非法,因此该问题属于OpenAPI的明确功能限制,疑似Bug。
问题复现代码
@GetMapping(path = "", params = {"id"}, produces = {MediaType.APPLICATION_JSON_VALUE}) @Operation( operationId = "getUsersById", summary = "Returns all users records with the same id.", description = "Retrieves users from persistence storage by given id.", tags = {"UserController"}, parameters = { @Parameter(in = ParameterIn.HEADER, name = "Custom-Authorization", description = "Jwt Bearer Token", example = "Bearer eyJhbGciOiJIUzU...", required = true, schema = @Schema(type = "string")) }, responses = { @ApiResponse( responseCode = "200", description = "Users Json array.", content = @Content(array = @ArraySchema(schema = @Schema(implementation = UserResponse.class)))), @ApiResponse( responseCode = "404", description = "User(s) with provided id could not be found.", content = @Content(schema = @Schema(implementation = ResponseEntity.class))) }) public List<UserResponse> getUsersById( @Parameter(name = "id", example = "1234567", required = true) @RequestParam String id) throws MyException { // 业务逻辑省略 } @GetMapping(path = "", params = {"lastName"}, produces = {MediaType.APPLICATION_JSON_VALUE}) @Operation(hidden = true, operationId = "getUserByLastName", summary = "Returns all user records with the same last name.", description = "Retrieves users from persistence storage by given last name.", tags = {"UserController"}, // parameters = { // @Parameter(in = ParameterIn.HEADER, // name = "Custom-Authorization", // description = "Jwt Bearer Token", // example = "Bearer eyJhbGciOiJIUzU...", // required = true, // schema = @Schema(type = "string")) // }, responses = { @ApiResponse( responseCode = "200", description = "Users Json array.", content = @Content(array = @ArraySchema(schema = @Schema(implementation = UserResponse.class)))), @ApiResponse( responseCode = "404", description = "Users with provided last name could not be found.", content = @Content(schema = @Schema(implementation = ResponseEntity.class))) }) public List<UserResponse> getUserLastName( @Parameter(name = "lastName", example = "Tester", required = true) @RequestParam String lastName) throws MyException { // 业务逻辑省略 }
现有方案的问题
springdoc-openapi #580议题给出的临时方案是使用@Hidden注解隐藏其余同路径接口,仅对外展示单个接口,上述示例代码也采用了该处理方式,但该方案完全不符合实际业务需求,并非合理的解决方案。
除此之外该方案还存在另一个问题:无法为所有接口统一配置Custom-Authorization请求头参数——如果不在被隐藏的接口中注释掉该头参数的配置,就会触发duplicate parameter(参数重复)类报错。
待解决诉求
是否存在可行的解决方案,能够同时满足以下两个要求:
- 无需隐藏接口,让OpenAPI正确识别同路径、不同请求参数的GET接口
- 支持正常配置全局公共请求头参数,不会触发参数重复报错
内容的提问来源于stack exchange,提问作者pixel
相关产品推荐
相关产品推荐

