11 June 2016


Swagger is a simple yet powerful representation of your RESTful API. Swagger is an open source software. With a Swagger-enabled API, you get interactive documentation.Swagger supports almost every modern programming language and deployment environment. From Swagger-UI, developer can test the exposed REST services as well.

Steps to write code

  • In this example, I am going to show how to integrate Swagger with a Spring boot applicaton. In my previous blog, I have shown how to create a spring boot application. In this blog, I shall integrate swagger just making 3 changes in the previous code i.e.

    • springfox dependency to be added
    • Configuration file (WebConfig.java in this example) has to be marked with @EnableSwagger2 annotation.
    • CORS to be enabled in your application
  • Run the spring boot application and access http://localhost:8080/v2/api-docs from your browser. If you get the response then you are done with your integration.
  • Open Swagger-UI. If you do not have Swagger-UI then download it from here, unzip and go to dist folder and open index.html file in a browser.

Change details

Below are the three changes to integrate Swagger with Spring application

  • springfox dependancy in pom.xml

	<!-- SWAGGER Integration START -->
	<!-- SWAGGER Integration END -->
  • In our previous example we have marked the configuration file (WebConfig.java in this example) with @EnableSwagger2 annotation. The code snippet is given below

public class WebConfig extends SpringBootServletInitializer {

  • Create a new file to allow CORS

package com.ashish.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

public class WebMvcInitializer extends WebMvcConfigurerAdapter {
	public void addCorsMappings(CorsRegistry registry) {

The response from http://localhost:8080/v2/api-docs URL will get displayed in swagger UI as shown below. It lists all the available services automatically. You would be able to test your services as well from the swagger UI

blog comments powered by Disqus