This tutorial will show you how to use swagger 2 using spring boot application for creating RESTful documentation. We create and deploy REST services but we do not have an option to let others know in a single place, where REST services are exposed for consumption. We do not have option to let others know that these are the methods, request body, request params for these exposed REST services. But luckily we have got simple but powerful API called swagger through which we 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 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.

You may also like to explore Spring REST API with Swagger 2 and Swagger REST API

Prerequisites

Java 8 needs to be installed and configured
Gradle plugin needs to be installed into Eclipse
Gradle 4.x needs to installed and configured
Dependencies : Spring boot, Swagger 2
Knowledge of REST services
Knowledge of Spring

Creating and setting up Gradle project

Create gradle project in Eclipse called SpringBootSwagger using the following gradle dependencies

buildscript {
	ext {
					springBootVersion = '1.5.9.RELEASE'
	}
    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")
	compile("io.springfox:springfox-swagger-ui:2.8.0")
}

I have added swagger dependencies along with spring boot dependencies.

When referring to build directories, the tutorial assumes the standard Gradle build paths for your gradle project:

SpringBootSwagger/src/main/java – Java source directory
SpringBootSwagger/src/main/resources – Resource directory
SpringBootSwagger/src/test/java – Java test directory
SpringBootSwagger/src/test/resources – Resource test directory

Configuring Swagger 2

In Spring Boot application we would like to configuration using Java annotations as much things as possible. To use swagger 2 API we need to use @EnableSwagger2 annotation on the class level. We need to create Docket bean in order to let swagger know where our REST resources are available for documentation. The apiInfo() method shows the title and description on the swagger documentation User Interface in browser. Using Spring Boot we don’t need to configure additional things like MappingJackson2HttpMessageConverter, ResourceHandlers and MessageConverters because these are automatically taken care by Spring Boot configuration.

package com.jeejava.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
	@Bean
	public Docket docket() {
		Docket docket = new Docket(DocumentationType.SWAGGER_2);
		docket.apiInfo(apiInfo()).select()
				.apis(RequestHandlerSelectors.basePackage("com.jeejava.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();
	}
}

Creating REST Controller

Now we will create Spring REST controller class and apply swagger annotations in order to be appeared on the documentation UI. In this example, I have created three REST URIs (two GET and one POST) 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.

package com.jeejava.swagger.rest.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/")
@Api(tags = "Message API", value = "Controller handles different messages")
public class MessageController {
	@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 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);
	}
}

Create main class

Create below main class to start up and deploy the application into default embedded server Tomcat.

package com.jeejava.swagger.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.jeejava.swagger")
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

Changing server port

Create application.properties file and put it under src/main/resources directory with below content.

server.port=9999

Build the application

Execute command – gradle clean build on the project root directory from cmd prompt.

You will see the required jar files get downloaded and finally you would get “BUILD SUCCESSFUL” message.

Run the application

Now once build is successful then refresh the project in Eclipse by doing right-click from option “Gradle -> Refresh Gradle Project”. When workspace build is done, run the main class.

Testing the application

Now open a browser and hit the URL http://localhost:9999/swagger-ui.html in the browser and you will see below screen. Now you can play with the REST services.

spring boot swagger 2

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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