后端整合Swagger + Knife4j 接口文档
什么是接口文档
写接口信息的文档,每条接口包括
- 请求参数
- 响应参数
-错误码 - 接口地址
- 接口名称
- 请求类型
- 请求格式
- 备注
谁需要使用接口文档
一般是后端或者负责人来提供,前端和后端都需要使用
为什么需要接口文档
- 目的是为了有一个书面内容便于参考和查阅,便于沉淀和维护,拒绝口口相传!
- 接口文档便于前后端开发对接,前后端联调的介质。后端=> 接口文档<= 前端
- 好的接口文档支持在线调试,在线测试,可以作为工具提高我们的开发测试效率
怎么做接口文档
- 手写(比如腾讯文档、MarkDown笔记)
- 自动化接口文档生成:自动根据项目代码生成完整的文档或在线测试网页Swagger、Postman(侧重接口管理)(国外);apifox、apipost、eolink(国产)
Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化Restful风格的Web服务
第一步引入依赖
在 pom.xml 文件中添加 Swagger 的 maven 依赖:
<!--添加Swagger的依赖-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
添加配置
- 新建一个config包,添加配置类
package com.yupi.usercenter.config;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
/**
* 自定义swagger 接口文档的配置
*/
@Configuration
//开启swagger2的功能
@EnableSwagger2WebMvc
public class SwaggerConfig {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//这里一定要标注你控制器的位置
.apis(RequestHandlerSelectors.basePackage("com/yupi/usercenter/controller"))
.paths(PathSelectors.any())
.build();
}
/**
* api信息
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("bullet用户中心")
.description("接口文档")
.build();
}
}
- 启动后访问doc.html 即可
接口文档的使用技巧
如何使用Swagger
原理:
- 引入依赖(swagger 或 knife4j)
- 自定义swagger配置类
- 自定义需要生成接口文档的代码位置(Controller),千万注意:线上环境不要把接口暴露出去!!!
- 启动即可
注意:如果springboot version >= 2.6 需要添加如下配置
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER