You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用springdoc-openapi为Spring REST API的同一响应码配置多个描述

问题分析与解决方案

首先得明确:OpenAPI 规范本身不允许为同一个 HTTP 响应码定义多个独立的响应描述。在 OpenAPI 的结构里,responses 是一个以状态码为键的对象,每个状态码只能对应一个响应条目——这就是为什么你添加多个 @ApiResponse(responseCode = "404") 时,只有第一个会被保留的原因,springdoc-openapi 只是严格遵循了这个规范。

不过你完全可以把多个错误场景的描述整合到同一个 @ApiResponse 里,而且还能让文档展示得清晰易读,这里有两种常用方案:

方案1:合并描述文本(最简单直接)

把所有404的错误场景合并到同一个 description 中,利用 OpenAPI 支持的 Markdown 格式来分隔不同场景,比如用项目符号列表或者换行:

@ApiResponses(value = { 
    @ApiResponse(responseCode = "200", description = "Task updated successfully", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = Task.class))}), 
    @ApiResponse(responseCode = "400", description = "Friend email equal to user email", content = @Content), 
    @ApiResponse(responseCode = "401", description = "Invalid Id Token", content = @Content), 
    @ApiResponse(responseCode = "404", description = "Possible errors:\n- Friend not found\n- Friend email is null\n- Task not found", content = @Content)
})

这样生成的文档会把三个错误场景以列表形式展示,清晰明了。

方案2:使用 examples 字段(更结构化)

如果想给每个错误场景配上对应的响应示例,可以利用 @Content 里的 examples 属性,每个示例对应一个错误场景,同时在示例的描述里说明具体错误:

@ApiResponses(value = { 
    @ApiResponse(responseCode = "200", description = "Task updated successfully", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = Task.class))}), 
    @ApiResponse(responseCode = "400", description = "Friend email equal to user email", content = @Content), 
    @ApiResponse(responseCode = "401", description = "Invalid Id Token", content = @Content), 
    @ApiResponse(responseCode = "404", description = "Resource not found (see examples for specific scenarios)", content = @Content(
        mediaType = "application/json",
        examples = {
            @ExampleObject(name = "Friend not found", summary = "Friend not found", description = "The specified friend does not exist", value = "{\"error\": \"Friend not found\"}"),
            @ExampleObject(name = "Friend email null", summary = "Friend email is null", description = "The provided friend email is null", value = "{\"error\": \"Friend email is null\"}"),
            @ExampleObject(name = "Task not found", summary = "Task not found", description = "The specified task does not exist", value = "{\"error\": \"Task not found\"}")
        }
    ))
})

这种方式不仅能展示所有错误场景,还能给每个场景配上具体的响应示例,对接口调用者更友好。

总结一下:不能直接为同一个状态码添加多个独立的 @ApiResponse,但通过合并描述或使用示例的方式,完全可以把所有错误场景清晰地呈现在接口文档里。

内容的提问来源于stack exchange,提问作者Isu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:22:46