Generating Swagger documentation from existing REST api

不打扰是莪最后的温柔 提交于 2019-12-21 06:38:30

问题


Given an existing JAX-RS-annotated API that accepts & returns json, with jackson-annotated types, is there a way that I can generate some YAML Swagger documentation? My plan B is to write some code that uses reflection to find REST-annotated types, make a hashmap of their arguments & returns, and then crawl those classes for Jackson annotations, and generate the documentation that way.

I would prefer to use a solution that already exists to writing a one-off thing. I found this Swagger module that claims it can parse Jackson configurations (https://github.com/FasterXML/jackson-module-swagger) but I don't know enough about Swagger to understand what modules are and whether I can use it to generate Swagger from existing code.


回答1:


You might want to have a look at this project: https://github.com/sdaschner/jaxrs-analyzer

It can generate Swagger documentation automatically for JAX-RS. As far as I know Jackson specific annotations are not taken into consideration.




回答2:


Swagger will generate interactive documentation for annotated methods. You don't need to write your own crawler. Add lib:

    <dependency>
        <groupId>com.wordnik</groupId>
        <artifactId>swagger-jaxrs_2.10</artifactId>
        <version>1.3.13</version>
        <scope>compile</scope>
    </dependency>

Configure it:

private void configureSwagger(String swaggerBasePath){
    SwaggerConfig swaggerConfig = new SwaggerConfig();
    ConfigFactory.setConfig(swaggerConfig);
    swaggerConfig.setSwaggerVersion("Version");
    swaggerConfig.setApiVersion("1"); 
    swaggerConfig.setBasePath("http://example.com:8080/your-service");
    ScannerFactory.setScanner(new DefaultJaxrsScanner());
    ClassReaders.setReader(new DefaultJaxrsApiReader());
}

Annotate your service and methods:

@Path("/v1/items")
@Api(value = "/v1/items", description = "API description for Swagger")
public class ItemsService {

      @GET
      @Path("/list")
      @ApiOperation(value = "Get items list", notes = "Returns items list.")
      @Consumes(MediaType.APPLICATION_JSON)
      @Produces(MediaType.APPLICATION_JSON)
      public ItemsResponse getItems(){
          ...
      }

}

Add Swagger UI folder and modify its index.html source to load your REST service documentation URL.



来源:https://stackoverflow.com/questions/40661283/generating-swagger-documentation-from-existing-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!