@ApiResponse 响应体为空(Spring Boot)
Posted
技术标签:
【中文标题】@ApiResponse 响应体为空(Spring Boot)【英文标题】:@ApiResponse with empty response body (Spring Boot) 【发布时间】:2020-06-04 17:38:53 【问题描述】:我正在寻找一种方法来告诉 swagger 某个 API 响应代码没有响应正文。例如,获取响应可以返回 200 代码并将实际对象作为响应,或者如果与传递的 ID 关联的对象不存在,则返回 404:
@ApiResponses(value =
@ApiResponse(responseCode = "200", description = "Object found"),
@ApiResponse(responseCode = "404", description = "Invalid object ID", content = @Content)
)
这是我能想到的最接近的东西,但它并不完美,我仍然在 404 响应的描述下得到一个烦人的“媒体类型”。 谢谢!
【问题讨论】:
为什么不能使用responseCode 204? 如果我想要一个额外的响应代码,例如 403(您无权访问此对象)怎么办?我想通过响应代码来处理最重要的特殊情况,这样用户就不必为响应正文而烦恼... 【参考方案1】:这可能是更好(也更短)的方式:
@ApiResponse(
responseCode = "404",
description = "Not found",
content = @Content(schema = @Schema(hidden = true)))
【讨论】:
【参考方案2】:如果您没有指定@ApiResponse
注释的content
属性,则控制器方法的返回类型将是您的响应内容。为了防止这种情况,明确定义content
:
@ApiResponse(responseCode = "200", description = "OK",
content = @Content(schema = @Schema(implementation = Void.class)))
或者您可以直接返回ResponseEntity<Void>
。
【讨论】:
Void.class 是实现参数的默认值,没有帮助。不幸的是,我的方法没有返回 void。这就是我得到的:ibb.co/6ZDNynR【参考方案3】:您可以在 v2 中的方法之上使用以下内容
@ApiResponses(value =
@ApiResponse(code = 200, message = "Success", response = YourObject.class),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message="Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Failure")
)
对于 V3,您可以尝试这样的操作,以防您的方法返回某个对象
@Operation(summary = "Add a new object", description = "", tags = "yourObject" )
@ApiResponses(value =
@ApiResponse(responseCode = "201", description = "Object created",content = @Content(schema = @Schema(implementation = YourObject.class))),
@ApiResponse(responseCode = "400", description = "Invalid input"),
@ApiResponse(responseCode = "409", description = "Object already exists") )
@PostMapping(value = "/your-url", consumes = "application/json","application/xml" )
public ResponseEntity<YourObject> addObject(
...
return ...
如果你的方法返回 void,试试这个
@Operation(summary = "Update an existing object", description = "", tags = "yourObject" )
@ApiResponses(value =
@ApiResponse(responseCode = "200", description = "successful operation"),
@ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
@ApiResponse(responseCode = "404", description = "Object not found"),
@ApiResponse(responseCode = "405", description = "Validation exception") )
@PutMapping(value = "/your-url/id", consumes = "application/json", "application/xml" )
public ResponseEntity<Void> addObject(
...
return ...
【讨论】:
我使用的是oas v3注解,你的解决方案是基于v2的。以上是关于@ApiResponse 响应体为空(Spring Boot)的主要内容,如果未能解决你的问题,请参考以下文章
由于状态消息为空,ADFS 响应失败时的 Spring SAML 单点登录