Swagger Generation With Spring Boot

Join the DZone community and get the full member experience.

Ever thought about what could happen if you develop your Restful API's but you are not able to document it for someone to refer to it? Or you develop your API's and the front-end team needs to access it how they would know what your API's contain or require as input?

The solution to the above question is using Swagger. Swagger is an open source framework where you can document your Restful API's, access them, and test your services. But how do we do that? Let's see through a working example.

We will go through a sample application let's say a hotel management system which is developed using Spring Boot and integrated with Swagger2.0 version. Firstly, you can download a Spring Boot project from https://start.spring.io/ , which gives you a starting point using all the dependencies you require and import it as a Maven project in your eclipse. Let's see what you need in your pom.xml for integrating swagger2.

Apart from other dependencies in Spring Boot, we require below two dependencies to integrate swagger2 with Spring Boot.

 io.springfox springfox-swagger2 2.6.1 compile  io.springfox springfox-swagger-ui 2.6.1 compile 

springfox libraries are required to generate the api-docs and the swagger-ui for our RestAPI's.

Let's create a RestController class that will define our API. Below is the CustomerController class, we will go in details of this class one-by-one.

package com.hotel.main.controllers; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.hotel.main.model.Customer; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; @RestController @Api(value="/customer",description="Customer Profile",produces ="application/json") @RequestMapping("/customer") public class CustomerController < @ApiOperation(value="get customer",response=Customer.class) @ApiResponses(value=< @ApiResponse(code=200,message="Customer Details Retrieved",response=Customer.class), @ApiResponse(code=500,message="Internal Server Error"), @ApiResponse(code=404,message="Customer not found") >) @RequestMapping(value="/getCustomer",method=RequestMethod.GET,produces="application/json") public ResponseEntity getCustomer()< Customer cust = new Customer(); cust.setName("Sagar"); cust.setId(1234); cust.setAddress("Pune"); return new ResponseEntity(cust, HttpStatus.OK); > >

The above controller class defines a GET service which is used to retrieve customer details. For simplicity, I'm returning a customer object from this class itself by specifying values in it. In the real world, it will be from a database. Some special annotations you will find here are as below.

  1. @Api — which defines what this controller class defines.
  2. @ApiOperation — which defines what this particular request method does.
  3. @ApiResponses — will define all the API responses that can be returned from this method.

Let's define the Customer Model. This class should be self-explanatory.

package com.hotel.main.model; public class Customer < private Integer id; private String name; private String address; public String getName() < return name; >public void setName(String name) < this.name = name; >public Integer getId() < return id; >public void setId(Integer id) < this.id = id; >public String getAddress() < return address; >public void setAddress(String address) < this.address = address; >>

We require a new class here which will define all the details of our API- Rest controllers through Swagger. Below is the SwaggerConfig.java class.

package com.hotel.main.util; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig < @Bean public Docket produceApi()< return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.hotel.main.controllers")) .paths(paths()) .build(); >// Describe your apis private ApiInfo apiInfo() < return new ApiInfoBuilder() .title("Hotel Management Rest APIs") .description("This page lists all the rest apis for Hotel Management App.") .version("1.0-SNAPSHOT") .build(); >// Only select apis that matches the given Predicates. private Predicate paths() < // Match all paths except /error return Predicates.and( PathSelectors.regex("/customer.*"), Predicates.not(PathSelectors.regex("/error.*")) ; >>

Let's go through the details.

  1. @EnableSwagger2 — This will enable the swagger configuration during application startup.
  2. Docket — It is a builder which acts as a primary interface in swagger-springmvc framework. It returns below things.
  3. apiInfo — It returns a ApiInfoBuilder which specfies the tile,description etc of the Rest API's.
  4. select()-select() method returns an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.
  5. apis — provides RequestHandlerSelectors which specified basepackage to scan for all the controllers.
  6. paths() — provides the mapping endpoints of our API's.

And lastly, we will run our application with the Application class provided by Springboot.

package com.hotel.main; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableSwagger2 public class Application < public static void main(String[] args) < SpringApplication.run(Application.class, args); >>

After running the application, the below logs will get printed, which specifies that the Swagger plugin is integrated with our application.

2018-08-19 14:21:43.418 INFO 13472 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "<[/customer/getCustomer],methods=[GET],produces=[application/json]>" onto public org.springframework.http.ResponseEntity com.hotel.main.controllers.CustomerController.getCustomer()

2018-08-19 14:21:43.422 INFO 13472 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "<[/v2/api-docs],methods=[GET],produces=[application/json || application/hal+json]>" onto public org.springframework.http.ResponseEntity springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)

2018-08-19 14:21:43.430 INFO 13472 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "<[/swagger-resources/configuration/security]>" onto org.springframework.http.ResponseEntity springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()

2018-08-19 14:21:43.432 INFO 13472 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "<[/swagger-resources/configuration/ui]>" onto org.springframework.http.ResponseEntity springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()

2018-08-19 14:21:43.436 INFO 13472 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "<[/swagger-resources]>" onto org.springframework.http.ResponseEntity> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()

2018-08-19 14:21:43.446 INFO 13472 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "<[/error]>" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)

2018-08-19 14:21:43.447 INFO 13472 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "<[/error],produces=[text/html]>" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

2018-08-19 14:21:44.761 INFO 13472 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e329c2c: startup date [Sun Aug 19 14:21:35 IST 2018]; root of context hierarchy

2018-08-19 14:21:44.954 INFO 13472 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

2018-08-19 14:21:44.955 INFO 13472 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

2018-08-19 14:21:45.139 INFO 13472 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

2018-08-19 14:21:46.277 INFO 13472 --- [ost-startStop-1] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup

2018-08-19 14:21:46.297 INFO 13472 --- [ost-startStop-1] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647

2018-08-19 14:21:46.298 INFO 13472 --- [ost-startStop-1] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed

2018-08-19 14:21:46.417 INFO 13472 --- [ost-startStop-1] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)

2018-08-19 14:21:46.521 INFO 13472 --- [ost-startStop-1] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references

2018-08-19 14:21:47.021 INFO 13472 --- [ost-startStop-1] com.hotel.main.ServletInitializer : Started ServletInitializer in 12.663 seconds (JVM running for 27.901)

2018-08-19 14:21:47.107 INFO 13472 --- [ main] org.apache.coyote.ajp.AjpNioProtocol : Starting ProtocolHandler ["ajp-nio-8009"]

2018-08-19 14:21:47.116 INFO 13472 --- [ main] org.apache.catalina.startup.Catalina : Server startup in 26221 ms

Now open your browser and type below URL's and see the results.

1. http://localhost:8080/hotelmanagement/customer/getCustomer

Image title

This will return you the JSON object customer with its details from the service.

2. Now let's see what's there in our api-docs integrated through swagger

http://localhost:8080/hotelmanagement/v2/api-docs

Image title

This will output all the details such as title, description, and tags, which we have configured through SwaggerConfig.java class.

3. The last thing to see is the swagger-ui.html, which will be referred to test our services, it will also act as an input for frontend team to see what all API's the application contain so that they can design their UI.

http://localhost:8080/hotelmanagement/swagger-ui.html

Image title

Image title

If you click on the GET service, it will show you the below screen.

Image title

Click on the "Try it out!" button. It will give you the result:

Image title

That's all for this tutorial. Please comment in the below box if you find anything missing or need to add anything.

Spring Framework Spring Boot application API

Opinions expressed by DZone contributors are their own.