springboot2.x basic tutorial: Swagger detailed explanation to add documentation to your interface

I believe that both front-end and back-end development have been more or less tortured by interface documents. The front end often complains that the interface documents given by the back end are inconsistent with the actual situation. The back end feels that writing and maintaining interface documents will consume a lot of energy, and it is often too late to update. In fact, whether the front end calls the back end or the back end calls the back end, a good interface document is expected.
SpringBoot integrated Swagger can clearly describe the interface through very simple annotations and generate a visual document page.
The native Swagger-ui interface is very rough, so use knife4j-spring-ui instead.

A good HTTP interface document description

  1. Write clearly the request path of the interface: QueryPath: /user/login
  2. Write clearly the request method type of the interface: GET/POST/DELETE/PUT
  3. Write clearly the business meaning of the interface and usage scenarios
  4. Write clearly the input parameters of the interface: parameter description, parameter type, parameter structure, whether the parameter must be passed
  5. Write clearly the return type of the interface: returned data structure, abnormal conditions

SpringBoot integrates Swagger

Project introduction dependency

        <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>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-ui</artifactId>
            <version>2.0.4</version>
        </dependency>

SpringBoot about Swagger configuration

Just paste this Swagger configuration into the project

@EnableSwagger2
@Configuration
public class SwaggerConfig implements WebMvcConfigurer {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
				//这里改成自己的接口包名
                .apis(RequestHandlerSelectors.basePackage("vip.codehome.springboot.tutorials.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot教程接口文档")//标题
                .description("使用swagger文档管理接口")//描述
                .contact(new Contact("codehome", "", "[email protected]"))//作者信息
                .version("1.0.0")//版本号
                .build();
    }
	//解决doc.html,swagger-ui.html 404问题
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");

    }
}

Specific use of Swagger

The role of each annotation

  1. @Api introduces the role of the class on the class
  2. @ApiOperation puts on the method to introduce the role of the method
  3. @ApiImplicitParam Introduction
  4. @ApiResponse introduces return status
  5. @ApiModel, @ApiModelProperty Introduction The input parameter is an object, and the return is an object field description

Code example

@RestController
@Api(tags = "Swagger注解测试类")
public class SwaggerUserController {
    @ApiOperation(value = "这是一个echo接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "msg",value = "请求的msg参数",required = true,paramType = "query"),
            @ApiImplicitParam(name = "token",value = "请求的token",required = false,paramType ="header" )
    })
    @ApiResponses({
            @ApiResponse(code=200,message = "请求成功"),
            @ApiResponse(code=400,message="请求无权限")
    })
    @GetMapping("/echo")
    public String echo(String msg,@RequestHeader(name = "token") String token){
        return msg;
    }
    @PostMapping("/login")
    public R<UserInfoVO> login(@RequestBody LoginDTO loginDTO){
        UserInfoVO userInfoVO=new UserInfoVO();
        userInfoVO.setNickname("编程之家");
        userInfoVO.setToken("xxx");
        return R.ok(userInfoVO);
    }
}
@Data
@ApiModel
public class LoginDTO {
    @ApiModelProperty(value = "用户账号或者邮箱")
    String account;
    @ApiModelProperty(value = "用户密码")
    String passwd;
    @ApiModelProperty(value = "用户密码")
    String verifyCode;
}

Interface document effect

The visit here is http://localhost:8080/doc.html, knife4j-spring-ui also has more powerful functions than the original ones.
A thousand miles begins with a single step. Here is the second article in the SpringBoot tutorial series. All project source codes can be downloaded on my GitHub .

Guess you like

Origin blog.csdn.net/github_35592621/article/details/108248717