Beautification of OpenAPI specification 3-Swagger2

background

I use swagger2 0. In view of the appearance value and OpenAPI specification, I want to experience and supplement the demo of various situations later.

1, What is swagger?

Open API specification (OAS) is a project of Linux foundation, which attempts to standardize the development process of Restful services by defining a language to describe API format or API definition. Current v3 Version 0 of the OpenAPI Specification (i.e. swagger v2.0 specification) has been released and open source on github. Swagger2 0 is an OAS3.0 based on The Apache License, Version 2.0 0 implementation.

2, Why use Swagger to manage projects (Swagger feature)?

Swagger tools provides multiple module user construction documents. Different modules have different functions. The main modules are as follows:

1. Design interface

Swagger Editor: a powerful editor to design new APIs or edit existing APIs, which can visually present your arrogant definitions and provide real-time error feedback. Data types in json and yaml (generally yaml) formats can be supported. As shown below:

2. Build

Build and enable the programming language of OAS/Swagger by generating server stub and client sdk from swagger specification.

3,Swagger UI

Swagger needs to configure the relevant information of the interface in the background and display the information through the Swagger UI in the way of annotation, which automatically generates all documents described in the OAS specification for visual interaction. Therefore, the advantage is that it is real-time and reduces communication; The disadvantage also lies in the way of annotation, which is too deep to interact with the code itself.

3, Swagger ui2 Implementation of 0

1. Introducing maven dependency

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

2. Swagger configuration and static configuration

  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.ComponentScan;  
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;  
  
  
import springfox.documentation.builders.ApiInfoBuilder;  
import springfox.documentation.builders.PathSelectors;  
import springfox.documentation.builders.RequestHandlerSelectors;  
import springfox.documentation.service.ApiInfo;  
import springfox.documentation.spi.DocumentationType;  
import springfox.documentation.spring.web.plugins.Docket;  
import springfox.documentation.swagger2.annotations.EnableSwagger2;  
/* 
 * Restful API Access path: 
 * http://IP:port/{context-path}/swagger-ui.html 
 * eg:http://localhost:8080/vrworldapi/api/swagger-ui.html 
 */
@Component
@EnableSwagger2  
@ComponentScan(basePackages = {"gevek.vr.controller"})
@Configuration
public class RestApiConfig extends WebMvcConfigurationSupport{
  
    @Bean  
    public Docket createRestApi() {  
        return new Docket(DocumentationType.SWAGGER_2) 
          .apiInfo(apiInfo())  
          /*.groupName("User data module ")*/
          .genericModelSubstitutes(DeferredResult.class)
//              .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(false)
                .select()
                .apis(RequestHandlerSelectors.basePackage("gevek.vr.controller"))
                .paths(PathSelectors.any())  
                .build();  
    }  
  
    private ApiInfo apiInfo() {  
        return new ApiInfoBuilder()  
                .title("XXXXRESTful APIs")
                .termsOfServiceUrl("http://www.lfly.com")  
                .contact("XXXX")  
                .version("1.1")
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .build();  
    }  
    
    @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/");
 }
} 

3. Configuring Controller with annotations

In the core part, you need to configure all the information of the OpenAPI specification for each interface. Common notes are as follows (see the official website for specific configuration parameters): @ Api: modifies the whole class and describes the role of Controller

Annotation name

describe

@ApiOperation

Describe a method or interface of a class

@ApiOperation:

Describe a method or interface of a class

@ApiParam:

Single parameter description

@ApiModel:

Receive parameters with objects

@ApiProperty:

When receiving parameters with an object, a field describing the object

@ApiResponse:

One description of the HTTP response

@ApiResponses:

Overall description of HTTP response

@ApiIgnore:

Use this annotation to ignore this API

@ApiClass

@ApiError

@ApiErrors

@ApiParamImplicit

@ApiParamsImplicit

4. Effect

The specific parameter information of each interface is as follows:

4, Extension of Swagger UI

The annotation based on swagger describes the API path, description, parameters, return values, exceptions, etc. the swagger UI module is just a front-end rendering framework. Because of the default UI style of swagger, although the API files based on other methods are very good, the page is still not particularly beautiful. As a result, frameworks such as swagger UI layer and swagger bootstrap UI appear. Their essence is only the implementation of a more friendly and beautiful front-end UI interface. The parsed data comes from / V2 / API docs, while the bottom layer still depends on swagger's annotation function.

1,swagger-ui-layer

In POM Swagger, swagger UI layer and dependencies are introduced into XML. Others are consistent with swagger2. maven dependencies are as follows:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>com.github.caspar-chen</groupId>
    <artifactId>swagger-ui-layer</artifactId>
    <version>0.0.2</version>
</dependency>
 

It should be noted that the default address of the swagger api is / V2 / api docs, so the swagger ui layer also reads the default address, so the group parameter cannot be specified when new Docket(). Otherwise, the address of the swagger api will be added with the group parameter later, resulting in the inability of the swagger ui layer to correctly request data. That is, using the customized ui, you can't split APIs of the same type using the grouping function. The default access address of swagger ui layer is http: / / {host}: {port} / docs HTML, and the beautified interface is as follows:

and

2,Swagger-Bootstrap-UI

Swagger bootstrap UI is roughly the same as swagger UI layer, and the dependencies to be introduced are as follows:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.6</version>
</dependency>

The default access address of swagger bootstrap UI is http: / / {host}: {port} / doc html

It should be noted that the request address given by swagger encapsulation is / V2 / API docs by default, so the background of swagger bootstrap UI call is also / V2 / API docs, without suffix, and needs to return json format data. If the framework is spring boot, it can be used directly without modification. If it is Spring MVC on the web If DispatcherServlet is configured in XML, a url matching rule needs to be added, as follows:

<servlet>
    <servlet-name>cmsMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/spring.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
 
<!--Default configuration,.htm|.do|.json Etc. configuration-->
<servlet-mapping>
    <servlet-name>cmsMvc</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
<!-- to configure swagger-bootstrap-ui of url Request path-->
<servlet-mapping>
    <servlet-name>cmsMvc</servlet-name>
    <url-pattern>/v2/api-docs</url-pattern>
</servlet-mapping>
 

The renderings are as follows:

Added by r4ck4 on Tue, 25 Jan 2022 12:53:36 +0200