Spring Boot Swagger Example

Setting Up Swagger 2 with a Spring REST API

Spring Boot Swagger Example: In modern applications, back-end and front-end components exist separately. Back-end components are often REST API while third-party application integrations make the front-end.

In the world of development, documentation is often a tedious task but it is inevitably a part and parcel of the software development life cycle(SDLC).

This is where Swagger comes as a savior.

Table of Contents

What is Swagger?

Swagger is an Interface Description Language for describing RESTful APIs expressed using JSON. Swagger is used together with a set of open-source software tools to design, build, document, and use RESTful web services. Swagger includes automated documentation, code generation, and test-case generation.

Wikipedia

In this post, I am going to share how to use Swagger 2 in the Spring Boot application with basic configurations as an example.

Adding Maven Dependency to the Spring Boot Project

To use Swagger 2, for Spring projects, the most popular library is Springfox. Basically, it is a suite of Java libraries. It is “Automated JSON API documentation for APIs built with Spring”.

Find more in its official documentation. Its open-source Git project and documentation can be found here.

Add the following dependencies in your pom.xml.

<!-- Spring Fox Dependencies -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>Code language: HTML, XML (xml)

Create Spring Boot Swagger Configuration Class

Most of the configurations happen in Docket bean. To understand more about Docket bean, refer to official Springfox documentation.

package com.bhutanio.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    @Bean
    public Docket bookHotelApi() {
        return new Docket( DocumentationType.SWAGGER_2)
                .select()
                .apis( RequestHandlerSelectors.any())
                .paths( PathSelectors.any())
                .build()
                .apiInfo(getApiInfo());
    }

    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger By Bhutan IO")
                .version("1.0")
                .description("Some description here..")
                .contact(new Contact("Bhutan IO", "https://bhutanio.com", "abcde@email.com"))
                .license("Apache License Version 2.0")
                .build();
    }
}Code language: JavaScript (javascript)

Import Swagger Configuration Class in Main Class

Once you are done configuring, all you have to do is import the configuration class with @Import() annotation as shown below.

@Import(SwaggerConfiguration.class)
public class YourAppName{

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

}Code language: JavaScript (javascript)

Wait, if you implemented Spring Security in your project

If you implemented Spring Security in your project, don’t forget to permit access to swagger-ui. Your security configuration should look something like this based on your requirements.

If you do not permit access to the swagger resources, as shown above, you will be redirected to Whitelabel Error Page, even if your Swagger configurations are working fine.

Here is an example to allow access to your swagger-ui. Doing this is prevent your application from getting redirected to Whitelabel Error Page.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/auth/**").permitAll()
            .antMatchers("/v2/api-docs",
                    "/configuration/ui",
                    "/swagger-resources/**",
                    "/configuration/security",
                    "/swagger-ui.html",
                    "/webjars/**")
            .permitAll()
            .anyRequest().authenticated()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and().logout().logoutRequestMatcher( new AntPathRequestMatcher( "/logout" ) ).logoutSuccessUrl( "/login" )
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}Code language: PHP (php)

Conclusion

It is pretty simple to implement swagger in a Spring Project. However, there are several things that you will have to take into consideration as shown above in the example.

If you come across any issues, get in touch with me so that I can assist you in solving your issues.

Leave a Reply

Discover more from BHUTAN IO

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top