user1529412 user1529412 - 28 days ago 18
Java Question

How to integrate Swagger with Maven + Java + Jersey +Tomcat

I can't seem to understand how to integrate Swagger to generate API documentation.
url: ####:8080/MyService/rest/users/getall

I have added Annotations to code and dependency.

I try to visit: ####:8080/MyService/rest/ but says its not found.

//web.xml


<servlet>
<servlet-name>mycompany-users-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.users.services.mycompany,com.wordnik.swagger.jersey.listing</param-value>
</init-param> `
<servlet>
<servlet-name>JerseyJaxrsConfig</servlet-name>
<servlet-class>com.wordnik.swagger.jersey.config.JerseyJaxrsConfig</servlet-class>
<init-param>
<param-name>api.version</param-name>
<param-value>1.0.0</param-value>
</init-param>
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>####:8080/MyService/rest/</param-value> //not sure What this should be?
</init-param>
<load-on-startup>2</load-on-startup>`

Answer

Provided that you have correctly copied the files from https://github.com/wordnik/swagger-ui to your project (directory dist must be copied to your src/main/webapp), then you can access the API documentation on http://.../MyService/index.html. Don't forget to modify index.html so that Swagger knows where to load the API docs:

window.swaggerUi = new SwaggerUi({
    url: "http://localhost:8080/MyService/rest/api-docs",

The API base path in your web.xml must be set to http://.../MyService/rest if rest is the application path that you have defined in your implementation of class javax.ws.rs.core.Application by using the annotation @ApplicationPath.

Here is an example of what I usually do (I don't use web.xml for configuration):

@ApplicationPath( "api" )
public class MyRestApplication extends Application
{
   @Override
   public Set<Class<?>> getClasses( )
   {
       Set<Class<?>> resources = new HashSet<Class<?>>( );
       resources.add( ApiListingResource.class );
       resources.add( ApiDeclarationProvider.class );
       resources.add( ApiListingResourceJSON.class );
       resources.add( ResourceListingProvider.class );
       resources.add( Ping.class ); // my own resource class
       swaggerConfiguration( );
       return resources;
   }

   private void swaggerConfiguration( )
   {
      SwaggerConfig swaggerConfig = new SwaggerConfig( );
      ConfigFactory.setConfig( swaggerConfig );
      swaggerConfig.setApiVersion( "0.0.1" ); 
      swaggerConfig.setBasePath( "http://localhost:8080/MyService/api" );
      ScannerFactory.setScanner( new DefaultJaxrsScanner( ) );
      ClassReaders.setReader( new DefaultJaxrsApiReader( ) );
   }
}
Comments