Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Swagger UI documentation for REST API

People also ask

How do I generate Swagger documentation for REST API automatically?

Use Swagger Inspector to quickly generate your OAS-based documentation for existing REST APIs by calling each end point and using the associated response to generate OAS-compliant documentation, or string together a series of calls to generate a full OAS document for multiple API endpoints.

How can I get Swagger UI?

First, you'll make sure you can view Swagger locally. Then you'll switch the Petstore OpenAPI document URL with an OpenWeatherMap OpenAPI document URL. Go to the Swagger UI GitHub project. Click Clone or download, and then click Download ZIP.

How Swagger UI HTML is generated?

When you open the webpage, the browser will load the webpage from the web server, and trigger requests to the API server to get data from a database. SwaggerUI is automatically generated from any API defined in the OpenAPI Specification and can be viewed within a browser.


There are several ways to integrate swagger-core with your application, but based on your description, I'd just follow the wiki page as described either by https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-1.X-Project-Setup-1.5 or https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5 depending on the Jersey version you use.

Those pages also link to a set of samples you can use for reference and see how they work. They also pull in swagger-ui directly into them so you can see a full set of interaction.


The easiest way I know is to use the JAXRS Analyzer maven plugin. Which can be found on GitHub

<plugin>
<groupId>com.sebastian-daschner</groupId>
<artifactId>jaxrs-analyzer-maven-plugin</artifactId>
<version>0.4</version>
<executions>
    <execution>
        <goals>
            <goal>analyze-jaxrs</goal>
        </goals>
        <configuration>
            <!-- Available backends are plaintext (default), swagger and asciidoc -->
            <backend>plaintext</backend>
            <!-- Domain of the deployed project, defaults to example.com -->
            <deployedDomain>example.com</deployedDomain>
        </configuration>
    </execution>
</executions>

This creates the swagger json for you with mvn clean install. To the best of my knowledge it does not need any manipulation of the web.xml etc. as it does it via bytecode analysis.

Source: Adam Bien weblog entry & his demo in one of the airhacks session

Bonus: a 9 minute video by the creator of the plugin explaining the usage


You should use roaster : you can do source code modification to add new annotations. Here is an example to illustrate how to use it in your case:

package ma.cars.iscraper;

import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.source.*;

import java.util.List;

public class Main {

    public static void main(String[] args) {



  String originalClassSourceCode = "@Path(\"user\")\n public class SomeClass {    @GET\n" +
                "  @Path(\"{userId}\")\n  public Response getUserById() {\n return null; \n}";

        System.out.println("Before : \n" + originalClassSourceCode);
  JavaClassSource javaClass =
                Roaster.parse(JavaClassSource.class,originalClassSourceCode );

       String pathValue = null;
        // extract Path annotation value
        List<AnnotationSource<JavaClassSource>> listAnnotations = javaClass.getAnnotations();
        for (AnnotationSource annotation :listAnnotations) {
            if (annotation.getName().equals("Path")) {
                pathValue = annotation.getStringValue();
            }
        }
        AnnotationSource<JavaClassSource> apiAnnotation = javaClass.addAnnotation("com.wordnik.swagger.annotations.Api");
        apiAnnotation.setLiteralValue("\"" + pathValue + "\"") ;

        List<MethodSource<JavaClassSource>> methods = javaClass.getMethods();

        for (MethodSource<JavaClassSource> method: methods) {
           for (AnnotationSource annotation: method.getAnnotations()) {
               if (annotation.getName().equals("DELETE") || annotation.getName().equals("GET")
                       || annotation.getName().equals("POST") || annotation.getName().equals("PUT")) {
                   String returnTypeClass = method.getReturnType().getQualifiedName();
                   AnnotationSource<JavaClassSource> apiOperation = method.addAnnotation("com.wordnik.swagger.annotations.ApiOperation");
                   apiOperation.setLiteralValue("value", "\"value\"");
                   apiOperation.setLiteralValue("response", "\"" + returnTypeClass + ".class\"");

               }
           }
        }

        System.out.println(javaClass);

    }
}

And here is the output:

Before : 
@Path("user")
 public class SomeClass {    @GET
  @Path("{userId}")
  public Response getUserById() {
 return null; 
}
After :

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;@Path("user")
 @Api("user")
public class SomeClass {    @GET
  @Path("{userId}")
  @ApiOperation(value = "value", response = "Response.class")
public Response getUserById() {
 return null; 
}

Swagger has nice documentation step by step implementations on github.

You should use swagger annotations on your methods, resources, models. Then you should configure your web.xml as described here. After all these steps you can reach swagger-ui yourdomain/api-docs or another path which configured in web.xml ApiDeclarationServlet's listening path.

There is a sample swagger app Jax-rs/Jersey

Swagger UI is a dependency-free collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation and sandbox from a Swagger-compliant API. Because Swagger UI has no dependencies, you can host it in any server environment, or on your local machine.

  • There is a nice discussion about to get statics dependency. Normally you need to copy and paste swagger-ui statics. https://github.com/swagger-api/swagger-ui/issues/758
  • Swagger UI distribution https://github.com/swagger-api/swagger-ui/tree/master/dist
  • Another example app which uses swagger: https://github.com/apache/camel/blob/master/examples/camel-example-servlet-rest-tomcat/src/main/webapp/WEB-INF/web.xml
  • Simple reference about swagger implementation with springboot(Which is not needed web.xml in this situation).