How to use Swagger-UI to generate beautiful interface documents online

1. Brief introduction

Swagger is a tool set that implements the OpenAPI (OpenAPI Specification) specification. OpenAPI is a project of the Linux Foundation, which attempts to standardize the development process of RESTful services by defining a language for describing the API format or API definition.

Swagger greatly facilitates front-end and back-end developers, and everyone who has used it says yes. However, some people have not experienced swagger, and still have a hard handwriting interface document, which is troublesome and non-standard; some people have used it, but it is only dim. See how others use it directly. It's very fragmented, not systematic. I used to look like this before, only knowing to add a dependency and accessing it after starting the project: localhost: 8080 / swagger-ui.html, you can see the generated document, it is very simple.

Once I saw that there was always a basic-error-controller in the generated document. If the obsessive-compulsive disorder was committed, I wanted to get rid of it, so I took a look at the swagger configuration and recorded it here.

Official website: https://swagger.io/

See the official instructions:

The tool set included in Swagger:

  • Swagger Editor: Swagger Editor allows you to edit the OpenAPI specification in YAML in the browser and preview the document in real time.
  • Swagger UI: Swagger UI is a collection of HTML, Javascript and CSS assets that can dynamically generate beautiful documents from APIs that comply with OAS standards.
  • Swagger Codegen: Allows API client libraries (SDK generation), server stubs, and documentation to be automatically generated according to the OpenAPI specification.
  • Swagger Parser: an independent library for parsing OpenAPI definitions from Java
  • Swagger Core: Java-related libraries for creating, using, and using OpenAPI definitions
  • Swagger Inspector (free): API testing tool that allows you to verify your API and generate OpenAPI definitions from existing APIs
  • SwaggerHub (free and commercial): API design and documentation, built for teams using OpenAPI.

Second, the entry case

SpringBoot has integrated Swagger, and the API documentation of swagger can be generated using simple annotations.

1. Introduce dependencies

<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>

2. Write configuration

@Configuration
@EnableSwagger2 // Swagger的开关,表示已经启用Swagger
public class SwaggerConfig {
    @Bean
    public Docket api() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .host("localhost:8081")// 不配的话,默认当前项目端口
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select() // 选择哪些路径和api会生成document
                .apis(RequestHandlerSelectors.any())// 对所有api进行监控
//                .apis(RequestHandlerSelectors.basePackage("com.hanstrovsky.controller"))// 选择监控的package
//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))// 只监控有ApiOperation注解的接口
                //不显示错误的接口地址
                .paths(Predicates.not(PathSelectors.regex("/error.*")))//错误路径不监控
                .paths(PathSelectors.regex("/.*"))// 对根下所有路径进行监控
                .build();
        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("XXXX项目接口文档")
                .contact(new Contact("Hanstrovsky", "www.hanstrovsky.com", "[email protected]"))
                .description("这是用Swagger动态生成的接口文档")
                .termsOfServiceUrl("NO terms of service")
                .license("The Apache License, Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .version("1.0")
                .build();
    }
}

3. Start the test

Start the service, visit: http: // localhost: 8081 / swagger-ui.html

You can see the API page provided by swagger-ui for us:

You can see the interface we wrote. Click any one to see the detailed information of the interface:

You can see the detailed interface declaration, including:

  • Request method:
  • Request path
  • Request parameters
  • Response and other information

try it out!You can also test the interface by clicking in the upper right corner .

3. Common notes

In the document description just now, swagge-ui is automatically generated according to the interface, which is not detailed enough. If necessary, you can customize the interface declaration through annotations. Common notes include:

/**
 @Api:修饰整个类,描述Controller的作用
 @ApiOperation:描述一个类的一个方法,或者说一个接口
 @ApiParam:单个参数描述
 @ApiModel:用对象来接收参数
 @ApiProperty:用对象接收参数时,描述对象的一个字段
 @ApiResponse:HTTP响应其中1个描述
 @ApiResponses:HTTP响应整体描述
 @ApiIgnore:使用该注解忽略这个API
 @ApiError :发生错误返回的信息
 @ApiImplicitParam:一个请求参数
 @ApiImplicitParams:多个请求参数
 */

Examples:

@PostMapping("/people")
@ApiOperation(value = "保存人员信息")
@ApiResponses({
       @ApiResponse(code = 0, message = "保存成功"),
       @ApiResponse(code = 1, message = "保存失败")
})
public FrontResult save(
         @ApiParam(value = "保存参数", example = "")
         @RequestBody People people) {
     people.setBirthday(Timestamp.valueOf(LocalDateTime.now()));
     return new FrontResult(FrontResult.SUCCEED, "保存成功", peopleDao.save(people));
}
@Data
@ApiModel(description = "人员信息保存请求对象")
public class People {
    @ApiModelProperty(value = "人员编号")
    private Long id;
    @ApiModelProperty(value = "姓名", required = true,position = 1)
    private String name;
    @ApiModelProperty(value = "性别", required = true,position = 2)
    private String sex;
    @ApiModelProperty(value = "生日", required = true,position = 3)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Timestamp birthday;
}

View the documentation:

Four, beautify

If you feel that you are not used to it, you can use Swagger-Bootstrap-UI to replace Swagger's default UI to implement the left and right menu-style Swagger-UI to make it look more clear and clear.

1. Add dependencies

<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>

2. Restart the project

Visit http: // localhost: 8080 / doc.html :

Guess you like

Origin www.cnblogs.com/hanstrovsky/p/12725112.html