1. Overview

In this article, We will learn how to configure swagger with spring boot application to generate automatically Rest API document or we can say Spring boot Rest API document using swagger.

What is swagger?

Swagger is the tool which helps us to auto-generate Rest API documentation in the java web application, especially in spring MVC application. here is an official site of swagger.

Let try to understand the requirement of swagger in our application:

For example, We are developing Rest API and those API will be used by someone else or us. before use that API we should know method Type, Method Parameter. Generally, we test API before implementing to our code using some rest client for example PostMan but here we require to configure URL, All parameters, Method Type etc. To overcome those type of overhead swagger is requires.

Swagger provides UI using that we can read API documentation, Request Parameters, API URL, method type, Response Type and most important we can also test or check our API, Here is a short overview of Swagger UI.

 

Swagger UI Example

Swagger UI Example

Steps to configure Swagger in Spring Application

Here is steps to configure swagger in spring MVC or spring boot application.

Step #1: Add dependency of Swagger

Add the following dependency:

 Maven (pom.xml)

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

Gradle

dependencies {
    compile "io.springfox:springfox-swagger2:2.7.0"
    compile "io.springfox:springfox-swagger-ui:2.7.0"
}

Step #2: Enable Swagger

Add annotation @EnableSwagger2 in Spring boot config.

Step #3: Add Swagger Configuration

Create bean of springfox.documentation.spring.web.plugins.Docket which contains configuration related to Swagger

Code for Step #1 and Step #2:

package com.javadeveloperzone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@SpringBootApplication
@ComponentScan // Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
@EnableSwagger2
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.javadeveloperzone.controller"))  // // Generate API of EndPoints which is available inside defined package
                .paths(PathSelectors.any())   // for all EndPoints
                .build();             // create object
    }
}

2. Example

Here is spring boot swagger2 example using Maven.

Spring boot Swagger Example

Spring boot Swagger Example

2.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>spring-boot-example</groupId>
    <artifactId>spring-boot-swagger-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <description>Spring boot Rest API Document using swagger</description>
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.2 application.properties

No need of any other extra configuration for swagger in application.properties or yml.

server.port=8282

2.3 SpringBootConfig

package com.javadeveloperzone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@SpringBootApplication
@ComponentScan // Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
@EnableSwagger2
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.javadeveloperzone.controller"))      // Generate API of EndPoints which is available inside defined package
                .paths(PathSelectors.any())     // for all EndPoints
                .build();                   // create object
    }
}

2.4 HelloController

Its same as like other controllers, @ApiOperation and @Api are a swagger annotation, Using that we can provide different configuration:

@Api(value = “API Description”) // it description of api at top used to Controller Class level, General info about API

@ApiOperation(value = “It will return list of Employee”)             // for description of API
@ApiOperation(value = “It will return list of Employee”, notes = “This is for note”)           // add note of api

@ApiOperation(value = “API Description”,hidden = true)              // Hire from API from document
@ApiOperation(value = “API Description”,tags = “View”)              // category of API

package com.javadeveloperzone.controller;
import com.javadeveloperzone.model.Employee;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by JavaDeveloperZone on 13-05-2018.
 */
@RestController
@Api(value = "API Description") // it description of api at top
public class HelloController {
    private List<Employee> employeeList = new ArrayList();
    @ApiOperation(value = "It will return list of Employee")        // it description of api
    @GetMapping(value = "/list")
    public List<Employee> list(){
        return employeeList;
    }
    @ApiOperation(value = "It will add new employee")               // it description of api
    @PostMapping(value = "save")
    public Employee save(Employee employee){
        employeeList.add(employee);
        return employee;
    }
    @ApiOperation(value = "It will delete employee")                // it description of api
    @DeleteMapping(value = "delete/{id}")
    public void delete(@PathVariable("id")Integer id){
        employeeList.removeIf(e->{
            return e.getId()==id;
        });
    }
}

2.5 Employee

package com.javadeveloperzone.model;
/**
 * Created by JavaDeveloperZone on 13-05-2018.
 */
public class Employee {
    private int id;
    private String name;
    public Employee(){
    }
    public Employee(int id,String name){
        this.id=id;
        this.name=name;
    }
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public void setId(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
}

2.6 Output

> mvn spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
.util.List<springfox.documentation.swagger.web.SwaggerResource>> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
2018-05-13 10:13:37.299  INFO 28268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/swagger-resources/configuration/ui]}" onto public org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration> springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
2018-05-13 10:13:37.301  INFO 28268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/swagger-resources/configuration/security]}" onto public org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.SecurityConfiguration> springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
2018-05-13 10:13:37.307  INFO 28268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-13 10:13:37.308  INFO 28268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springhttp://localhost:8282/swagger-ui.htmlframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-13 10:13:37.656  INFO 28268 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
2018-05-13 10:13:38.005  INFO 28268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@610f7aa: startup date [Sun May 13 10:13:32 IST 2018]; root of context hierarchy
2018-05-13 10:13:39.084  INFO 28268 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8282 (http)

Let’s call UI using http://localhost:8282/swagger-ui.html

Swagger UI Example

Swagger UI Example

3. Concussion

In this article, We have learned how to configure Swagger to generate API document in spring MVC application using spring boot.

4. References

5. Source Code

spring-boot-rest-api-document-swagger (173 KB)

Was this post helpful?

Leave a Reply

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