开发的小伙伴应该会遇到这个问题吧!
项目设计阶段写的接口文档,需求的不断的改动,导致前期定义的接口已面目全非。如果没有及时更新接口文档,那么这些接口文档对前端开发人员将是一场灾难!由于项目紧急,是没有时间完善接口文档,我们该如何提高前后端的开发效率呢?
解决方案一:项目集成 Swagger 插件,前端人员访问 Swagger 生成的接口文档,查看和使用接口。
解决方案二:项目集成 Swagger 插件,在项目打包的时候,生成 html/pdf 形式的接口文档,供其他人使用。
解决方式三:在接口上添加一套自定义注解,指定请求 url,请求方式,请求参数,返回参数等信息,再通过前端页面呈现。
项目添加swagger 依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
启动项目,访问链接:http://localhost:8080/swagger-ui.html
原理:项目加载 swagger 依赖后,可以生成web的接口测试页面,访问 /v2/api-docs 这个接口 ,会返回 json 字符串,包括所有控制类的接口的定义,然后通过 springfox 将 json 数据按照格式转化为 html 或者 pdf 文档。
在项目根目录打包,打包命令如下:
mvn clean package
SwaggerConfig.java
@EnableSwagger2
@Configuration
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {
@Bean
public Docket restApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.securitySchemes(asList(
new OAuth(
"petstore_auth",
asList(new AuthorizationScope("write_pets", "modify pets in your account"),
new AuthorizationScope("read_pets", "read your pets")),
Arrays.<GrantType>asList(new ImplicitGrant(new LoginEndpoint("http://petstore.swagger.io/api/oauth/dialog"), "tokenName"))
),
new ApiKey("api_key", "api_key", "header")
))
.select()
.paths(Predicates.and(ant("/**"), Predicates.not(ant("/error")), Predicates.not(ant("/management/**")), Predicates.not(ant("/management*"))))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger Petstore")
.description("Petstore API Description")
.contact(new Contact("TestName", "http:/test-url.com", "[email protected]"))
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.version("1.0.0")
.build();
}
}
Swagger2PdfTest.java
@Test
public void createSpringfoxSwaggerJson() throws Exception {
String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
logger.info("swagger.json文件存放路径:{}", outputDir);
// 这里是生成当前项目的swagger.json
MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String swaggerJson = response.getContentAsString();
logger.info("swagger json为:{}", swaggerJson);
Files.createDirectories(Paths.get(outputDir));
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"),
StandardCharsets.UTF_8)) {
writer.write(swaggerJson);
}
}
target\asciidoc\ 就是生成的文档目录,包括 html 和 pdf 文档。
项目地址:https://github.com/nitianziluli/swagger2pdf
原理:在对外暴露的接口上添加一套自定义注解。注解可指定接口名称,请求 url,请求方式,请求参数,请求参数类型,返回参数,返回参数类型等信息。通过解析 controller 类上注解和方法上的注解,生成获取所有对外暴露方法的定义的接口,然后通过 web 页面呈现所有接口定义。
a.定义一套注解,标记controller名称,接口基本信息,接口请求参数,接口响应参数。
接口上添加注解如下:
@ApiAction(name = "获取用户信息", mapping = "/user/{id}", method = Method.GET)
@ApiReqParams(type = ParamType.URL_PARAM, value = {
@ApiParam(name = "id", dataType = DataType.STRING, defaultValue = "", description = "用户id")
})
@ApiRespParams({
@ApiParam(name = "code", dataType = DataType.NUMBER, defaultValue = "0", description = "状态编码"),
@ApiParam(name = "data", dataType = DataType.OBJECT, defaultValue = "null", description = "响应数据", object = "user"),
@ApiParam(name = "name", dataType = DataType.STRING, defaultValue = "", description = "姓名", belongTo = "user"),
@ApiParam(name = "age", dataType = DataType.NUMBER, defaultValue = "", description = "年龄", belongTo = "user"),
@ApiParam(name = "message", dataType = DataType.STRING, defaultValue = "", description = "提示信息")
})
@GetMapping("/user/{id}")
public Result getUserByIDParams(@pathvariable String id) {
return Result.success(new User("996", "毁灭你们,与你何干!", 22));
}
b.获取所有接口信息的接口
@GetMapping("/api/{type}")
public ApiDoc admin(@PathVariable("type") String type) {
//是否打开文档功能
if (openApiDoc) {
ApiDoc apiDoc = null;
//后台管理系统
if (type.equals("admin")) {
String packageName = "com.demo.web";
apiDoc = new GeneratorApiDoc() //工具类,获取所有接口信息
.setInfo(//设置文档基本信息
new ApiDocInfo()
.setTitle("某某系统后台管理文档")
.setVersion("1.0")
.setDescription("问题描述\n")
)
.generator(packageName);//指定生成哪个包下controller的文档
}
web前端调用 /api/{type} 接口,效果如下图:
项目地址:https://github.com/dakuohao/api-doc
本文的思考来源于工作。项目接口文档本应该就是根据代码同时发布的,在多加一步操作,将生成的接口文档自动部署到服务上,就实现接口文档的自动更新,一劳永逸!