Swagger 中的 @Operation 和 @ApiResponse 注解

1、概览

本文将带你了解 Swagger 中 @Operation@ApiResponse 注解的主要区别和应用场景。

2、用 Swagger 生成文档

Swagger 是一套围绕 OpenAPI 规范构建的开源工具,用于描述整个 API,如暴露的端点、操作、参数、验证方法等。

Swagger 提供了 @Operation@ApiResponse 注解,用于描述 REST API,以及 REST API 的响应。

定义一个示例 Controller:

@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

@Operation 注解用于描述单个操作。

@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、summary 属性

summary 属性必填,表示摘要。建议字符数量不要太长,示例如下:

@Operation(summary= "Gets customer by ID")

3.2、description 属性

description 属性用于描述细节,例如可以通过此属性介绍该 API 的限制、返回值等等。

@Operation(summary= "Gets customer by ID", description= "Customer must exist")

3.3、hidden 属性

hidden 属性表示是否隐藏此 API。

4、@ApiResponse

通常,不同的业务状态会返回不同的 HTTP 状态码,可以使用 @ApiResponse 注解来描述该 API 可能会返回的具体响应和状态码。

该注解既可应用于方法上,也可应用于类上,方法上的注解优先于类上注解。

注意,不论是一个 @ApiResponse 还是多个 @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、responseCodedescription 属性

responseCodedescription 属性都是 @ApiResponse 注解中的必填参数。表示响应的 http 状态码和描述。注意,同一个 API 上不能定义多个具有相同 code 属性的 @ApiResponse

message 属性通常用于设置一些描述性信息:

@ApiResponse(responseCode = 400, message = "Invalid ID supplied")

4.2、content 属性

有时,API 会响应不同的类型。例如成功和失败的时候,返回的类型可能不一致。

此时,你可以通过定义不同的 content 属性,来描述不同的响应类型。

如,定义一个在内部服务器出错时响应的类:

class ErrorResponse {

    private String error;
    private String message;

    // Get 和 Set 方法省略
}

然后,为其添加一个新的 @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、@Operation@ApiResponse 之间的区别

@Operation@ApiResponse 注解之间的主要区别如下表:

@Operation @ApiResponse
用于描述操作 用于描述操作可能返回的响应
用于成功响应 用于成功和错误响应
只能在方法上定义 可在方法或类上上定义
可直接使用 只能在 @ApiResponses 注解中使用

6、总结

在本文中,我们学习了 Swagger 中 @Operation@ApiResponse 注解之间的区别和各自的用法。


总结:https://www.baeldung.com/swagger-operation-vs-apiresponse