Spring Boot tutorial - swagger UI

Spring Boot tutorial - swagger UI

1. What is Swagger?

Swagger Gamma The goal is to define a standard, language independent interface for REST APIs, so that people and computers can discover and understand the functions of various services without seeing the source code, documents or network traffic detection. When services are defined by swagger, consumers can interact with remote services through a small amount of implementation logic. Similar to low-level programming interfaces, swagger removes a lot of guesswork when invoking services.
browse Swagger To learn more about the Swagger project, including additional libraries that support other languages.

2. Integrate Swagger in the project

  • 2.1 introduce maven dependency

    My own project uses swagger2.

    <!--springboot Parent project-->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <dependencies>
            <!--springboot frame web assembly-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.2.2.RELEASE</version>
            </dependency>
            <!--swagger-ui assembly-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.9.2</version>
            </dependency>
            <!--swagger assembly-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
            </dependency>
            <!--mybatis integration springboot assembly-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.0</version>
            </dependency>
            <!--mysql Database connection driver-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.18</version>
            </dependency>
            <!--lombok assembly-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.10</version>
            </dependency>
        </dependencies>
    
        <build>
            <!--springboot Of maven plug-in unit-->
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <compilerArgs>
                            <arg>-parameters</arg>
                        </compilerArgs>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
  • 2.2 configuration of swagger

    SwggerConfig.java:

    package com.butterflytri.config;
    
    import com.google.common.base.Predicates;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Profile;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.ParameterBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.schema.ModelRef;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.service.Parameter;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    /**
     * @author: WJF
     * @date: 2020/5/21
     * @description: SwaggerConfig
     */
    
    /**
     * {@link Configuration}: Flag this is a configuration class. When the spring boot boot boot class starts, the configuration of this class will be loaded automatically.
     * {@link Profile}: Description load profile ' application.yml 'to load the corresponding configuration.
     * {@link EnableSwagger2}: Enable configuration for Swagger2.
     */
    @Configuration
    @Profile("dev")
    @EnableSwagger2
    public class SwaggerConfig {
    
        @Bean
        public Docket restApi() {
            Class[] classes = this.getClasses();
            Set<String> consumesSet = new HashSet<>();
            consumesSet.add("application/x-www-form-urlencoded");
            return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .globalOperationParameters(parameters())
                .ignoredParameterTypes(classes)
                .forCodeGeneration(true)
                .consumes(consumesSet)
                .select()
                .apis(Predicates.and(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)))
                .paths(PathSelectors.any())
                .build();
        }
    
        /**
         * API Basic information of the document
         * @return ApiInfo
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("Student management platform")
                    .description("Student management platform documents")
                    .termsOfServiceUrl("http://127.0.0.1:8080/butterflytri/swagger-ui.html")
                    .contact(new Contact("wjf", "http://butterflytri.com", "butterflytri@163.com"))
                    .version("2.0")
                    .build();
        }
    
        /**
         * Swagger2 You can add parameters to the Swagger2 document
         * @return List<Parameter>
         */
        private List<Parameter> parameters() {
            // Add a parameter butterflytri, Parameter Description: Immortal Butterfly
            ParameterBuilder paramBuilder = new ParameterBuilder();
            List<Parameter> paramList = new ArrayList<Parameter>();
            paramBuilder.name("butterflytri")
                    .description("Undead Butterfly")
                    .modelRef(new ModelRef("string"))
                    .parameterType("header")
                    .required(true)
                    .build();
            paramList.add(paramBuilder.build());
            return paramList;
        }
    
    
        /**
         * Get class array
         * @return Class[]
         */
        private Class[] getClasses() {
            return new Class[]{};
        }
    
    }
    
    
  • 2.3 control layer

    StudentController.java:

    package com.butterflytri.controller;
    
    import com.butterflytri.entity.Student;
    import com.butterflytri.service.StudentService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiImplicitParams;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.web.bind.annotation.*;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    /**
     * @author: WJF
     * @date: 2020/5/16
     * @description: StudentController
     */
    @Api(tags = "Student management interface")
    @RestController
    @RequestMapping("/student")
    public class StudentController {
    
        @Resource
        private StudentService studentService;
    
        /**
         * GET : Request specific resources from the server. For example: GET /student
         * @return List<Student>
         */
        @ApiOperation(value = "Query all students", httpMethod = "GET", notes = "Query all students")
        @GetMapping("/student")
        public List<Student> student() {
            return studentService.findAll();
        }
    
        /**
         * GET : Request specific resources from the server. For example: GET /student/1
         * @param id
         * @return Student
         */
        @ApiOperation(value = "Query student details", httpMethod = "GET", notes = "Query student details")
        @ApiImplicitParam(name = "id", value = "student id", required = true, paramType = "form", dataTypeClass = Long.class)
        @GetMapping("/student/{id}")
        public Student student(@PathVariable("id") Long id) {
            return studentService.findOne(id);
        }
    
        /**
         * POST : Create a new resource on the server. For example: POST /student
         * @param student
         */
        @PostMapping("/student")
        @ApiOperation(value = "Add students", httpMethod = "POST", notes = "Add students")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "studentName", value = "Student name", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "studentNo", value = "Student ID", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "sex", value = "Student gender", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "age", value = "Student age", required = true, paramType = "form", dataTypeClass = Integer.class)
        })
        public void student(@RequestBody Student student) {
            studentService.add(student);
        }
    
        /**
         * PUT : Update the resources on the server (the client provides the entire updated resources). For example: PUT /student/1 (update all information of student with student number 1)
         * @param id
         */
        @PutMapping("/student/{id}")
        @ApiOperation(value = "according to id Modify student information(large-scale)", httpMethod = "PUT", notes = "according to id Modify student information")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "id", value = "student id", required = true, paramType = "from", dataTypeClass = Long.class),
                @ApiImplicitParam(name = "studentName", value = "Student name", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "studentNo", value = "Student ID", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "sex", value = "Student gender", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "age", value = "Student age", required = true, paramType = "form", dataTypeClass = Integer.class)
        })
        public void updateById(@PathVariable("id") Long id, Student student) {
            studentService.updateAll(id,student);
        }
    
        /**
         * DELETE : Remove specific resources from the server. For example: DELETE /student/1
         * @param id
         */
        @DeleteMapping("/student/{id}")
        @ApiOperation(value = "according to id Delete student information", httpMethod = "DELETE", notes = "according to id Delete student information")
        @ApiImplicitParam(name = "id", value = "student id", required = true, paramType = "from", dataTypeClass = Long.class)
        public void deleteById(@PathVariable("id") Long id) {
            studentService.delete(id);
        }
    
        /**
         * PATCH : Update the resources on the server (the client provides the changed properties, which can be seen as part of the update). The usage is relatively small. Here is no example.
         * @param id
         * @param student
         */
        @PatchMapping("/student/{id}")
        @ApiOperation(value = "according to id Modify student information(Small scale)", httpMethod = "PATCH", notes = "according to id Modify student information")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "id", value = "student id", required = true, paramType = "from", dataTypeClass = Long.class),
                @ApiImplicitParam(name = "studentName", value = "Student name", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "studentNo", value = "Student ID", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "sex", value = "Student gender", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "age", value = "Student age", required = true, paramType = "form", dataTypeClass = Integer.class)
        })
        public void updatePart(@PathVariable("id") Long id, Student student) {
            studentService.updatePart(id,student);
        }
    
    }
    
    

    These notes are also easy to understand. I believe that you smart technical bulls will soon use them. The specific functions of these annotations can be seen from a glance, even without looking up the data. Here we explain the paramType attribute of @ ApiImplicitParam, which has the following values:

    • Header: placed in the request header, used to obtain the request header parameters. Use @ RequestHeader to receive parameters in the code.
    • query: used for parameter splicing of get requests. Use @ RequestParam to receive parameters in the code.
    • path: used to obtain the restful interface request parameters. Use @ PathVariable to receive parameters on the mapping address.
    • Body: put it in the request body and use @ RequestBody to receive parameters.
    • Form: pass parameters in the form of a form.
  • 2.4 Entity

    Student.java:

    package com.butterflytri.entity;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    
    import java.io.Serializable;
    
    /**
     * @author: WJF
     * @date: 2020/5/16
     * @description: Student
     */
    
    @ToString
    @Getter
    @Setter
    @ApiModel("student Entity")
    public class Student implements Serializable {
    
        @ApiModelProperty("student id")
        private Long id;
    
        @ApiModelProperty("Student name")
        private String studentName;
    
        @ApiModelProperty("Student ID")
        private String studentNo;
    
        @ApiModelProperty("Gender")
        private String sex;
    
        @ApiModelProperty("Age")
        private Integer age;
    
    }
    
    

    The @ ApiModelProperty annotation can be used to identify the meaning of each Entity property.

  • 2.5 operation results

    Launch project, accessing http://127.0.0.1:8080/butterflytri/swagger-ui.html You can see the following page:

    Click on the student management interface to see StudentController.java All interface methods written in:

    Click the Models below to see the Student.java Entity class:

    Then click the query method for all students, call the method, and click Try it out to test the method:

    I see a parameter butterflytri here, and it's still a required parameter, because I'm in SwaggerConfig.java This configuration file class has been configured. If you don't know, you can double up to see the configuration class.

    After clicking Try it out, assign a value to this parameter casually. Anyway, there is nothing about this parameter. It's just for demonstration. Then click execute to see the returned result:

3. Project address

Transmission gate of the project: spring-boot-swagger-ui

This tutorial will be updated all the time. If it's OK for bloggers to write, pay attention to it, and it's more convenient for them to learn next time.

Tags: Java Spring Maven Lombok

Posted on Sat, 23 May 2020 09:55:48 -0700 by YorkshireSteve