val*_*arv 15 java rest swagger spring-boot openapi
我正在寻找一种方法来告诉 swagger 某个 API 响应代码没有响应正文。例如,获取响应可以返回 200 代码以及实际对象作为响应,如果与传递的 ID 关联的对象不存在,则返回 404:
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Object found"),
@ApiResponse(responseCode = "404", description = "Invalid object ID", content = @Content)
})
Run Code Online (Sandbox Code Playgroud)
这是我能想到的最接近的东西,但它并不完美,我仍然在 404 响应的描述下得到一个烦人的“媒体类型”。谢谢!
Vla*_*ier 12
如果您没有指定注释content的属性@ApiResponse,则控制器方法的返回类型将是您的响应内容。为了防止这种情况content明确定义:
@ApiResponse(responseCode = "200", description = "OK",
content = @Content(schema = @Schema(implementation = Void.class)))
Run Code Online (Sandbox Code Playgroud)
或者您可以直接返回ResponseEntity<Void>。
这可能是更好(而且更短)的方法:
@ApiResponse(
responseCode = "404",
description = "Not found",
content = @Content(schema = @Schema(hidden = true)))
Run Code Online (Sandbox Code Playgroud)
您可以在 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")
})
Run Code Online (Sandbox Code Playgroud)
对于 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 ...
}
Run Code Online (Sandbox Code Playgroud)
如果你的方法返回 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 ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25637 次 |
| 最近记录: |