Swagger 2 integration

in Spring 4 application

Created by Paolo Escobar / @pao_esco

Agenda

  • Swagger
  • Spring
  • Integration (Springfox)

Swagger

Swagger is a simple yet powerful representation of your RESTful API

http://swagger.io/

Features

Swagger UI

Swagger UI

Spring

RESTful Features

  • @RestController
  • MediaType : application/json, application/xml
  • HTTP verbs : GET, POST, PUT, DELETE, ...

RESTful Controller

							
@RestController
@RequestMapping(value = "/resources/pets", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public class PetsResource {

    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<List<Pet>> get() {
		...
    }
}
							
						

Spring & Swagger Integration

Springfox GitHub project

Springfox Site & Documentation

Scans @Controller annotations

Maven Dependencies

						
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>${swagger.version}</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>${swagger.version}</version>
</dependency>
						
						
					

Spring configuration

						
<!-- Swagger Configuration bean -->
<bean name="/applicationSwaggerConfig" class="com.jeetemplates.app.resources.ApplicationSwaggerConfig"/>

<!-- Enables swagger ui-->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
						
						
					

Swagger configuration

						
import org.springframework.context.annotation.Bean;

import com.google.common.base.Predicate;

import static springfox.documentation.builders.PathSelectors.*;
import static com.google.common.base.Predicates.*;

import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author paoesco
 */
@EnableSwagger2
public class ApplicationSwaggerConfig {

    /**
     * Every Docket bean is picked up by the swagger-mvc framework - allowing for multiple
     * swagger groups i.e. same code base multiple swagger resource listings.
     */
    @Bean
    public Docket customDocket(){
       return new Docket(DocumentationType.SWAGGER_2)
               .select()
               .paths(this.paths())
               .build(); //some customization goes here
    }
    
    //Here is an example where we select any api that matches one of these paths
    @SuppressWarnings("unchecked")
    private Predicate<String> paths() {
      return or(regex("/resources.*"));
    }

}