Swagger for documenting your Spring Boot REST Api

 

What Is Swagger?

Swagger is a set of open-source tools built around the OpenAPI Specification that can help you design, build, document and consume REST APIs.

Swagger  is mostly used as an open source project for describing and documenting RESTful APIs.  Swagger-UI an another tool which provides the capability of displaying the REST Api documentation in the browser.  Besides rendering documentation, Swagger UI allows other API developers or consumers to interact with the API’s resources without having any of the implementation logic in place.

The more details can be found through following documentations.

https://swagger.io/docs/ 

http://springfox.github.io/springfox/docs/current/

 

Springfox for Swagger

The Swagger 2 specification, which is known as OpenAPI specification has several implementations. Currently, Springfox that has replaced Swagger-SpringMVC (Swagger 1.2 and older) is popular for Spring Boot applications.

What we are going to do?

This article will explain how the Swagger is integrated into the Spring Boot REST Api as a API documentation generator. So in order to proceed with this article, you need to have a Spring Boot based REST Api project.

 

Integrating Swagger for your Project

To bring it in, we need the following dependency declaration in our Maven POM. This includes two dependencies springfox-swagger2 and springfox-swagger-ui. 

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

view raw
pom.xml
hosted with ❤ by GitHub

 

Adding the following Swagger Configuration

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket restApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.springbootdev.examples.swagger.controller"))
.build()
.apiInfo(getApiInfo());
}
private ApiInfo getApiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot REST API – User Management")
.description("\"Simple Spring Boot REST Api for managing Users\"")
.version("1.0.0")
.license("Apache License Version 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
.contact(new Contact("Chathuranga Tennakoon", "https://www.springbootdev.com", "chathuranga.t@gmail.com"))
.build();
}
}

view raw
Swagger2Config.java
hosted with ❤ by GitHub

 

@EnableSwagger2 

This will add the Swagger 2 support for the Spring REST Api project.

 

Advanced configuration with Docket

The Docket bean of your application can be configured to give you more control over the API documentation generation process.

Docket is a builder that provides default configuration of Swagger documentation. If you want a custom implementation, then you need to create a method in Swagger configuration class with return type Docket annotated with @Bean. (please refer the restApi() method of the above Swagger configuration class)

 

Filtering and Restricting Api Documentation with apis() and paths()

It is not always desirable to expose the documentation for your entire API. You can restrict Swagger’s response by passing parameters to the apis() and paths() methods of the Docket class. In this way, you can decide which part of the REST api needs to be exposed through documentation and which part need to be restricted from being generating Api documentation.

according to above configuration class, the REST Api documentation will be generated only for the controllers which are in the below package.

com.springbootdev.examples.swagger.controller

 

 

Configure Spring Security to allow the access of REST Api documentation with Swagger UI

 

The most of the Spring Security configuration will require the user authentication and authorization for accessing certain part of the application. It will restrict the user access of the certain part of the application (URLs)  if they are not explicitly excluded from checking the authentication and authorization. Therefore we need to exclude the URL that is used to access the Swagger based REST Api documentation from authentication and authorization security checking.  This can be done by adding the following configuration for your main Spring Security configuration file.

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}

 

 

Rendering REST Api documentation with Swagger UI

Now our initial configuration is done with integrating Swagger for the Spring REST Api. Now it is the time to render the generated documentation with Swagger UI. You can follow the instructions given below.

  • build  and run the project. This can be done with following command.
   mvn spring-boot:run

(In your case, it can be accessed with http://localhost:8080/swagger-ui.html)

Then you will see the Swagger generated API documentation as follows.

Screen Shot 2018-05-11 at 10.32.56 PM.png

 

 

Swagger Annotations

@ApiOperation: Provides documentation support for REST web service method, for example what operation this method performs.

@ApiParam: Provides documentation support about parameter of REST web service method.

@Api: provides the support for documenting RestContoroller classes. Grouping the set of @ApiOperation endpoints.

@ApiModel: provides the support for documenting the DTO models.

 

Here are some real usages of some of the annotations described above.

import com.springbootdev.examples.swagger.exception.ModelNotFoundException;
import com.springbootdev.examples.swagger.exception.PersistentException;
import com.springbootdev.examples.swagger.model.dto.request.AddUserRequest;
import com.springbootdev.examples.swagger.model.dto.response.AddUserResponse;
import com.springbootdev.examples.swagger.model.dto.response.FindUserResponse;
import com.springbootdev.examples.swagger.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@Api(value = "user-controller", description = "Endpoints for handling and managing user related operations", tags = "/users")
public class UserController {
@Autowired
private UserService userService;
@ApiOperation(value = "creating new user")
@PostMapping("/users")
public AddUserResponse createUser(@Valid @RequestBody AddUserRequest addUserRequest, BindingResult bindingResult) throws PersistentException {
if (bindingResult.hasErrors()) {
throw new PersistentException(bindingResult.getAllErrors().get(0).getDefaultMessage());
}
return userService.create(addUserRequest);
}
@ApiOperation(value = "finding the user by id")
@GetMapping("/users/{id}")
public FindUserResponse findUserById(@PathVariable("id") Integer id) throws ModelNotFoundException {
return userService.findUserById(id);
}
}

view raw
UserController.java
hosted with ❤ by GitHub

 

 

Based on the above UserController, following documentation will be generated.

Screen Shot 2018-05-12 at 10.15.51 AM.png

 

 

Please refer the below DTO model (AddUserRequest.java).

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@NoArgsConstructor
@AllArgsConstructor
@Getter(AccessLevel.PUBLIC)
@Setter(AccessLevel.PUBLIC)
@ApiModel(value = "UserRequest")
public class AddUserRequest implements Serializable {
@NotNull(message = "Name is required")
@ApiModelProperty(notes = "Name of the user")
private String name;
@NotNull(message = "Username is required")
@ApiModelProperty(notes = "Username of the user")
private String username;
@NotNull(message = "Password is required")
@ApiModelProperty(notes = "Password of the user")
private String password;
}

view raw
AddUserRequest.java
hosted with ❤ by GitHub

 

 

The following documentation segment will be generated for the above mode.

Screen Shot 2018-05-12 at 10.20.25 AM.png

 

You find more annotation related to the Swagger REST API documentation in the official documentation.

http://springfox.github.io/springfox/docs/current/

 

Source Code

A sample Spring Boot REST Api project  (that is documented using Swagger) can be accessed through following GitHub Repository.

https://github.com/chathurangat/spring-boot-rest-swagger

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s