1. 概述
在本教程中,我們將討論 Swagger 中 @Operation 和 @ApiResponse 註解之間的主要區別。
2. 使用 Swagger 進行描述性文檔
當我們創建 REST API 時,創建其適當的規範也同樣重要。 此外,這種規範應該易於閲讀、易於理解,並提供所有必要的信息。
此外,文檔應該描述對 API 所做的所有更改。 手動創建 REST API 文檔既耗時又繁瑣。 幸運的是,像 Swagger 這樣的工具可以幫助我們完成這個過程。
Swagger 是一套圍繞 OpenAPI 規範構建的開源工具。 它能幫助我們設計、構建、文檔和消費 REST API。
Swagger 規範是 REST API 文檔的標準。 使用 Swagger 規範,我們可以描述整個 API,例如暴露的端點、操作、參數、身份驗證方法等。
Swagger 提供各種註釋,可以幫助我們文檔化 REST API。 此外,它還提供 @Operation 和 @ApiResponse 註釋,用於文檔化 REST API 的響應。
在接下來的教程中,我們將使用下面的控制器類,並瞭解如何使用這些註釋:
@RestController
@RequestMapping("/customers")
class CustomerController {
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}
}3. @Operation
The @Operation annotation is used to describe a single operation. An operation is a unique combination of a path and an HTTP method.
Additionally, using @Operation, we can describe the result of a successful REST API call. In other words, we can use this annotation to specify the general return type.
Let’s add the annotation to our method:
@Operation(summary = "Gets customer by ID",
description= "Customer must exist")
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}接下來,我們將深入瞭解 @Operation 中最常用的屬性。
3.1. <i/>摘要</i>屬性
<i/>摘要</i>屬性包含操作的摘要字段。 簡單來説,它提供了一個對操作的簡短描述。 但是,我們應該將此參數限制在 120 個字符以內。
以下是如何在 <em/>@Operation</em/> 註解中定義摘要屬性:
@Operation(summary= "Gets customer by ID")3.2. <i/>description 屬性
通過使用 `description`,我們可以提供有關操作的更多詳細信息。例如,我們可以放置一段描述端點限制的文本:
@Operation(summary= "Gets customer by ID", description= "Customer must exist")3.3. 隱藏屬性
隱藏屬性表示該操作是否隱藏。
4. <em @ApiResponse @ApiResponses>
通常的做法是在使用 HTTP 狀態碼返回錯誤。我們可以使用 <em @ApiResponse @ApiResponses 註解來描述操作的可能返回碼。
雖然 <em @ApiResponse @ApiResponses 註解描述了一個操作及其通用返回類型,但 <em @ApiResponse @ApiResponses 註解描述了其他可能的返回碼。
此外,該註解可以應用於方法級別和類級別。類級別的註解僅在方法級別已定義具有相同代碼的 <em @ApiResponse @ApiResponses 註解時才會被解析。換句話説,方法註解優先於類註解。
我們應該在 <em @ApiResponse @ApiResponses 註解中使用 <em @ApiResponse @ApiResponses 註解,無論我們有幾個響應。 如果我們直接使用此註解,則不會被 Swagger 解析。
讓我們為我們的方法定義 <em @ApiResponse @ApiResponses 和 <em @ApiResponse @ApiResponses 註解:
@ApiResponses(value = {
@ApiResponse(responseCode = 400, description = "Invalid ID supplied"),
@ApiResponse(responseCode = 404, description = "Customer not found")})
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}我們還可以使用標註來指定成功響應:
@Operation(summary = "Gets customer by ID", description = "Customer must exist")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Ok", content =
{ @Content(mediaType = "application/json", schema =
@Schema(implementation = CustomerResponse.class)) }),
@ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
@ApiResponse(responseCode = "404", description = "Customer not found"),
@ApiResponse(responseCode = "500", description = "Internal server error", content =
{ @Content(mediaType = "application/json", schema =
@Schema(implementation = ErrorResponse.class)) }) })
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}現在,我們來回顧一下在 @ApiResponse 中使用的某些屬性。
4.1. responseCode 和 description 屬性
responseCode 和 description 屬性是 @ApiResponse 註解的必需參數。需要注意的是,我們不能定義具有相同代碼屬性的多個 @ApiResponse 註解。
消息屬性通常包含與響應相關的可讀性消息:
@ApiResponse(responseCode = 400, message = "Invalid ID supplied")4.2. <i data-translation-key="content">內容</i> 屬性
有時,一個端點會使用不同的響應類型。例如,我們可以為成功響應和錯誤響應定義不同的類型。我們可以通過使用可選的 `內容 屬性`,將響應類關聯為模式來描述它們。
首先,讓我們定義一個在內部服務器錯誤時返回的類:
class ErrorResponse {
private String error;
private String message;
// getters and setters
}第二,我們添加一個新的 @ApiResponse 以處理內部服務器錯誤:
@Operation(summary = "Gets customer by ID", description = "Customer must exist")
@ApiResponses(value = {
@ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
@ApiResponse(responseCode = "404", description = "Customer not found"),
@ApiResponse(responseCode = "500", description = "Internal server error",
content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = ErrorResponse.class)) }) })
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}5. <em @Operation</em> 和 <em @ApiResponse</em> 的區別
總結如下表所示,<em @Operation</em> 和 <em @ApiResponse</em> 標註的主要區別:
| 用於描述操作 | 用於描述操作的可能響應 |
| 用於成功的響應 | 用於成功的響應和錯誤響應 |
| 只能定義在方法級別 | 可以在方法級別或類級別定義 |
| 可以直接使用 | 只能在 `` 標註中使用 |
6. 結論
在本文中,我們學習了 @Operation 和 @ApiResponse 兩個註解之間的區別。