We are now live in a software development era where software industries are providing cloud services to the clients. It is important to expose the API with proper documentation for a service provider. Open API or Swagger library gives this facility to the spring-based application to expose interactive documentation to the client.
Read Also: Spring Boot Hello World
1. What is Swagger
Nowadays, backend application exposes the REST API endpoints which are used by the different type of clients like mobile application, web application, and others. It is important to know about the exposed endpoint for client implementation. Swagger provides this API documentation for the client in a format that is understandable by the human. Swagger UI also provides a user interface for the API documentation provided by the backend application. Let's dive deep into the topic.1.1 Build a project
We will create an initial project from Spring Initializr. At first, we will create a spring boot project using a spring web library with a maven build tool. We can follow the below image.If you are completely new to Spring Boot, then follow this tutorial for creating a project from Spring Initializr step by step.
1.2 Adding Swagger Maven Dependency
After creating the initial project we will add the swagger dependency to the pom.xml file. We will add the following code to pom.xml. You can find the latest version on Maven Central.<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency>
Then we should build and run the project. Here we are using springfox swagger 2 with version 2.9.2. We should add a config file for the spring swagger. We will create and add a config file SwaggerConfig.java to com.javahungry.swagger.config package.
package com.javahungry.swagger.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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 api(){ return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build().apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Java Hungry API") .description("Java Hungry API's") .version("1.0.0") .termsOfServiceUrl("http://javahungry.blogspot.com") .license("JavaHungry License") .licenseUrl("http://javahungry.blogspot.com") .build(); } }
@EnableSwagger2 enables swagger to the application and Docket bean is the central configuration bean of swagger. ApiSelectorBuilder instance returns by the select method to control API endpoints exposed by Swagger. Using this builder we can configure which endpoints should be exposed with swagger or not. For example, if we use the following path selector /employee/*, it will just return the information that API contains this employee endpoint.
We will add employee controller to check the swagger example.
package com.javahungry.swagger.controller; import com.sun.org.apache.xpath.internal.operations.Bool; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping(value = "/employee") public class EmployeeController { @GetMapping public List<Employee> getEmployee(){ List<Employee> employees = new ArrayList<>(); return employees; } @PostMapping public Boolean save(@RequestBody Employee employee) { //@TODO save employee return true; } @PutMapping(value = "{id}") public Boolean update(@PathVariable Integer id,@RequestBody Employee employee) { //@TODO update employee return true; } @DeleteMapping(value = "{id}") public Boolean delete(@PathVariable Integer id){ //@TODO delete employee return true; } }
We can see that employee controller contain a different kind of HTTP methods. We will add another controller TestController.
package com.javahungry.swagger.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping(value = "/test") public class TestController { @GetMapping public List<String> getTest(){ List<String> strings = new ArrayList<>(); return strings; } }
1.3 Swagger UI
Springfox provides UI for easy interaction with the user. We should add the following dependency to the pom.xml file and restart the server.<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
Now we will open terminal to project root folder and execute mvn spring-boot:run command to run the project. After starting the server we should hit the URL
http://localhost:8080/swagger-ui.html#/ on the browser.
Click on the employee-controller and browser should show HTML like below image
2. Advanced Configuration for Swagger
When we will define PathSelector like above configuration file SwaggerConfig.java it will return all API information but we can restrict only employee endpoints to the client then we should follow below configuration.@Bean public Docket api(){ return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) //.paths(PathSelectors.any()) .paths(PathSelectors.regex("/employee/*")) .build().apiInfo(apiInfo()); }
This configuration only allows exposing /employee endpoints documentation to the client. But for now, we should revert this to the default configuration. You should hit http://localhost:8080/v2/api-docs from the browser. We will see that all information about the API is exposed like below image.
Annotations used by springfox:
We can use our TestController to check some examples. We have to add the following code like this
package com.javahungry.swagger.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping(value = "/test") @Api(value = "Endpoints for Retrieving of Test String List.", tags = {"List String"}) public class TestController { @ApiOperation(value = "API to GET Test list String", notes = "Get all string list", tags = { "TestString" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "List retrieve success", response=List.class ) }) @GetMapping public List<String> getTest(){ List<String> strings = new ArrayList<>(); return strings; } }
We already defined an Employee class which is like this. Here we add an annotation @ApiModel to define this is a swagger model.
package com.javahungry.swagger.controller; import io.swagger.annotations.ApiModel; @ApiModel(value = "Employee Model", description = "Employee Model for employee controller request response") public class Employee { Integer id; String name; String address; String department; Double age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public Double getAge() { return age; } public void setAge(Double age) { this.age = age; } }
If we again restart the project and hit the browser with the following link http://localhost:8080/swagger-ui.html#/TestString/getTestUsingGET and expand TestString GET method we will see the result like below image.
Click on the Models and then the Employee model, it will look like the below image.
3. Conclusion
Spring Swagger provides a good way to generate automatic API documentation for the entire application with some simple configuration. It reduces to write many documents for all exposed API.That's all for today, please mention in comments in case you have any questions related to Spring Boot Swagger 2 example using springfox.
4. Download Source Code
Download – Swagger.zip