Swagger2
最近收到老大要求,需要把swagger引入,对API进行测试,并且形成文档。文档和代码可以同步更新。
于是就对Swagger2做一些记录,项目使用的是基于springboot引入的。
引入Swagger2
maven pom.xml 依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.13</version>
</dependency>
快速跳过….
添加配置的class类:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket config() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XXXXAPI文档")
.contact(new Contact("name", "API地址", "联系方式"))
.build();
}
}
basePackage(“com.xxx.controller”) 让swagger能够扫描到你的接口,也就是controller包
@Configuration 相当于配置文件xml中的 beans
@Bean 相当于配置文件xml中的 bean
以此类推,springmvc项目可以这样配置。
注解controller
例如:
@Api(description = “”) : 作用于Controller类,对整个类的描述
@ApiOperation(value=”“) : 作用于方法,对方法的描述
@ApiParam(name = “token”, value = “token”,required = true):作用于方法内的参数
@Api(description = "首页接口")
@Controller
@RequestMapping("/home")
public class HomeController {
@ApiOperation(value="首页", notes="默认参数code='xiaoyuan'")
@RequestMapping("/index")
@ResponseBody
private ResultObject index(
@ApiParam(name = "code", value = "code",required = true)
@RequestParam("code")String code){
.....
}
}
重启项目,直接请求 http://localhost:8001/v2/api-docs (端口配置自己项目设置的) 就能看到一堆json,但是这样看很挫。
使用Swagger-ui生成美丽的文档
于是Swagger-ui,转换成美丽的样式。
到githut下载Swagger-UI: https://github.com/swagger-api/swagger-ui
下载完之后找到dist/index.html,修改如下
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
//url: "http://petstore.swagger.io/v2/swagger.json", //这个是GitHub官方的
url: "http://localhost:8001/v2/api-docs", //修改如下 /v2/api-docs
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
保存之后直接打开 index.html
最后直接把这个东西丢给老大,估计不会被怼把?