Document Enum in Swagger – Swagger中的文档枚举

最后修改: 2022年 2月 19日

1. Overview

1.概述

In this tutorial, we’ll learn how to document enum in Swagger using the swagger-maven-plugin and verify the generated JSON document in the swagger editor.

在本教程中,我们将学习如何使用swagger-maven-plugin在Swagger中记录enum,并在Swagger编辑器中验证生成的JSON文档。

2. What Is Swagger?

2. What Is Swagger?

A Swagger is an open-source tool for defining rest-based APIs. In today’s world, most organizations are moving towards microservices and API first approach. Swagger comes in very handy for designing as well as documenting APIs. It also provides various tools like Swagger Editor, Swagger UI, and Swagger CodeGen to assist API development.

Swagger是一个开源的工具,用于定义基于rest的API。在当今世界,大多数组织都在向微服务和API优先的方法发展。Swagger在设计和记录API时非常方便。它还提供各种工具,如Swagger编辑器、Swagger UI和Swagger CodeGen,以协助API开发。

Also, Swagger is an implementation of OpenAPI specifications or OAS, which defines the set of standards for rest API development; consequently, it helps organizations across the globe to standardize the process of writing APIs.

另外,Swagger是OpenAPI规范或OAS的实施,它定义了一套休息API开发的标准;因此,它帮助全球的组织规范了编写API的过程。

The JSON file generated by our application will also follow the OpenAPI specifications.

我们的应用程序生成的JSON文件也将遵循OpenAPI规范。

Let’s try to understand the importance of Enum in Swagger. Some APIs need the user to stick with a specific set of pre-defined values. These pre-defined constant values are called enum. Similarly, when Swagger exposes APIs, we want to ensure that the user selects a value from this pre-defined set rather than free text. In other words, we need to document enums in our swagger.json file so that the user is aware of the possible values.

让我们试着理解Swagger中Enum的重要性。有些API需要用户坚持使用一组特定的预定义值。这些预定义的常量值被称为enum。同样地,当Swagger公开API时,我们希望确保用户从这个预定义的集合中选择一个值而不是自由文本。换句话说,我们需要在swagger.json文件中记录enum,以便用户了解可能的值。

3. Implementation

3.实施

Let’s take an example of a REST API and jump to the implementation. We’ll implement a POST API to hire employees for an organization for specific roles. However, a role can only be one of the following: Engineer, Clerk, Driver, or Janitor.

让我们举一个REST API的例子,然后跳到实现。我们将实现一个POST API,为一个组织雇用特定角色的员工。然而,一个角色只能是以下的一个。工程师职员司机、或清洁工

We’ll create an enum named Role with all the possible values of employee role and create a class Employee having a role as one of its properties. Let’s have a look at the UML diagram for a better understanding of the classes and their relationship:

我们将创建一个名为Role的枚举,包含雇员角色的所有可能值,并创建一个将角色作为其属性之一的Employee类。让我们看一下UML图,以便更好地理解这些类和它们的关系。

UML Diagram HireController

To document this in Swagger, firstly, we’ll import and configure the swagger-maven-plugin in our application. Secondly, we’ll add required annotations to our code, and finally, we’ll build the project and verify the generated swagger document or swagger.json in the swagger editor.

为了用Swagger记录,首先,我们要在应用程序中导入并配置swagger-maven-plugin。其次,我们将在代码中添加所需的注释,最后,我们将构建项目并在swagger编辑器中验证生成的swagger文档或swagger.json

3.1. Import and Configure Plugin

3.1.导入和配置插件

We’re going to use swagger-maven-plugin, and we need to add it as a dependency to the pom.xml of our application:

我们将使用swagger-maven-plugin,我们需要将其作为依赖项添加到我们应用程序的pom.xml

<dependency>
    <groupId>com.github.kongchen</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>3.1.1</version>
</dependency>

Also, to configure and enable this plugin, we’ll add it under the plugins section of the pom.xml:

另外,为了配置和启用这个插件,我们将在pom.xml的插件部分添加它。

  • locations: This tag specifies the packages or classes containing @Api separated by a semi-colon
  • info: This tag provides metadata for the APIs. Swagger-ui uses this data to display information
  • swaggerDirectory: This tag defines the path of the swagger.json file
<plugin>
    <groupId>com.github.kongchen</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>3.1.1</version>
    <configuration>
        <apiSources>
            <apiSource>
                <springmvc>false</springmvc>
                <locations>com.baeldung.swaggerenums.controller</locations>
                <schemes>http,https</schemes>
                <host>baeldung.com</host>
                <basePath>/api</basePath>
                <info>
                    <title>Baeldung - Document Enum</title>
                    <version>v1</version>
                    <description>This is a Baeldung Document Enum Sample Code</description>
                    <contact>
                        <email>pmurria@baeldung.com</email>
                        <name>Test</name>
                    </contact>
                    <license>
                        <url>https://www.apache.org/licenses/LICENSE-2.0.html</url>
                        <name>Apache 2.0</name>
                    </license>
                </info>
                <swaggerDirectory>generated/swagger-ui</swaggerDirectory>
            </apiSource>
        </apiSources>
    </configuration>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
     </executions>
 </plugin>

3.2. Documenting an Enum

3.2.记录一个枚举

In order to document an enum in Swagger, we need to declare the models using annotation @ApiModel.

为了在Swagger中记录一个枚举,我们需要使用注解@ApiModel.来声明模型。

In this example, we created an enum Role with four possible values – Engineer, Clerk, Driver, and Janitor. As we need to document this enum, we’ll add @ApiModel to the enum Role. In other words, this will let the Swagger know about the presence of the model. In the Employee class, we’ll annotate the Employee with @ApiModel and Role with @ApiModelProperty.

在这个例子中,我们创建了一个枚举Role,有四个可能的值–工程师、职员、司机和清洁工。由于我们需要记录这个枚举,我们将把@ApiModel添加到枚举Role中。换句话说,这将让Swagger知道这个模型的存在。在Employee类中,我们将用@ApiModelRole来注释@ApiModelProperty

Our Employee, Role, and HireController will look like:

我们的Employee,Role,HireController将看起来像。

@ApiModel
public class Employee {
    @ApiModelProperty
    public Role role;

   // standard setters and getters
}
@ApiModel
public enum Role {
    Engineer, Clerk, Driver, Janitor;
}

Next, we’ll create an API with @Path as “/hire” and use the Employee model as an input parameter to the hireEmployee method. We have to add @Api to our HireController so that the swagger-maven-plugin is aware and should consider it for documenting:

接下来,我们将创建一个API,将@Path设为“/hire”,将Employee模型作为hireEmployee方法的输入参数。我们必须在HireController中添加@Api,这样swagger-maven-plugin就会知道,并应考虑将其写入文档。

@Api
@Path(value="/hire")
@Produces({"application/json"})
public class HireController {

    @POST
    @ApiOperation(value = "This method is used to hire employee with a specific role")
    public String hireEmployee(@ApiParam(value = "role", required = true) Employee employee) {
        return String.format("Hired for role: %s", employee.role.name());
    }
}

3.3. Generating the Swagger Document

3.3.生成Swagger文档

To build our project and generate a swagger document, run the following command:

为了构建我们的项目并生成一个swagger文档,运行以下命令。

mvn clean install

mvn clean install

Once built, the plugin will generate the swagger.json file at generated/swagger-ui or at the location configured in the plugin. Looking under the definitions, we’ll see the enum Role documented inside the employee properties with all its possible values.

一旦构建完成,该插件将在generated/swagger-ui或在插件中配置的位置生成swagger.json文件。在定义下,我们会看到雇员属性中记录的枚举Role及其所有可能的值。

"definitions" : {
  "Employee" : {
    "type" : "object",
    "properties" : {
      "role" : {
        "type" : "string",
        "enum" : [ "Engineer", "Clerk", "Driver", "Janitor" ]
      }
    }
  }
}

Now, we’ll visualize the generated JSON using the online swagger editor and look for the enum Role:

现在,我们将使用在线swagger编辑器来可视化生成的JSON,并寻找枚举Role

Swagger Editor

Swagger Editor

4. Conclusion

4.总结

In this tutorial, we discussed what Swagger is and learned about the OpenAPI specification and its importance in API development for organizations. Also, we created and documented our sample API containing enum using the swagger-maven-plugin. Finally, to validate the output, we used the swagger editor to visualize the generated JSON document.

在本教程中,我们讨论了什么是Swagger,并了解了OpenAPI规范及其对组织的API开发的重要性。同时,我们使用swagger-maven-plugin创建并记录了包含枚举的样本API。最后,为了验证输出结果,我们使用swagger编辑器对生成的JSON文档进行了可视化。

This implementation can be found over on GitHub.

这个实现可以在GitHub上找到over。