Introducing Swagger To Spring Boot

Using swagger with your spring boot application is a great idea. It will automate documentation your api as well as provide a nice user inteface to test your apis. And enabling swagger to your spring boot application is easy with the following 2 steps.

Step#1: Add maven dependencies to you pom.xml

Add the following maven dependencies to your pom.xml to introduce swagger to your spring boot project. "springfox-swagger2" is to add necessary dependecies to enable swagger on your spring boot project and "springfox-swagger-ui" to add necessary dependecies to enable swagger-ui in your spring-boot project.

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

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

Step#2: Enable Swagger with @EnableSwagger2

Add @EnableSwagger2 annotation to the class with main method in your spring boot application as below. You can also configure to any other class annotated with @Configuration. I will suggest to put it in the class with main method, where you have your @SpringBootApplication annotation.

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@SpringBootApplication
public class Application {

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

}

Now you are done. Run your spring boot application and access the swagger ui as below :

http://{hostname}:{port}/swagger-ui.html

Now you can see all your apis at one place exposed by your spring boot application as well as test them using the same interface.I hope with this 2 steps you can make your spring boot application more powerful. It will also acclerate your team's efficiency with regards to development, documentation and testing of your apis.








No comments:

Post a Comment