使用 SpringFox、Swagger2Markup、Spring-Restdoc和 Maven 构建 RESTful API文档

转: 使用 SpringFox、Swagger2Markup、Spring-Restdoc和 Maven 构建 RESTful API文档

有时候我们的的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发、Android开发或是前端开发等。为了减少与其他团队平时开发期间的频繁沟通成本,我们需要构造相应的开发文档进行说明。利用传统的方法构造的文档即耗时耗力,利用Swagger生成的API文档可以实时预览,而且可以实时更新。
本文主要内容是:

  • 先利用 SpringFox 库生成实时文档;
  • 再利用 Swagger2Markup Maven插件生成 asciidoc 文档;
  • 最后利用 asciidoctor Maven插件生成 htmlpdf 文件;

环境: SpringBoot + SpringFox + Swagger2Markup + Maven

本文示例代码:点我
下载整个 Repo 后在 springfox-rest-doc 文件夹下直接运行 mvn clean package 后在 targ/asciidoc/ 下就可以看到 htmlpdf 文档了。

SpringFox/Swagger2 生成 RESTful API

Swagger is The World’s Most Popular Framework for APIs,可以自动生成 RESTFUL 接口文档,并且可以进行在线测试。SpringFox 则集成了 Swagger 与 SpringMVC,有了 SpringFox 我们可以在 Spring 项目中轻松的生成 Controller 的相关 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 Petstore")
                .description("Petstore API Description")
                .contact(new Contact("leongfeng", "http:/test-url.com", "leongfeng@163.com"))
                .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<String> 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<String> 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<Long, Pet> {
    public List<Pet> findPetByStatus(String status) {
      return where(Pets.statusIs(status));
    }

    public List<Pet> findPetByTags(String tags) {
      return where(Pets.tagsContain(tags));
    }
  }
}

启动 SpringBoot, 然后访问 localhost:port/context-path/swagger-ui.html,就能找到 API 文档页面:
REST demo APIs

测试
复制 Example Value 的值到 Value 输入框内,修改 id1,然后点击 try it out:
add example
add example result

生成 Asciidoc 片段

生成一个 RESTful API 片段

使用 Spring Rest Docs 可以通过单元测试生成相应的 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);
    }
}

运行该方法后会在 build/asciidoc/snippets/addPetUsingPOST/ 下生成 getPetById 方法的 Asciidoc 片段。但是,此时生成的 asciddoc 文件只包含 /pets/ (POST) 一个 API 信息。

生成所有的 RESTful API 片段

一般地,我们需要的肯定是整个项目的 RESTful API 文档,如果一个一个 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 testBUILD 成功后会在 target\asciidoc\generated 看到生成的 asciddoc 文件。
swagger2Markup 插件配置

生成 HTML 和 PDF

  1. 在将 index.adocmanual_content1.adocmanual_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[]
    
  2. pom.xml 中添加 asciidoctor 插件, 配置好后运行 mvn test,在配置的文件夹中就会生成 htmlpdf 文档了。

    html和pdf

最终结果

总结

生成的 PDF 对中文支持不是很完美,会出现漏字的情况,总的来说,能做到这步已经能够满足基本需求了。

后续看了 Swagger2Markup 的文档,发现可以很轻松的将 Swagger.json 转换成 Markdown

Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                    .withMarkupLanguage(MarkupLanguage.MARKDOWN)
                    .withOutputLanguage(Language.ZH)
                    .withPathsGroupedBy(GroupBy.TAGS)
                    .build();

Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(localSwaggerFile).withConfig(config).build();
converter.toFile(outputFile);

这样的话可以随时随地编辑,可以更灵活地使用、编辑文档。

参考:

  1. Spring Boot中使用Swagger2构建强大的RESTful API文档
  2. 基于Spring的Restful接口生成工具
  3. Swagger2Markup 手册
  4. Swagger2Markup demo
  5. SpringFox 手册
  6. SpringFox demo
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值