directory

  • Preface: What is Swagger
  • Getting started: just 3 easy steps
    • Load depends on
    • Add the annotation @enableOpenAPI
    • Start SpringBoot and access Swagger background interface
  • Configuration: Java-based configuration
  • Contrast Swagger2 with Swagger3
  • Source: github.com/Jalon2015/s…
  • Problem: Pothole records (to be sorted later)

preface

What Swagger is:

Swagger is the most popular API development tool that follows the OpenAPI Specification (ALSO known as OAS).

The most convenient part is that the API documentation can be synchronized with the server, that is, when the server updates an interface, the front-end API documentation can be updated in real time and can be tested online.

That way, Swagger reduces the communication barriers on the front and back end, and doesn’t have to argue over a bad interface

Before the use of cloud documents, but this third party need manual maintenance, or not too convenient

start

  1. Load depends on
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
Copy the code
  1. Add the @enableOpenAPI annotation
@EnableOpenApi
@SpringBootApplication
public class SwaggerApplication {
    public static void main(String[] args) { SpringApplication.run(SwaggerApplication.class, args); }}Copy the code
  1. Start the project, access to “http://localhost:8080/swagger-ui/index.html”

Such a simple Swagger background interface document is built;

Let’s talk about configuration and annotations

configuration

As you can see, the interface above shows a basic-error-Controller interface group by default, but we didn’t write it;

Looking in the project, we found that SpringBoot does have such a controller class inside, as follows:

By default, the @Controller Controller class is automatically added to the interface documentation

Let’s configure it ourselves, as follows:

import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
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.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(a) {
        // Configure OAS 3.0
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                // Find the class annotated with @tag and generate a corresponding group; Class for all HTTP request methods, the corresponding API interface is generated
            	// With this configuration, you can exclude controller classes that do not have @tag annotations
                .apis(RequestHandlerSelectors.withClassAnnotation(Tag.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("GPS Doc")
                .description("GPS Doc document")
                .termsOfServiceUrl("http://www.javalover.com")
                .contact(new Contact("javalover"."http://www.javalover.cn"."[email protected]"))
                .version("2.0.0") .build(); }}Copy the code

So you can’t see the basic-error-controller up there

annotations

Let’s look at the comment in Swagger2, as follows:

  • @Api: used on a controller class to describe the class

    • Tags =” A handy annotation of the information you can see on the UI that explains what this class does”
    • Value =” This parameter is meaningless and can be seen on the UI, so it is not needed”
  • ApiOperation: used in a requested method to describe the purpose of the method

    • Value =” specify the purpose of the method”
    • Notes =” Method remarks”
  • ApiImplicitParams: Used in the request method to represent a set of parameter descriptions

    • @APIIMPLICITParam: Used in the @APIIMPLicitParams annotation to specify aspects of a request parameter (annotating a specified parameter, outlining aspects of the parameter in detail, e.g., what is the parameter name? Parameter meaning, whether mandatory, etc.)
      • Name: The attribute value is the method parameter name
      • Value: Indicates the Chinese character description of a parameter
      • Required: Indicates whether the parameter must be passed
      • ParamType: Where does the parameter go
      • Header –> Get the request parameters: @requestheader
      • Query –> Get request parameters: @requestParam
      • Path (used for restful interfaces) –> Obtaining request parameters: @pathvariable
      • DataType: Parameter type, default String, other values dataType=”Integer”
      • DefaultValue: indicates the defaultValue of the parameter
  • @apiresponses: Used in a request method to represent a set of responses

    • @apiResponse: Used in @apiresponses, usually to express an incorrect response
      • Code: indicates the status code number, for example, 400
      • Message: a message, such as “request parameters are not filled in”
      • Response: Class that throws an exception
  • @ ApiModel: Used on the response class (POJO entity class) to describe a message that returns the response data (entity description that describes the REQUEST or response of the POJO class) (this is commonly used in post interface scenarios where @RequestBody is used to receive JSON data, Request parameters cannot be described using the @apiIMPLicitParam annotation.

    • @APIModelProperty: Used on POJO properties to describe the attribute description of the response class
  • @apiIgnore: Use this annotation to ignore an API or argument;

These are the notes for Swagger2, and here’s a simple comparison of Swagger3

Next we will write an interface with Swagger3’s annotation to see the effect (interspersed with Swagger2’s annotation)

  • The controller UserController. Java
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

@tag (name = "user-controller", description = "user interface ")
@RestController
public class UserController {

    // Ignore this API
    @Operation(hidden = true)
    @GetMapping("/hello")
    public String hello(a){
        return "hello";
    }

    @operation (summary = "User interface - Get user details ")
    @GetMapping("/user/detail")
    // The @parameter Parameter can be omitted. Swagger automatically recognizes the name Parameter
    // But the @parameter annotation can add some useful information such as descriptions
    public User getUser(@parameter (in = parameterin. QUERY, name = "name", description = "username ") String name){
        User user = new User();
        user.setUsername(name);
        user.setPassword("123");
        return user;
    }

    @operation (summary = "User interface - Add user ")
    @PostMapping("/user/add")
    // Where user is automatically recognized by Swagger
    public User addUser(@RequestBody User user){
        System.out.println("Add user");
        returnuser; }}Copy the code

Entity class user.java:


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@Schema
@Data
public class User {

    @schema (name = "username", description = "username", example = "javalover")
    private String username;

    @schema (name = "password", description = "password", example = "123456")
    private String password;

    // Hide this property so that it is not visible in the request parameters of the interface document
    @Schema(hidden = true)
    private String email;

}

Copy the code

After startup, the operating interface is as follows:

  • Home page display:

  • /user/add Interface display:

  • /user/detail Interface display

The source code

On Github: github.com/Jalon2015/s…

The problem

At present, I have simply experienced it. In fact, there are still many pits in it. I will sort them out later when I have time.

  • The @paramters parameter is invalid
  • The @apiIMPLicitParamter body property is invalid
  • @tag name attribute: If the name attribute is not in the lower case hyphen format of the current class name, it is recognized as a separate interface group
  • , etc.

The latest IDEA activation code can be obtained by replying “activation code” in the background.