Val Akkapeddi
Val Akkapeddi

Reputation: 1183

Generating Swagger documentation from existing REST api

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.

Upvotes: 2

Views: 9483

Answers (2)

Justinas Jakavonis
Justinas Jakavonis

Reputation: 8858

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.

Upvotes: 1

simdevmon
simdevmon

Reputation: 693

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.

Upvotes: 1

Related Questions