30

I have my REST API developed using JAX-RS/Jersey in Java. I want to convert to/generate Swagger based UI documentation for it. Can anyone please tell me precise/steps in simple way on how to do so? I m sorry but, steps given on their site are little vague for me.

  • I couldn't really get where I wanted to get with Swagger; I ended up using iodocs: https://github.com/mashery/iodocs. Take a look, see what you think as an alternative. – Rots May 26 '15 at 10:15
  • Check [this](http://jakubstas.com/spring-jersey-swagger-create-documentation/) tutorial out, it has step by step directions to generate UI documentation for your API. – Srini May 26 '15 at 19:45
  • Swagger is a specification. Have you already decided on what implementation of Swagger you are going to use? If yes, what is it? If no, do you want to use swagger-springmvc? – DolphinJava May 28 '15 at 15:08

4 Answers4

6

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.

Ron
  • 14,160
  • 3
  • 52
  • 39
  • 1
    Note that only classes with `@Api` annotation will be scanned by swagger. – Alex R Jul 15 '16 at 14:37
  • @AlexR - by default, yes. That can be changed though. – Ron Jul 15 '16 at 14:45
  • You can set the ReaderConfig.scanAllResources value to `true`. Check out more details at the first section of https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X. – Ron Jul 15 '16 at 22:25
6

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

dubes
  • 5,324
  • 3
  • 34
  • 47
  • How to configure this on eclipse? –  Jun 05 '15 at 07:29
  • If you have a Maven project then you just need to add the dependency and eclipse will take over. Without Maven, I will have to check how it can be used. – dubes Jun 05 '15 at 07:32
  • I added the dependency..but I m facing this error. Plugin com.test.webservices:jaxrs-analyzer-maven-plugin:0.4 or one of its dependencies could not be resolved: Failure to find com.test.webservices:jaxrs-analyzer-maven-plugin:jar:0.4 in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced –  Jun 05 '15 at 08:55
  • Seems like Maven is unable to find the plugin, I will have to take a look at the repository where it is hosted. – dubes Jun 05 '15 at 16:23
  • @SystemMGR can you double check your mvn pom ? I see that the group id is incorrect. You will have to add this in the plugin section of your pom. I will edit the answer to show the entry. – dubes Jun 08 '15 at 07:59
  • I m getting this error now. Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project RESTfulWebServiceExample: Compilation failure –  Jun 10 '15 at 18:07
2

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; 
}
Master Mind
  • 3,014
  • 4
  • 32
  • 63
1

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.

İlker Korkut
  • 3,129
  • 3
  • 30
  • 51
  • I'm sorry, but the link to configuring the web.xml is just wrong and not relevant to the configuration in the question. – Ron May 26 '15 at 19:36
  • There is a sample app jax-rs/jersey also it has configured web.xml file , btw i didn't tried it. – İlker Korkut May 26 '15 at 20:32