Documenting Spring Boot Web Services with Swagger v2

A while ago I wrote about how to document Spring Boot Microservices with Swagger. This new post details how to use Swagger v2 documentation in order to document your web services. Using V2 will let you do neat things like use ReDoc, or import your Web Service into Postman (both of which are also awesome!).

The pom.xml file

Firstly, you’ll need to add Swagger dependencies into your pom file:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.5.0</version>
    <type>jar</type>
</dependency>

Swagger config

Then, you should create a SwaggerConfig class in the config package of your application. Here’s an example:

@Configuration
@EnableSwagger2
@EnableAutoConfiguration
public class SwaggerConfig {

    @Value("${swagger.oauth.url}")
    private String swaggerOAuthUrl;

    @Bean
 public Docket swaggerSpringMvcPlugin() {


        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("my-new-ms")
                .select()
                .paths(paths())
                .build()
                .apiInfo(apiInfo())
                .securitySchemes(newArrayList(oauth2()));
    }

    //Here is an example where we select any api that matches one of these paths
 private Predicate<String> paths() {
        return or(regex("/entity/.*"),
                regex("/entities.*"));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("My New MS API")
                .description("This service provides a JSON API for my new entity.")
                .version("2.0")
                .build();
    }


    @Bean
 SecurityScheme oauth2() {
        return new OAuthBuilder()
                .name("oauth2")
                .grantTypes(grantTypes())
                .scopes(scopes())
                .build();
    }

    List<AuthorizationScope> scopes() {
        return newArrayList(new AuthorizationScope("entity.read","Read access on entity in my new API"));
    }

    List<GrantType> grantTypes() {
        ImplicitGrant implicitGrant = new ImplicitGrant(new LoginEndpoint(swaggerOAuthUrl),"access_code");

        return newArrayList(implicitGrant);
    }
    
}

Change the above paths() to protect whichever paths you need. If you’re using OAuth2, make sure you set the scope as per your actual OAuth2 scope(s).

Controller annotations

Next you annotate your controller methods with Swagger specific annotations:

@ApiOperation(value="Get an entity by id",notes="Requires an entity id to lookup", response = Entity.class,
        authorizations = {@Authorization(value="oauth2",scopes = {@AuthorizationScope(scope="entity.read",description = "Read access on entity in my new API")})})
@ApiResponses({@ApiResponse(code=404,message="Entity not found")})
@RequestMapping(value = "/entity/{entity-id}", method = RequestMethod.GET)
public @ResponseBody Entity getEntity(@PathVariable(value = "entity-id") String entityId) throws NotFoundException {
    Entity entity = entityRepository.findOne(entityId);
    if (entity!=null)
    {
        return entity;
    }
    else
 {
        throw new NotFoundException("Entity not found");
    }
}

@ApiOperation(value="Get a list of entities by param",notes="Requires param to lookup", response = Entity.class,responseContainer = "List",
        authorizations = {@Authorization(value="oauth2",scopes = {@AuthorizationScope(scope="entity.read",description = "Read access on entity in my new API")})})
@RequestMapping(value="/entities", method = RequestMethod.GET)
public @ResponseBody
List<Entity> getEntities(@RequestParam(value="param",required = true) String param)
{
        return entityRepository.findEntitiesByParam(param);   
}

The @ApiOperation annotation is then used by Swagger to generate the Swagger JSON for documentation purposes.

Security

If you are protecting your API using OAuth2 protection, remember that you’ll need to unprotect the Swagger API docs URL (e.g. /v2/api-docs) so that the Swagger UI (and ReDoc) can access it and build documentation.

Swagger UI

Finally, so that developers can interact with the Swagger UI, get Swagger ui v2.2.5 and copy the contents of the dist folder into /src/main/resources/public in your Spring Boot application:

Make sure and change the index.html file to set the correct OAuth client-id, the appName, and also set the url for the API explicitly so that it will default to the correct URL when rendering for the first time.