Spring Boot REST API Documentation with Swagger 2

Introduction

This tutorial will show you how to use swagger 2 using Spring Boot application for creating RESTful documentation. You generally create and deploy REST services but you do not have an option to let others know in a single place, where REST services are exposed for consumption or what details are there for a REST API, what is the HTTP method, or what parameters you need to pass in the request or what you are expecting as a response from the REST service, etc.

Luckily you have got simple but powerful API called swagger through which you can document such RESTful services in a single place in order to let others know about every details (request URI, request body, request params, request method, etc.) of the exposed REST services. This API is a third party API because developers do not have option to generate RESTful documentation using JAX-RS (JSR-339). After completing the Spring Boot REST API Documentation with Swagger 2 example, you will understand the usage of this wonderful API and you will be able to apply the similar concept for your own projects.

The Swagger specification is a powerful definition format to describe RESTful APIs. The Swagger specification creates a RESTful interface for easily developing and consuming an API by effectively mapping all the resources and operations associated with it. It’s easy-to-learn, language agnostic, and both human and machine readable.

Related Posts

spring boot rest api documentation with swagger 2

Spring Boot Swagger 2 – Prerequisites

Java 1.8+, Spring Boot 1.5.9 – 2.5.4, Swagger 2.8.0 – 3.0.0

Spring Boot Swagger 2 – Project Setup

Create a gradle or maven based project in your favorite IDE or tool. The name of the project is spring-boot-swagger.

If you are creating gradle based project then you can use the following build.gradle script.

buildscript {
	ext {
	    springBootVersion = '1.5.9.RELEASE' to '2.5.4'
	}
    repositories {
    	mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
repositories {
	mavenLocal()
    mavenCentral()
}
dependencies {
	compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
	compile("io.springfox:springfox-swagger2:2.8.0") //3.0.0
	compile("io.springfox:springfox-swagger-ui:2.8.0") //3.0.0
}

If you are creating maven based project then you can use the following pom.xml file:

<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.roytuts</groupId>
	<artifactId>spring-boot-swagger</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>8</maven.compiler.source>
		<maven.compiler.target>8</maven.compiler.target>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.4</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<!-- <dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-boot-starter</artifactId>
			<version>3.0.0</version>
		</dependency> -->

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>3.0.0</version>
		</dependency>

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>3.0.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

One thing to note here is that if you are using dependency having artifact id springfox-boot-starter, then you don’t need to add dependency having artifact id springfox-swagger-ui and it will automatically be included into your class path.

Spring Boot Swagger 2 Configuration

In Spring Boot application you would like to have configurations using Java annotations. To use swagger 2 API you need to use @EnableSwagger2 annotation on the class level. You need to create Docket bean in order to let swagger know where your REST resources are available for documentation.

The apiInfo() method shows the title and description on the swagger documentation when accessed through User Interface in the browser. Using Spring Boot you don’t need to configure additional things like MappingJackson2HttpMessageConverter, ResourceHandlers and MessageConverters because these are automatically taken care of by Spring Boot configuration.

@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Bean
	public Docket docket() {
		Docket docket = new Docket(DocumentationType.SWAGGER_2);
		docket.apiInfo(apiInfo()).select()
				.apis(RequestHandlerSelectors.basePackage("com.roytuts.spring.boot.swagger.rest.controller"))
				.paths(PathSelectors.any()).build();
		return docket;
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("RESTful API").description("Browse and interact with RESTful API dynamically")
				.build();
	}

}

I have configured swagger for all REST APIs by setting base package for the REST APIs. You can also configure swagger for specific REST APIs.

Spring REST Controller

Now I will create Spring REST controller class and apply swagger annotations in order to be appeared on the documentation UI (User Interface). In this example, I have created three REST URIs (two with HTTP GET and one with HTTP POST methods) for testing purpose. You may add more or as per your requirements. Once you access swagger documentation you will be able to know how easily these services can be tested.

I have added error response message for HTTP status 404, you can add more error messages based on other HTTP status code.

@RestController
@Api(tags = "Message API", value = "Controller handles different messages")
public class GreetingController {

	@GetMapping("/hello")
	@ApiOperation(value = "Returns a String", notes = "Method to return a string message.")
	@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
			@ApiResponse(code = 404, message = "The resource not found") })
	public ResponseEntity<String> getMsg() {
		return new ResponseEntity<>("Hello, Welcome to Swagger", HttpStatus.OK);
	}

	@GetMapping("/hello/{name}")
	@ApiOperation(value = "Returns a String with name", notes = "Method to return a string message with name.")
	@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
			@ApiResponse(code = 404, message = "The resource not found") })
	public ResponseEntity<String> getMsg(@PathVariable String name) {
		return new ResponseEntity<>("Hello " + name, HttpStatus.OK);
	}

	@PostMapping("/hello")
	@ApiOperation(value = "Returns a String with name", notes = "Method to return a string message with name.")
	@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
			@ApiResponse(code = 404, message = "The resource not found") })
	public ResponseEntity<String> msg(@RequestBody String name) {
		return new ResponseEntity<>("Hello " + name, HttpStatus.OK);
	}

}

Spring Boot Main Class

Create below main class to start up and deploy the application into default embedded server Tomcat. @SpringBootAPplication is sufficient to deploy the Spring Boot application into the embedded Tomcat server.

@SpringBootApplication
public class SpringSwaggerApp {

	public static void main(String[] args) {
		SpringApplication.run(SpringSwaggerApp.class, args);
	}

}

Spring Boot Swagger – Testing The Application

Now open a browser and hit the URL http://localhost:8080/swagger-ui.html (if swagger version < 3) or http://localhost:8080/swagger-ui/ (if swagger version = 3) in the browser and you will see below screen. Now you can test the REST services whether they are giving you the expected response or not.

The important point here is to don’t forget to put “/” at the end when you are accessing the swagger UI URL for swagger version 3: http://localhost:8080/swagger-ui/

Swagger Version 3

spring boot swagger 2

Swagger Version < 3

Note that the following image is the old image and the spring boot application was running on port 9999.

spring boot swagger 2

Now click on any endpoint to see the details. To test any endpoint, click on Try Out, then put any parameter value if required, followed by Execute. You will get the response.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *