自動生成接口文檔
一、開頭
開發的小夥伴應該會遇到這個問題吧!
項目設計階段寫的接口文檔,需求的不斷的改動,導致前期定義的接口已面目全非。如果沒有及時更新接口文檔,那麼這些接口文檔對前端開發人員將是一場災難!由於項目緊急,是沒有時間完善接口文檔,我們該如何提高前後端的開發效率呢?
解決方案一:項目集成 Swagger 插件,前端人員訪問 Swagger 生成的接口文檔,查看和使用接口。
解決方案二:項目集成 Swagger 插件,在項目打包的時候,生成 html/pdf 形式的接口文檔,供其他人使用。
解決方式三:在接口上添加一套自定義註解,指定請求 url,請求方式,請求參數,返回參數等信息,再通過前端頁面呈現。
二、實戰
1.項目集成 Swagger 依賴,訪問接口文檔
項目添加swagger 依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
啓動項目,訪問鏈接:http://localhost:8080/swagger-ui.html
2.項目集成 springfox 依賴,生成 html/pdf 形式的接口文檔
原理:項目加載 swagger 依賴後,可以生成web的接口測試頁面,訪問 /v2/api-docs 這個接口 ,會返回 json 字符串,包括所有控制類的接口的定義,然後通過 springfox 將 json 數據按照格式轉化爲 html 或者 pdf 文檔。
2.1示例代碼
在項目根目錄打包,打包命令如下:
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);
}
}
2.2運行效果
target\asciidoc\ 就是生成的文檔目錄,包括 html 和 pdf 文檔。
2.3示例項目
項目地址:https://github.com/nitianziluli/swagger2pdf
3.自定義動態生成接口文檔
原理:在對外暴露的接口上添加一套自定義註解。註解可指定接口名稱,請求 url,請求方式,請求參數,請求參數類型,返回參數,返回參數類型等信息。通過解析 controller 類上註解和方法上的註解,生成獲取所有對外暴露方法的定義的接口,然後通過 web 頁面呈現所有接口定義。
3.1示例代碼
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的文檔
}
3.2運行效果
web前端調用 /api/{type} 接口,效果如下圖:
三、最後
本文的思考來源於工作。項目接口文檔本應該就是根據代碼同時發佈的,在多加一步操作,將生成的接口文檔自動部署到服務上,就實現接口文檔的自動更新,一勞永逸!
關注我,“不安分的猿人”,一個正在搬磚的碼農!