使用 SpringFox、Swagger2Markup、Spring-Restdoc和 Maven 构建 RESTful API文档。
实现思路:
1、先利用 SpringFox 库生成实时文档;
2、再利用 Swagger2Markup,Maven插件生成 asciidoc文档;
3、最后利用 asciidoctor Maven 插件生成 html 或 pdf ;
运行环境: SpringBoot + SpringFox + Swagger2Markup + Maven
本文示例代码 下载整个 Repo 后在 springfox-rest-doc文件夹下直接运行 mvn clean package 或者 mvn clean test 后在 targ/asciidoc/ 下就可以看到 html和 pdf 文档了。
If you want to start the Spring Boot application, please run:
mvn clean package
java -jar target/spring-swagger2markup-demo-1.1.0.jar
If you only want to generate the HTML and PDF documentation, please run:
mvn clean test
The results are generated into target/asciidoc/html and target/asciidoc/pdf.
实现步骤
- SpringFox/Swagger2 生成 RESTful API:
将相关依赖引入后,新建 SwaggerConfig 类:
@EnableSwagger2 // 启用Swagger2
@Configuration
public class SwaggerConfig {
//创建Docket Bean
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 排除 error 相关的 url
.paths(Predicates.and(ant("/**"), Predicates.not(ant("/error"))))
.build()
.ignoredParameterTypes(ApiIgnore.class)
.enableUrlTemplating(true);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger API Demo")
.description("API Description")
.contact(new Contact("chang", "http:/joeychang.me", "[email protected]"))
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.version("1.0.0")
.build();
}
}
- 然后在 Controller 中添加相关的 swagger 注解:
@RestController
@RequestMapping(value = "/pets", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE, "application/x-smile"})
@Api(value = "/pets", tags = "Pets", description = "Operations about pets")
public class PetController {
PetRepository petData = new PetRepository();
@RequestMapping(method = POST)
@ApiOperation(value = "Add a new pet to the store")
@ApiResponses(value = {@ApiResponse(code = 405, message = "Invalid input")})
public ResponseEntity addPet(
@ApiParam(value = "Pet object that needs to be added to the store", required = true) @RequestBody Pet pet) {
petData.add(pet);
return Responses.ok("SUCCESS");
}
@RequestMapping(method = PUT)
@ApiOperation(value = "Update an existing pet",
authorizations = @Authorization(value = "petstore_auth", scopes = {
@AuthorizationScope(scope = "write_pets", description = ""),
@AuthorizationScope(scope = "read_pets", description = "")
}))
@ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 404, message = "Pet not found"),
@ApiResponse(code = 405, message = "Validation exception")})
public ResponseEntity updatePet(
@ApiParam(value = "Pet object that needs to be added to the store", required = true) @RequestBody Pet pet) {
petData.add(pet);
return Responses.ok("SUCCESS");
}
static class PetRepository extends MapBackedRepository {
public List findPetByStatus(String status) {
return where(Pets.statusIs(status));
}
public List findPetByTags(String tags) {
return where(Pets.tagsContain(tags));
}
}
}
启动 SpringBoot, 然后访问 localhost:port/context-path/swagger-ui.html,就能找到 API 文档页面。
- 生成 Asciidoc 片段
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@AutoConfigureRestDocs(outputDir = "build/asciidoc/snippets")
@SpringBootTest
public class Swagger2MarkupTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testAddPet() throws Exception{
this.mockMvc.perform(post("/pets/").content(createPet()).contentType(MediaType.APPLICATION_JSON))
// Spring Rest Docs 生成 Asciidoc 片段
.andDo(document("addPetUsingPOST", preprocessResponse(prettyPrint())))
.andExpect(status().isOk());
}
private String createPet() throws JsonProcessingException {
Pet pet = new Pet();
pet.setId(1);
pet.setName("Tomcat");
Category category = new Category(1l, "Cat");
pet.setCategory(category);
return new ObjectMapper().writeValueAsString(pet);
}
}
- 生成所有的 RESTful API 片段
可以通过可以通过 /v2/api-docs 获得 swagger.json,然后再通过 swagger2Markup 插件来生成 Asciidoc 文档。
@Test
public void createSpringFoxSwaggerJson() throws Exception {
//String designFirstSwaggerLocation = Swagger2MarkupTest.class.getResource("/swagger.yaml").getPath();
String outputDir = System.getProperty("io.springfox.staticdocs.outputDir"); // mvn test
// String outputDir = "D:\\workspace\\springfox-swagger2-demo\\target\\swagger"; // run as
LOG.info("--------------------outputDir: {}--------------------", outputDir);
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();
Files.createDirectories(Paths.get(outputDir));
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
writer.write(swaggerJson);
}
LOG.info("--------------------swaggerJson create --------------------");
}
运行该方法会在 /target/swagger 下生成 swagger.json 文件。接着我们就需要 swagger2markup 插件生成 Asciidoc 文件。
我们在 pom.xml 中添加好 swagger2markup 插件配置,然后运行 mvn test,BUILD 成功后会在 target\asciidoc\generated 看到生成的 asciddoc 文件。
- 生成 HTML 和 PDF
将 index.adoc(manual_content1.adoc和manual_content2.doc测试用) 放入到 src/docs/asciidoc 下, index.adoc 的内容为,意思是引入我们刚刚生成的文件:
include::{generated}/overview.adoc[]
include::manual_content1.adoc[]
include::manual_content2.adoc[]
include::{generated}/paths.adoc[]
include::{generated}/security.adoc[]
include::{generated}/definitions.adoc[]
在 pom.xml 中添加 asciidoctor 插件, 配置好后运行 mvn test,在配置的文件夹中就会生成 html 和 pdf 文档了。
结语:Maven 环境下,研究了好长时间,终于搞定,cheers
参考:
- 使用 SpringFox、Swagger2Markup、Spring-Restdoc和 Maven 构建 RESTful API文档
- https://github.com/Swagger2Markup/spring-swagger2markup-demo
- Swagger2Markup Documentation