https://cloud.tencent.com/developer/article/1332445
使用Swagger2Markup實現導出API文檔
在這篇文章中:
前言
在學會了如何使用Swagger之后,我們已經能夠輕松地為Spring MVC或SpringBoot的Web項目自動構建出API文檔了。但是,構建的文檔必須通過在項目中整合swagger-ui
、或使用單獨部署的swagger-ui
和/v2/api-docs
返回的配置信息才能展現出您所構建的API文檔。本文將在使用Swagger的基礎上,再介紹一種生成靜態API文檔的方法,以便於構建更輕量部署和使用的API文檔。 Swagger使用說明:REST API文檔工具Swagger2,以及與SpringBoot的集成
Swagger2Markup簡介
Swagger2Markup是Github上的一個開源項目。該項目主要用來將Swagger自動生成的文檔轉換成幾種流行的格式以便於靜態部署和使用,比如:AsciiDoc、Markdown、Confluence。
項目主頁:https://github.com/Swagger2Markup/swagger2markup
如何使用
在使用Swagger2Markup之前,我們先需要准備一個使用了Swagger的Web項目,REST API文檔工具Swagger2,以及與SpringBoot的集成。
生成AsciiDoc
生成AsciiDoc的方式有兩種:
- 通過Java代碼來生成
第一步:編輯pom.xml
增加需要使用的相關依賴和倉庫
<dependency> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup</artifactId> <version>1.3.3</version> </dependency> <repositories> <repository> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> <id>jcenter-releases</id> <name>jcenter</name> <url>http://jcenter.bintray.com</url> </repository> </repositories>
第二步:編寫一個單元測試用例來生成執行生成文檔的代碼
/**
* 生成AsciiDocs格式文檔
* @throws Exception
*/
@Test
public void generateAsciiDocs() throws Exception { // 輸出Ascii格式 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.ASCIIDOC) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL("http://127.0.0.1:8082/v2/api-docs")) .withConfig(config) .build() .toFolder(Paths.get("./docs/asciidoc/generated")); } /** * 生成Markdown格式文檔 * @throws Exception */ @Test public void generateMarkdownDocs() throws Exception { // 輸出Markdown格式 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.MARKDOWN) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs")) .withConfig(config) .build() .toFolder(Paths.get("./docs/markdown/generated")); } /** * 生成Confluence格式文檔 * @throws Exception */ @Test public void generateConfluenceDocs() throws Exception { // 輸出Confluence使用的格式 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs")) .withConfig(config) .build() .toFolder(Paths.get("./docs/confluence/generated")); } /** * 生成AsciiDocs格式文檔,並匯總成一個文件 * @throws Exception */ @Test public void generateAsciiDocsToFile() throws Exception { // 輸出Ascii到單文件 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.ASCIIDOC) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build()