Posted by Hayri Cicek on July 28, 2018
In this tutorial we are going to learn how to document our Spring Boot REST APIs using Swagger with Springfox.
Tools You Will Need
Maven 3.3+
Your favorite IDE. I'm using NetBeans
JDK 1.8+
Creating the Project With Spring Initializer
Go to start.spring.io and follow the steps below to generate a new project.
Enter the Details as Follows
Group: com.kodnito Artifact: spring-boot-swagger-springfox Dependencies: WebClick Generate Project to generate and download your project.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Swagger Config
package com.kodnito.springbootswaggerspringfox.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class MySwaggerConfig {
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Hello Swagger APIs")
.description("My APIs is listed here")
.version("0.0.1-SNAPSHOT")
.build();
}
}
@EnableSwagger2 annotation enables Springfox Swagger 2
package com.kodnito.springbootswaggerspringfox.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api("This is The Hello Swagger API Documentation")
public class HelloSwaggerController {
@GetMapping("/hello-swagger")
@ApiOperation("Return String hello swagger")
public String helloSwagger() {
return "hello swagger";
}
@PostMapping("/post-hello")
@ApiOperation("This is the POST request")
public String postReq() {
return "post";
}
}
Now, enter the http://localhost:8080/swagger-ui.html in browser's address bar and access your new Swagger documentation. Share this: