Automated document generation tool-swagger usage record

1 Reason for use

In the summer homework, the teacher wants us to use swagger to write documentation for the API.
Why do you need to document the API?

The aggregate experience of the developer when discovering, learning to use, and finally integrating with an API is termed as Developer Experience. The API documentation is the key to excellent developer experience.

2 Swagger configuration

Refer to the content of this link for use: Integration of swagger and SpringBoot project

First introduce maven dependency

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>

Then enable Swagger in the startup class of SpringBoot

@EnableSwagger2
@SpringBootApplication
public class WeiboserviceApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(WeiboserviceApplication.class, args);
    }

}

A better way is to build a seperate config class.
Here, we specify the address of the API exposed (exposed) and set the package name

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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    
    

    @Bean
    public Docket createRestApi() {
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                //apiInfo指定测试文档基本信息,这部分将在页面展示
                .apiInfo(apiInfo())
                .select()
                //apis() 控制哪些接口暴露给swagger,
                // RequestHandlerSelectors.any() 所有都暴露,会多出一个默认的error-service-controller
                // RequestHandlerSelectors.basePackage("com.info.*")  指定包位置
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    //文档的总体信息
    private ApiInfo apiInfo() {
    
    
        return new ApiInfoBuilder()
                .title("测试项目标题")
                .description("接口描述")
                //联系人实体类
                .contact(
                        new Contact("名字", "网址", "邮箱")
                )
                //版本号
                .version("1.0.0-SNAPSHOT")
                .build();
    }
}

After introducing Swagger according to the second method, the configuration is complete. You can use Postman to send a request to http://localhost:8080/v2/api-docs to test it
Local test results
. Obviously, the returned result is not the document we want. , It’s time for Swagger-ui to come into play

3 Use Swagger UI

Swagger UI github homepage

Swagger UI is a dependency-free collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation and sandbox from a Swagger-compliant API. Because Swagger UI has no dependencies, you can host it in any server environment, or on your local machine.

This article uses the 2.x version instead of the latest 3.x version, because the use scenario of 2.0 is more concise, and 3.0 is better for standardized large-scale projects

The interface description is described in Swagger 3.0 through the Swagger specification (a JSON file), and Swagger 2.0 is described by providing a series of annotations in the interface.

First introduce maven dependency

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

After the introduction, you can directly access the swagger UI page with localhost:8080 as the Base url in the browser http://localhost:8080/swagger-ui.html#/.
Without adding any comments to the controller, the default document is as follows
The default interface document of a function
Annotate the controller class. Common annotations are:

@Api(value="",tag=""): Used on a class to explain the role of the class.

@ApiOperation: Annotation to add method description to API.
Note that httpMethod must be specified here, otherwise there will be a document for each method
@ApiImplicitParams: used to include a set of parameter descriptions on the method.

@ApiImplicitParam: Used to annotate to add instructions to the method parameters.

@ApiResponses: used to represent a set of responses

@ApiResponse: Used in @ApiResponses, generally used to express an incorrect response message

code: number, such as 400

message: information, such as "request parameters are not filled in"

response: the class that threw the exception

   @ApiResponses({
        @ApiResponse(code = 1000, message = "非HTTP状态码,返回值JSON code字段值,描述:成功"),
        @ApiResponse(code = 401, message = "非HTTP状态码,返回值JSON code字段值,描述:无token")
})

@ApiModel: Describe the information of a Model (usually used when the request parameter cannot be described using the @ApiImplicitParam annotation)

@ApiModelProperty: describe the properties of a model

@CrossOrigin(origins = "*")
@RestController
@Api(value = "UserServiceControl23ler")
public class UserServiceController {
    
    


    @Autowired
    private UserService userService;

     @ApiOperation(notes = "get user info by userID", value = "get user info",httpMethod = "GET")
    @RequestMapping(path="/user/getUser")
    public User getUser(@ApiParam(name = "userId", value = "The user ID of a WeiBo user,should be a Long Integer") @RequestParam("userId") Long uid){
    
    
        System.out.println("*****getWeibo*****");
        return userService.findAllById(uid);
    }
}

The document effect after adding annotations. For small projects, these annotations are sufficient
Insert picture description here

4 matters needing attention

Swagger should send a request to the interface based on the annotation to obtain the document information to be displayed. At this time, the parameters passed in are all empty. If the backend does not handle exceptions, an error will be reported, such as

java.lang.NumberFormatException: For input string: ""

For the description of the post method, there is no easy solution for the time being, but there are many blogs who have written their own methods, you can search for it. My plan is as follows:

    @ApiOperation(notes = "deleteById", value = "delete one user", httpMethod = "POST")
    @ApiImplicitParams({
    
    
            @ApiImplicitParam(name = "nickname", value = "the nickname of the iLife user"),
            @ApiImplicitParam(name = "account", value = "the account of the iLife user"),
            @ApiImplicitParam(name = "password", value = "the password of the iLife user"),
            @ApiImplicitParam(name = "email", value = "the email of the iLife user")
    }
    )
    @RequestMapping(path = "/auth/logUp")
    public ResponseEntity<?> logUp(@ApiIgnore @RequestBody Map<String, String> params) {
    
    
        String nickname = params.get("nickname");
        String account = params.get("account");
        String password = params.get("password");
        String email = params.get("email");
        System.out.println("********** deleteById **********");
        return userService.save(nickname, account, password, email);
    }

Use param to represent the parameters to be passed in the data in the headers, and then ignore the requestBody parameter (otherwise there will be an extra black box), the operation effect is as follows
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44602409/article/details/107285187