Categories
spring-boot

add swagger in spring boot application

In this tutorial, we will learn to add swagger in spring boot application

What is Swagger ?

Swagger is an open-source software framework backed by a large ecosystem of tools that helps developers design, build, document, and consume RESTful web services.

How to add in Spring boot

It is easy to integrate with spring boot. with help of few dependencies and some configuration we can easily integrate with spring boot

Depedency
<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>
Annotation
@EnableSwagger2
Bean
@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
				.paths(PathSelectors.any()).build();
	}
Main Class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

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

@SpringBootApplication
@EnableSwagger2
public class StudentServiceApplication {

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

	@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
				.paths(PathSelectors.any()).build();
	}
}

Time needed: 10 minutes

Steps

  1. dependency in pom.xml

    add above dependency in pom.xml

  2. Annotation in Configuration file

    add above annotation in a configuration file

  3. Bean method

    add above bean

  4. Testing

    Open http://localhost:8080/swagger-ui.html in browserswagger

Conclusion

With the help of two dependencies and one bean method we can easily add swagger in spring boot application

Related Articles

crud operations in spring boot with Mysql

Leave a Reply

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