Setting up Swagger 3 With Spring Boot
Documentation is a very important part of any restful API, Swagger had made it easy for developers to get a neat documentation for their API endpoints that is readable for both humans and machines only with a few steps. Swagger lists all API endpoints with detailed information about them like description, parameters and output schema in JSON format while Swagger-UI provides a styled interface with the ability to test the endpoints.
Swagger 2 still works with Spring Boot 2, but it doesn’t integrate well and you might encounter some inconvenience, therefor, it’s better to use swagger 3 with Spring Boot 2.
So let’s jump right in to the simple steps:
- Adding dependencies
Add the 3rd version springfox-boot-starter and springfox-swagger-ui to pom.xml for maven project
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency><dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
or to gradle file for gradle project
repositories {
jcenter()
}
dependencies {
implementation "io.springfox:springfox-boot-starter:3.0.0"
compile "io.springfox:springfox-swagger-ui:3.0.0"
}
2. Configuration
Swagger configuration is done using Docket Bean, below is a simple configuration to integrate Swagger with Spring Boot, you can add more customization to your documentation in the Docket Bean, also you may create more than one Docket Bean.
@Configuration
public class SpringFoxConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
3. Verification
Verification URI has been changed from what used to be in version 2, for JSON output http… your-app-root/v2/api-docs , for a human readable documentation provided by swagger-UI use http..your-app-root/swagger-ui/index.html
Resource: https://springfox.github.io/springfox/docs/current/