Learn Swagger enum step by step: from beginner to proficient

enum is a way of defining enumeration types in the Swagger specification. It allows developers to explicitly list the parameters, return values, or enumeration values ​​acceptable in the request body of the interface in the API documentation. By using Swagger enum, developers can describe API input and output more clearly, improving the readability and maintainability of API documentation.

enum usage scene

Using the Swagger enum functionality makes a lot of sense in the following situations:

  1. WhenAPI interface has predefined enumeration values ​​for parameters or return values, use Swagger enum to clearly inform users of their options Options.
  2. When an API interface has multiple possible states, using Swagger enum can reduce the number of times developers need to view the API source code, thereby understanding the usage of the API faster.
  3. When a development architecture with front-end and back-end separation is used, Swagger enum can serve as a convention for unified enumeration values ​​between back-end developers and front-end developers.

enum Usage explanation

In Swagger specifications, use the enum keyword to define enumeration values. For example, we can use enum in the parameter definition to explicitly specify optional values ​​for the parameter:

parameters:
  - name: status
    in: query
    required: true
    type: string
    enum:
      - active
      - inactive

In this example, the only possible values ​​for the status parameter are active or inactive.

Practical cases

When using the Swagger Editor to edit and run Swagger definitions, you can use the following example to use a Swagger enum within an enumeration type:

swagger: "2.0"
info:
  title: Example API
  version: 1.0.0

paths:
  /pets:
    post:
      summary: Add a new pet to the store
      parameters:
        - name: petSize
          in: query
          description: The size of the pet
          required: true
          type: string
          enum:
            - small
            - medium
            - large
      responses:
        200:
          description: OK

InSwagger Editor, paste the above text into the editor, you will see that the Swagger UI on the right will display your API. You can try sending a request to see the effect.

When you send a POST request to /pets, you will need to pass the value of petSize in the query parameter. Try setting petSize to a value other than small, medium, or large and send ask. You'll see that the Swagger UI will indicate that your request is invalid and explicitly list the optional enumeration values ​​in the documentation.

This example can be run and tested in the Swagger Editor to demonstrate how Swagger enums are used.

Configure annotations in SpringBoot

In Spring Boot, you can use@ApiModelProperty annotations to configure Swagger enumeration types.

First, make sure you add the Swagger dependency to your project. Add the following dependencies in the pom.xml file:

 
 
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

Next, use the @ApiModelProperty annotation on your enumeration field to configure it. For example, suppose you have an entity class named Pet that contains a size field that uses an enumeration type:

import io.swagger.annotations.ApiModelProperty;

public class Pet {
    @ApiModelProperty(value = "The size of the pet", allowableValues = "SMALL, MEDIUM, LARGE")
    private Size size;

    // ...
}

In the above example, we used the @ApiModelProperty annotation to specify the description and optional values ​​of the field. The allowableValues attribute is used to specify optional enumeration values, each value separated by commas.

Then, use@ApiModel annotation to configure the entity class:

import io.swagger.annotations.ApiModel;

@ApiModel(description = "Pet entity")
public class Pet {
    // ...
}

Next, configure Swagger’s Docket Bean to enable Swagger and set related configurations. In your Spring Boot application main class, add the following code:

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class YourApplication {

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build();
    }
}

The above code configures a Docket Bean namedapi to enable Swagger and sets conditions to scan all request handlers and paths.

Then, start your Spring Boot application and access the Swagger UI interface (usually http://localhost:8080/swagger-ui.html). You will see that your enum type field displays optional enumeration values.

Precautions

You need to pay attention to the following points when using Swagger enum:

  1. Enumeration values ​​should be unique and descriptive so that developers can easily understand the meaning of each option.
  2. When the number of enumeration values ​​is large, it is recommended to define it as a separate class to improve readability.
  3. When modifying an enumeration value, you need to ensure that API users also update the corresponding enumeration value simultaneously.

Frequently Asked Questions and Solutions

  • Incorrect enumeration value definition causes interface call to fail: Please ensure that the values ​​used in the enumeration definition are consistent with the interface definition.
  • The values ​​in the enumeration class are inconsistent with the actual application: please make sure to update the API interface synchronously when modifying the enumeration class.

Swagger and Apifox integration

You can automatically synchronize Swagger annotations to IDEAApifox, generate interface documents with one click, and synchronize multiple terminals, which is very convenient for testing and maintenance. In this way, you can quickly share the API with other friends.

Apifox's IDEA plug-in can automatically parse code comments and generate API documentation based on Javadoc, KDoc and ScalaDoc. With the Apifox Helper plugin for IntelliJ IDEA, developers can synchronize their documents with Apifox projects without switching tools.

When there is a change in the interface information in the IDEA project, you only need to right-click "Upload to Apifox" to complete the synchronization without running around to tell the news. Team members can see the latest synchronized content in Apifox.

Knowledge expansion:

Reference links:

Swagger official documentation introduces enum:Enums

Guess you like

Origin blog.csdn.net/LiamHong_/article/details/134333319