Spring Boot2 tutorial series (four) | Swagger2 build powerful integrated RESTful API documentation

Swagger2

Foreword

New Year approached, you do not know Shashi Hou annual leave, you busy. Anyway, I was very busy, so there is time to write blog. Today bring to you the tutorial SpringBoot integrated Swagger2.

What is Swagger2

Swagger is a standardized and complete framework for generating, description, and visualization calls for RESTful Web services.

Why Swagger2?

I believe the beginning are not familiar with web development when we have the handwritten document Api time. The handwritten document Api pain mainly in the following points:

  1. Documentation needs to be updated, need to send a copy to the front again, that is not timely exchange of documentation updates.
  2. Interface returns the result is not clear.
  3. Can not direct online test interface, usually requires the use of tools, such as postman.
  4. Too many interface documentation, bad management.

These pain points on the trailing edge separating the first large-scale project is particularly irritable. The Swagger2 appears just to solving these pain points. Because Swagger2 has the following features:

  1. The document is automatically updated, as long Api generated URL has not changed, the basic need to communicate with the front end.
  2. Interface returns the results very clear, including data types, status codes, error information.
  3. You can direct online test documents, but also give you an example.
  4. You can use to configure only once, after which there will be a long interface documentation, very easy to manage.

Integrated demo

First create a new SpringBoot project, I will not reference this old article - how to use the IDEA project to build Spring Boot

When building, the choice depends on that step check Web, LomBok, JPA, and Mysql dependence. Mysql hook which can not, because I am here for the actual operation of the database, so I checked.

Pom SpringBoot dependent files generated as follows: As used herein, the Swagger2 version 2.4.0.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.nasus</groupId>
    <artifactId>swagger2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>swagger2</name>
    <description>Demo project for Swagger2</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

The second step, in SpringBoot start class (Application) in the same directory create a new configuration class Swagger, attention Swagger2 configuration class must be in the same level with the project directory entry class Application, or failure to generate Api document, as follows:

package com.nasus;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Project Name:swagger2-demo <br/>
 * Package Name:com.nasus <br/>
 * Date:2019/1/22 22:52 <br/>
 * <b>Description:</b> TODO: 描述该类的作用 <br/>
 *
 * @author <a href="[email protected]">nasus</a><br/>
 * Copyright Notice =========================================================
 * This file contains proprietary information of Eastcom Technologies Co. Ltd.
 * Copying or reproduction without prior written approval is prohibited.
 * Copyright (c) 2019 =======================================================
 */
@Configuration
// 启用 Swagger2
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 文档信息对象
                .apiInfo(apiInfo())
                .select()
                // 被注解的包路径
                .apis(RequestHandlerSelectors.basePackage("com.nasus.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 标题
                .title("springboot 利用 swagger 构建 API 文档")
                // Api 文档描述
                .description("简单优雅的 restful 风格,https://blog.csdn.net/turodog/")

                .termsOfServiceUrl("https://blog.csdn.net/turodog/")
                // 文档作者信息
                .contact(new Contact("陈志远", "https://github.com/turoDog", "[email protected]"))
                // 文档版本
                .version("1.0")
                .build();
    }
}

The third step, annotated Controller class configuration, each write request parameter interface, returns the result, the interface description, etc., as follows:

package com.nasus.controller;

import com.nasus.entity.Student;
import com.nasus.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

/**
 * Project Name:swagger2-demo <br/>
 * Package Name:com.nasus.controller <br/>
 * Date:2019/1/22 22:07 <br/>
 * <b>Description:</b> TODO: 描述该类的作用 <br/>
 *
 * @author <a href="[email protected]">nasus</a><br/>
 * Copyright Notice =========================================================
 * This file contains proprietary information of Eastcom Technologies Co. Ltd.
 * Copying or reproduction without prior written approval is prohibited.
 * Copyright (c) 2019 =======================================================
 */
@RestController
@RequestMapping("/student")
// @Api:修饰整个类,描述Controller的作用
@Api("StudentController Api 接口文档")
public class StudentController {

    @Autowired
    private StudentService studentService;

    // @ApiOperation:描述一个类的一个方法,或者说一个接口
    @ApiOperation(value="获取所有学生列表", notes="获取所有学生列表")
    @RequestMapping(value={""}, method= RequestMethod.GET)
    public List<Student> getStudent() {
        List<Student> list = studentService.findAll();
        return list;
    }

    @ApiOperation(value="添加学生信息", notes="添加学生信息")
    // @ApiImplicitParam:一个请求参数
    @ApiImplicitParam(name = "student", value = "学生信息详细实体", required = true, dataType = "Student")
    @PostMapping("/save")
    public Student save(@RequestBody Student student){
        return studentService.save(student);
    }

    @ApiOperation(value="获学生信息", notes="根据url的id来获取学生详细信息")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer",paramType = "path")
    @GetMapping("/{id}")
    public Student findById(@PathVariable("id") Integer id){
        return studentService.findById(id);
    }

    @ApiOperation(value="删除学生", notes="根据url的id来指定删除的学生")
    @ApiImplicitParam(name = "id", value = "学生ID", required = true, dataType = "Integer",paramType = "path")
    @DeleteMapping("/{id}")
    public String deleteById(@PathVariable("id") Integer id){
        studentService.delete(id);
        return "success";
    }

    @ApiOperation(value="更新学生信息", notes="根据url的id来指定更新学生信息")
    // @ApiImplicitParams:多个请求参数
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "学生ID", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "student", value = "学生实体student", required = true, dataType = "Student")
    })
    @PutMapping(value="/{id}")
    public String updateStudent(@PathVariable Integer id, @RequestBody Student student) {
        Student oldStudent = this.findById(id);
        oldStudent.setId(student.getId());
        oldStudent.setName(student.getName());
        oldStudent.setAge(student.getAge());
        studentService.save(oldStudent);
        return "success";
    }

    // 使用该注解忽略这个API
    @ApiIgnore
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String  jsonTest() {
        return " hi you!";
    }
}

The fourth step is to start the project, visit http: // localhost: 8080 / swagger-ui.html address, results as shown below:

operation result

Project source code

github

Graphical interfaces

Parameter Description

Parameter Description

Test Results

Swagger2 common comment Profile

@ApiOperation:用在方法上,说明方法的作用
  1.value: 表示接口名称
  2.notes: 表示接口详细描述 
@ApiImplicitParams:用在方法上包含一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
  1.paramType:参数位置
  2.header 对应注解:@RequestHeader
  3.query 对应注解:@RequestParam
  4.path  对应注解: @PathVariable
  5.body 对应注解: @RequestBody
  6.name:参数名
  7.dataType:参数类型
  8.required:参数是否必须传
  9.value:参数的描述
  10.defaultValue:参数的默认值
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
  1.code:状态码
  2.message:返回自定义信息
  3.response:抛出异常的类
@ApiIgnore: 表示该接口函数不对swagger2开放展示
@Api:修饰整个类,描述Controller的作用
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息

Precautions

paramType attributes of @ApiImplicitParam annotation, will affect the test interface if provided with spring property annotations do not correspond, it will not obtain parameters, e.g. paramType = path, but using the @RequestParam annotation function, so, may get less than parameters passed in, you need to follow the above correspondence, notes the @RequestParam changed @PathVariable to get to the corresponding parameter.

Afterword

If you see here, that you liked this article, please forward, thumbs up. Micro-channel search " a good basket case ", after concerns reply " 1024 " will give you a complete set of java tutorial.

Tutorial excerpt

Guess you like

Origin www.cnblogs.com/nasus/p/12149642.html