1. Overview
1.概述
In this tutorial, we’ll discuss the main differences between Swagger’s @ApiOperation and @ApiResponse annotations.
在本教程中,我们将讨论Swagger的@ApiOperation和@ApiResponse注解的主要区别。
2. Descriptive Documentation With Swagger
2.使用Swagger的描述性文档
When we create a REST API, it’s important to create its proper specification as well. Additionally, such a specification should be readable, understandable, and provide all essential information.
当我们创建一个REST API时,创建其适当的规范也很重要。此外,这样的规范应该是可读的、可理解的,并提供所有必要的信息。
Moreover, the documentation should have a description of every change made on the API. It’d be exhausting and, more importantly, time-consuming to create REST API documentation manually. Fortunately, tools like Swagger can help us with this process.
此外,文档应该有对API的每一个变化的描述。手动创建REST API文档会很累,更重要的是很耗时间。幸运的是,像Swagger这样的工具可以帮助我们完成这个过程。
Swagger represents a set of open-source tools built around OpenAPI Specification. It can help us design, build, document, and consume REST APIs.
Swagger代表了围绕OpenAPI规范构建的一套开源工具。它可以帮助我们设计、构建、记录和消费REST API。。
The Swagger Specification is a standard for documenting REST APIs. Using Swagger Specification we can describe our entire API, such as exposed endpoints, operations, parameters, authentication methods, and so on.
Swagger Specification是一个记录REST API的标准。使用Swagger规范,我们可以描述我们的整个API,如暴露的端点、操作、参数、认证方法等等。
Swagger provides various annotations that can help us document REST API. Moreover, it provides the @ApiOperation and @ApiResponse annotations to document responses for our REST API. In the remainder of this tutorial, we’ll use the below controller class and see how to use these annotations:
Swagger提供了各种注解,可以帮助我们记录REST API。此外,它提供了@ApiOperation和@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. @ApiOperation
3.@ApiOperation。
The @ApiOperation annotation is used to describe a single operation. An operation is a unique combination of a path and an HTTP method.
@ApiOperation注解用于描述单个操作。一个操作是一个路径和HTTP方法的独特组合。
Additionally, using @ApiOperation, 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.
此外,使用@ApiOperation,我们可以描述一个成功的REST API调用的结果。换句话说,我们可以使用这个注解来指定一般的返回类型。
Let’s add the annotation to our method:
让我们把注解添加到我们的方法中。
@ApiOperation(value = "Gets customer by ID",
response = CustomerResponse.class,
notes = "Customer must exist")
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}
Next, we’ll go through some of the most used properties within @ApiOperation.
接下来,我们将浏览@ApiOperation中一些最常用的属性。
3.1. The value Property
3.1.value属性
The required value property contains the operation’s summary field. Simply put, it provides a short description of the operation. However, we should keep this parameter shorter than 120 characters.
要求的value属性包含操作的摘要字段。简单地说,它提供了对该操作的简短描述。然而,我们应该让这个参数短于120个字符。
Here’s how we define the value property inside the @ApiOperation annotation:
下面是我们如何在@ApiOperation注解中定义value属性。
@ApiOperation(value = "Gets customer by ID")
3.2. The notes Property
3.2.笔记属性
Using notes, we can provide more details about the operation. For instance, we can place a text describing the endpoint’s restrictions:
使用notes,我们可以提供关于操作的更多细节。例如,我们可以放置一段文字来描述端点的限制。
@ApiOperation(value = "Gets customer by ID", notes = "Customer must exist")
3.3. The response Property
3.3.response属性
The response property contains the response type of the operation. In addition, setting this property would override any automatically-derived data type. The response property defined inside the @ApiOperation annotation should contain the general response type.
response属性包含操作的响应类型。此外,设置此属性将覆盖任何自动衍生的数据类型。在@ApiOperation注解中定义的响应属性应该包含一般的响应类型。
Let’s create the class that will represent the successful response our method returns:
让我们创建一个类,它将代表我们的方法返回的成功响应。
class CustomerResponse {
private Long id;
private String firstName;
private String lastName;
// getters and setters
}
Next, let’s add the response property to our annotation:
接下来,让我们把response属性添加到我们的注释中。
@ApiOperation(value = "Gets customer by ID",
response = CustomerResponse.class,
notes = "Customer must exist")
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}
3.4. The code Property
3.4.code属性
The code property represents the HTTP status of the response code. There are several definitions of HTTP Status Codes. One of them should be used. If we don’t provide it, the default value will be 200.
code属性表示响应代码的HTTP状态。有几个HTTP状态代码的定义。应该使用其中的一个。如果我们不提供它,默认值将是200。
4. @ApiResponse
4.@ApiResponse。
It’s a common practice to return errors using HTTP status codes. We can use the @ApiResponse annotation to describe the concrete possible response of an operation.
使用HTTP状态码来返回错误是一种常见的做法。我们可以使用@ApiResponse注解来描述操作的具体可能响应。
While the @ApiOperation annotation describes an operation and a general return type, the @ApiResponse annotation describes the rest of the possible return codes.
虽然@ApiOperation注解描述了一个操作和一个一般的返回类型,但@ApiResponse注解描述了其余可能的返回代码。
Furthermore, the annotation can be applied at the method level as well as at the class level. Moreover, annotation put on the class level will be parsed only if an @ApiResponse annotation with the same code is not already defined on the method level. In other words, the method annotations have precedence over class annotations.
此外,注解可以应用在方法层,也可以应用在类层。此外,只有当具有相同代码的@ApiResponse注解尚未在方法层定义时,放在类层的注解才会被解析出来。换句话说,方法注解比类注解更有优先权。
We should use the @ApiResponse annotations within the @ApiResponses annotation, whether we have one or multiple responses. If we use this annotation directly, it will not be parsed by Swagger.
我们应该在@ApiResponses注解中使用@ApiResponse注解,无论我们有一个还是多个回应。如果我们直接使用该注解,它将不会被 Swagger 解析。
Let’s define the @ApiResponses and @ApiResponse annotations on our method:
让我们在我们的方法上定义@ApiResponses和@ApiResponse注解。
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 404, message = "Customer not found")})
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}
We can use the annotation to specify the success response as well:
我们也可以使用注解来指定成功响应。
@ApiOperation(value = "Gets customer by ID", notes = "Customer must exist")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = CustomerResponse.class),
@ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 404, message = "Customer not found"),
@ApiResponse(code = 500, message = "Internal server error", response = ErrorResponse.class)})
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}
If we specify the successful response using the @ApiResponse annotation, there’s no need to define it inside the @ApiOperation annotation.
如果我们使用@ApiResponse注解来指定成功的响应,就没有必要在@ApiOperation注解中定义它。
Now, let’s go through some of the properties used within @ApiResponse.
现在,让我们来看看@ApiResponse中使用的一些属性。
4.1. The code and message Properties
4.1.code和message属性
Both code and message properties are required parameters in the @ApiResponse annotation.
code和message属性都是@ApiResponse注解中的必要参数。
As with the code property inside the @ApiOperation annotation, it should contain the HTTP status code of the response. It’s important to mention we cannot define more than one @ApiResponse with the same code property.
与@ApiOperation注解中的code属性一样,它应该包含响应的HTTP状态代码。值得一提的是,我们不能用相同的代码属性定义一个以上的@ApiResponse。
The message property usually contains a human-readable message that goes along with the response:
消息属性通常包含一个与响应一起的人类可读的消息。
@ApiResponse(code = 400, message = "Invalid ID supplied")
4.2. The response Property
4.2.response属性
Sometimes, an endpoint uses different response types. For example, we can have one type for success response and another for error response. We can describe them using the optional response property by associating a response class with a response code.
有时,一个端点使用不同的响应类型。例如,我们可以有一种类型用于成功响应,另一种用于错误响应。我们可以使用可选的response属性来描述它们,将一个响应类与一个响应代码联系起来。
Firstly, let’s define a class that will be returned in case of an internal server error:
首先,让我们定义一个将在内部服务器错误的情况下返回的类。
class ErrorResponse {
private String error;
private String message;
// getters and setters
}
Secondly, let’s add a new @ApiResponse for internal server errors:
其次,让我们为内部服务器错误添加一个新的@ApiResponse。
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 404, message = "Customer not found"),
@ApiResponse(code = 500, message = "Internal server error", response = ErrorResponse.class)})
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
return ResponseEntity.ok(customerService.getById(id));
}
5. Differences Between @ApiOperation and @ApiResponse
5.@ApiOperation和@ApiResponse之间的差异
To sum up, the following table shows the main differences between the @ApiOperation and @ApiResponse annotations:
总而言之,下表显示了@ApiOperation和@ApiResponse注解之间的主要区别。
@ApiOperation | @ApiResponse |
---|---|
Used for describing an operation | Used for describing the possible response of an operation |
Used for a successful response | Used for successful and error responses |
Can be defined only on the method level | Can be defined on a method or class level |
Can be used directly | Can be used only within the @ApiResponses annotation |
The default code property value is 200 | Does not have a default code property value |
6. Conclusion
6.结语
In this article, we learnt the differences between the @ApiOperation and @ApiResponse annotations.
在这篇文章中,我们学习了@ApiOperation和@ApiResponse注释之间的区别。
As always, the source code for the examples is available over on GitHub.
一如既往,这些示例的源代码可在GitHub上获取。