Swagger with Java

What is Swagger ?

Swagger 2 is an open source package written in Java to generate documentation of Swagger compliant APIs.

The latest version of swagger uses a set of html, css and JavaScripts to dynamically generate the documentation. It operates over HTTP protocol.
Swagger 2 also allows us top customize the descriptions of any REST api.

To demonstrate the uses of Swagger we shall be using a Spring boot Java application and see how swagger renders the documentation.

There are several implementations available for Swagger2 which is also known as the OpenApi.

Currently, Springfox that has replaced Swagger-SpringMVC (Swagger 1.2 and older) is popular for Spring Boot applications. Springfox supports both Swagger 1.2 and 2.0.

How to integrate Swagger with Java:

We are going to be using Springfox.

To use Springfox in our project, we need to add the following dependency declaration in our Maven POM.

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.6.1</version>
   <scope>compile</scope>
</dependency>

we also require Swagger UI. The code to include Swagger UI is this.

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.6.1</version>
   <scope>compile</scope>
</dependency>

Configuring Swagger 2 in the Application

For configuring Swagger in our application , we need to create a Docket bean .

This Springfox Docket instance will provide the primary API configuration along with all required sensible defaults and the convenience methods .

The Spring Boot configuration class, SwaggerConfig.java is this

@Configuration
@EnableSwagger2
public class SwaggerConfig {
   @Bean
   public Docket productApi() {
       return new Docket(DocumentationType.SWAGGER_2)
               .select()                 
               .apis(RequestHandlerSelectors.basePackage("app.codegigs.controllers"))
               .paths(regex("/api.*"))
               .build();
   }
}

@EnableSwagger2 annotation enables Swagger support in the class

select() method called on the Docket bean instance returns an ApiSelectorBuilder, which provides the apis()

paths() method is used to filter the controllers and methods ~ being documented using String predicates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Doubts? WhatsApp me !