Use swagger to manage the interface

Introduction: Swagger is a simple but powerful representation of Rest API, standard, language-independent, which is not only human-readable, but also machine-readable. It can be used as an interactive document of Rest API or as a formal interface description of Rest API to generate client and server code.

 

Combining with the more common scenarios, we will briefly discuss how to use swagger to manage interfaces under Springboot, so that front-end and back-end developers can well connect interfaces, and it is also conducive to the subsequent maintenance and development of interfaces.

 

1. Introduce the jar package required by swagger in maven:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
    </dependencies>

 

2. Specify some static resource file configurations of swagger, generally use a class to manage and maintain:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {

    @Value("${swagger2.basePackage:com.xxx}")
    private String swagger2BasePackage;
    @Value("${swagger2.title:System API Documentation}")
    private String swagger2Title;
    @Value("${swagger2.api.version:1.0}")
    private String apiVersion;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars*").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

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

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title(swagger2Title).version(apiVersion).build();
    }
}

 

3. How to use?

In this step, I will use the more common business scenarios to describe the interface:

First, the Controller layer (class) needs to be annotated like this:

@Api(value = "SWAGGER接口")
@RestController
@RequestMapping(value = "/api/swagger/user")
public class SwaggerController{
  //....
}

 

1) The request parameter corresponds to a set of String strings or a VO, and the return result is a single object

At this point, the method must have a return instead of void

eg: query a record based on input conditions

@ApiOperation(value="Get user details", notes="Get user details according to parameters")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "用户ID", dataType = "Long", paramType = "query"),
        @ApiImplicitParam(name = "name", value = "用户名字", required = true, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "age", value = "用户年龄", dataType = "Long", paramType = "query")
    })
    @RequestMapping(value="", method=RequestMethod.GET)
    @PostMapping("/find1")
    public  User find (@ModelAttribute User user) {//@ModelAttribute User user 等效于Long id, String name; Long age;
        return new User();
    }

 The User class is as follows:

//@ApiModel(value="User", description="User object")
public class User {
  @ApiModelProperty(value = "用户ID", required = true)
    private Long id;
  @ApiModelProperty(hidden = true)
    private String name;
  @ApiModelProperty(value = "User Age")
    private Long age;
  public void setId(Long id) {
    this.id = id;
  }
  public void setName(String name) {
    this.name = name;
  }
  public void setAge(Long age) {
    this.age = age;
  }
  public Long getId() {
    return id;
  }
  public String getName() {
    return name;
  }
  public Long getAge() {
    return age;
  }
    
}

 The User class is an entity composed of corresponding query conditions or query results. Each property needs to use @ApiModelProperty to describe the meaning of each field; the @ApiModel annotation on the User class can be optionally given.

 

To access the swagger interface description page, just start the project (here is springboot), and then enter http://localhost:8080/swagger-ui.html#! to access, we click the corresponding Controller and interface, we can see:



 

Paramters is the area that describes the input parameters, and Response is the description of the output. Response can be switched to Model, and you can see the specific meaning of the output fields:



 

2) The request parameters are composite, at this time they must correspond to an entity class, such as:

//@ApiModel(value="Params", description="Incoming parameters")
public class Params {
  @ApiModelProperty(name="param1", value = "参数1", required = true)
  private String param1;
  
  @ApiModelProperty(name="input", value = "输入", required = true)
  private List<Input> input;
  
  public String getParam1() {
    return param1;
  }

  public void setParam1(String param1) {
    this.param1 = param1;
  }

  public List<Input> getInput() {
    return input;
  }

  public void setInput(List<Input> input) {
    this.input = input;
  }

}

 

The return is a collection type:

@ApiOperation(value="Get user information collection", notes="Get user information collection according to the input type")
    @PostMapping("/find2")
    @ApiResponse(response = User.class, responseContainer="List", code = 200, message = "请求成功")
    public List<User> find2(@ApiParam(value="Incoming parameter type", required=true) @RequestBody Params params) {
      
      return new ArrayList<User>();
    }

 

Click the corresponding method on the ui, you can see:



 

 

It can be seen that no matter how complex the input and output are in the interface, the meaning of each attribute (field) can be clearly seen, and the interface can be tested directly with the Try it out button on the swagger ui availability.

 

Swagger can help us manage the project interface~, as well as the interface docking work between different business sides.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326163246&siteId=291194637