So you have written your spring rest apis and it’s time to share it with front-end developers so that they can integrate with it.

Your front-end developers will need all the rest api endpoints and the request method, request parameters, request body and response format of each endpoint.

How will you share all the information about your apis? It’s very difficult and time-consuming to document all the apis manually.

Moreover, if you document your apis manually, you’ll have to change your documentation every time you do some changes in your apis.

Well! What if I tell you that you can automate all these stuff using an amazing tool called Swagger?

What is Swagger?

Swagger is the world’s most popular API framework with support for over 40 different languages. You can use swagger to design, build and document your rest apis.

In this blog post, we’ll learn how to use Swagger to document rest apis written in java and Spring framework.

Swagger creates a beautiful and interactive documentation for all your rest apis with very little integration code.

So, Let’s integrate swagger with Spring and give life to our rest apis.

Integrating Swagger with Spring

1. Add Swagger dependencies

Swagger specifications are implemented by Springfox suit of java libraries.

We’ll need to add Springfox dependencies to integrate Swagger with Spring. We will be using Springfox’s Swagger 2 dependencies to get the latest features of Swagger.

Maven

If you use maven, add the following dependencies to your pom.xml file

<dependencies>
	<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>
</dependencies>

Gradle

If gradle is the build system of your choice, then you can add the following dependencies to your build.gradle file -

compile "io.springfox:springfox-swagger2:2.6.1"
compile 'io.springfox:springfox-swagger-ui:2.6.1'    

2. Swagger Configuration

I usually create a SwaggerConfig.java file inside config package of my application and write all the Swagger configurations in this file -

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
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 api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(paths())
                .build();
    }

    // Describe your apis
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger Sample APIs")
                .description("This page lists all the rest apis for Swagger Sample App.")
                .version("1.0-SNAPSHOT")
                .build();
    }

    // Only select apis that matches the given Predicates.
    private Predicate<String> paths() {
    	// Match all paths except /error
        return Predicates.and(
        	PathSelectors.regex("/.*"), 
        	Predicates.not(PathSelectors.regex("/error.*"))
        );
    }
}

The @EnableSwagger2 annotation is used to enable Swagger 2 support for the application.

All the configuration is done through the Docket Bean. You can give a title and write a nice description for your apis using apiInfo configuration.

Also, you can decide which apis to include in the documentation by selecting paths which matches your predicates.

The configuration above is enough for integrating Swagger in Spring boot applications. You can now run your application and go to /swagger-ui.html endpoint to access swagger documentation.

Swagger Documentation

Awesome! That’s how simple it is to integrate Swagger in Spring Boot projects. However, for non spring-boot projects, we need few additional integration code.

Configuration for non spring boot projects

If you are not using Spring boot in your project, then /swagger-ui.html endpoint will give 404 not found error because no resource handler is configured for this endpoint.

When you integrate Swagger with Spring boot, it automatically configures all the resource handlers for you. But with Spring, you’ll have to do it yourself.

Fortunately, it’s not that difficult to do. Just create a WebMvcConfig.java file inside config package of your project with the following contents -

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

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

If you’ve already extended WebMvcConfigurerAdapter in some config class of your project then just add the above resource handlers and you’re ready to go.

That’s all you have to do for making Swagger work in non spring boot projects. Please verify it by opening /swagger-ui.html endpoint in your browser.

Conclusion

Swagger is very helpful for automating the documentation of your apis. I use it in almost all of my projects.

In this blog post, we integrated swagger with very basic configurations but Springfox has a lot to offer in terms of documenting your apis.

Checkout Springfox documentation for more configuration options.

As always, Thank you for reading my blog. Please let me know if you get stuck anywhere while integrating swagger in your project by commenting in the comment section below.