Spring Boot Swagger Example (2024)
In this tutorial, we'll show you how to use Swagger 2 with Spring Boot application.
You can refer Spring Boot + Swagger 3 Example from here.
Spring Boot Swagger Tutorial :
What is Swagger?
Swagger is a JSON-based interface description language for specifying RESTful APIs for microservices/spring boot applications. To design, construct, describe, and consume RESTful web services, Swagger is used in conjunction with a set of open-source software tools. Automated documentation, code generation, and test-case generation are all included in Swagger.
Let's create Spring Boot Project from Spring Initializer site https://start.spring.io/
Project Structure
Maven Dependency
Add springfox-swagger2
and springfox-swagger-ui
dependencies for swagger2
in pom.xml file.
<?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>com.techgeeknext</groupId>
<artifactId>spring-boot-swagger2-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-swagger2-example</name>
<description>Demo project for Spring Boot Swagger2</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Take a look at our suggested posts:
Swagger2 Configuration
Add Class to manage swagger configuration.
package com.techgeeknext.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
@Configuration
@EnableSwagger2
public class Swagger2Config {
/**
* Method to set paths to be included through swagger
*
* @return Docket
*/
@Bean
public Docket configApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).pathMapping("/").select()
.paths(regex("/api.*")).build();
}
/**
* Method to set swagger info
*
* @return ApiInfoBuilder
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("").description("").version("1.0").build();
}
}
Rest Controller
Create controller class to test swagger documentation using rest endpoint.
package com.techgeeknext.controller;
import com.techgeeknext.model.User;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Api(value = "User Rest Controller", description = "REST API for User")
@RequestMapping("/api")
@RestController
public class Swagger2RestController {
List<User> users = new ArrayList<User>();
{
users.add(new User(1,"TechGeekNext-User1", "ADMIN", "user1@test.com"));
users.add(new User(2,"TechGeekNext-User2", "SUPERVISOR", "user2@test.com"));
users.add(new User(3,"TechGeekNext-User3", "USER", "user3@test.com"));
users.add(new User(4,"TechGeekNext-User4", "USER", "user4@test.com"));
}
@ApiOperation(value = "Get Users ", response = Iterable.class, tags = "getUsers")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success|OK"),
@ApiResponse(code = 401, message = "Not Authorized!"),
@ApiResponse(code = 403, message = "Forbidden!"),
@ApiResponse(code = 404, message = "Not Found!") })
@RequestMapping(value = "/getUsers")
public List<User> getUsers() {
return users;
}
@ApiOperation(value = "Get User by User Id ", response = User.class, tags = "getUserById")
@RequestMapping(value = "/getUser/{id}")
public User getUserById(@PathVariable(value = "id") int id) {
return users.stream().filter(x -> x.getId()==(id)).collect(Collectors.toList()).get(0);
}
@ApiOperation(value = "Get User by role ", response = User.class, tags = "getUserByRole")
@RequestMapping(value = "/getUser/role/{role}")
public List<User> getUserByRole(@PathVariable(value = "role") String role) {
return users.stream().filter(x -> x.getRole().equalsIgnoreCase(role))
.collect(Collectors.toList());
}
}
@Api
- This annotation should be used to provide basic information about the controller.@ApiOperation and @ApiResponses
- These annotations can be added to any rest method in the controller to provide basic information about that method.
Model Object
Create User class and provide @ApiModelProperty
annotation in the Model attributes to provide some description
to the Swagger output for model properties.
package com.techgeeknext.model;
import io.swagger.annotations.ApiModelProperty;
public class User {
@ApiModelProperty(notes = "User Id",name="id",required=true,value="1")
private int id;
@ApiModelProperty(notes = "User Name",name="name",required=true,value="test name")
private String name;
@ApiModelProperty(notes = "User Role",name="role",required=true,value="test role")
private String role;
@ApiModelProperty(notes = "User Email Id",name="email",required=true,value="test email")
private String email;
public User(int id, String name, String role, String email) {
this.id = id;
this.name = name;
this.role = role;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", role='" + role + '\'' +
", email='" + email + '\'' +
'}';
}
}
Swagger 2 JSON Api Docs
Start the server by running maven build. The whole documentation should be available in JSON format if you open the link http://localhost:8080/v2/api-docs. This is not very easy to read and understand; nonetheless, Swagger has offered it for usage in other systems, such as API management tools, which provide features such as API gateways, API caching, API documentation, and so on.
Swagger2 UI Docs
Open http://localhost:8080/swagger-ui.html in browser to view the Swagger UI documentation.
You can expand any operation or rest end point and test as given below:
Download Source Code
The full source code for this article can be found on below.Download it here - Spring Boot Swagger Example