Let's Build an API Together - Part 31

Last Update: 14.02.2018. By Jens in API Series | APIs | Newsletter

Swagger is a tool for documenting APIs, primarily driven from a coding side and a universal docs client.

Adding basic support in a Spring application is straightforward using the springfox lib.

We add two dependencies to the POM:

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>

springfox-swagger-ui is only needed if you want the swagger UI be running in your application.

Next, we declare a new bean in a @Configuration class like:

@Bean
public Docket api() { 
    return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo() )
      .select()                                  
      .apis(RequestHandlerSelectors.basePackage("de.codeboje.kanbanapi"))              
      .paths(PathSelectors.any())                          
      .build();                                           
}

APIInfo provides some additional info about our app. See method below. And the rest define which controller and path aka endpoints should be included in the API doc.

Name, description, contact info and more is set in ApiInfo:

private ApiInfo apiInfo() {
    return new ApiInfo(
      "Kanban API", 
      "Kanban API as a backend for testing UIs",
      "v1",
      "Free to use", 
      new Contact("Jens Boje", "kanbanbackend.com", "info@codeboje.de"), 
      "Free to us", 
      "Free to use",
      Collections.emptyList());
}

The swagger endpoint is exposed under /v2/api-docs and the UI is available under /swagger-ui.html.

If we run Spring Security like we did in the tutorial, we need to exclude a few path from security, so swagger works without it.

Override the configure(WebSecurity web) in WebSecurityConfigurerAdapter or implement it using the WebSecurityConfigurer like:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers( "/v2/api-docs", "/swagger-ui.html", "/webjars/**", "/swagger-resources/**");
}

All four paths are needed for swagger. And here is a live version of the kanban backend running on a free Heroku instance, so it might just start for you.