How to Add Swagger to a Spring Boot REST API Project

In this tutorial, you will learn how to add Swagger or an OpenAPI support to your Spring Boot project so that you can start documenting your REST API.

To be able to follow this tutorial you will need to have your REST API Spring Boot project created. If you do not have one, here is a very short tutorial(includes video) that teaches you how to Create a Simple Web Service Project with Spring Boot.

Add Swagger Dependencies to POM.XML

Open pom.xml file and add the following dependencies:

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

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

Create @Configuration File

The next step will be to create a configuration file. The purpose of this configuration file is to configure basePackage and selectors of your project and to make the configured Docket bean available in your application. Once you create this configuration file, there is a lot will be done by the framework behind the scenes.

Below is an example of a very simple configuration file:

package com.appsdeveloperblog.app.ws;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
   @Bean
   public Docket apiDocket() {
       
       Docket docket =  new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.appsdeveloperblog.app.ws"))
                .paths(PathSelectors.any())
                .build();
       
       return docket;
       
    } 
}

There are a couple of very important details to note in the above code snippet:

  • apis() – here you specify classes which need to be included in Swagger. I provided the base package of my project and thus delegate the job of finding the needed classes to the framework. The base package will be scanned by the framework and needed classes will be included based on the annotations they have,
  • paths() – here we specify the methods(which are annotated with @Path annotation) from the Controller classes which should be included. Since I want all methods to be included in my documentation created with Swagger, I provide the PathSelectors.any()

Swagger and Spring Security

If you RESTful Web Service application is using Spring Security then you will need to do a little of configuration in your Java class which extends the WebSecurityConfigurerAdapter and which is annotated with @EnableWebSecurity annotation.

Open the Java class in your Spring Boot project which extends the WebSecurityConfigurerAdapter and which is annotated with @EnableWebSecurity annotation and then enable the following paths:

.antMatchers("/h2-console/**")
.permitAll()
.antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
.permitAll()
.anyRequest().authenticated()

below is an example of my Web Security class with Swagger and other endpoints configured. Please disregard other details if they are not relevant to your project.

package com.appsdeveloperblog.app.ws.security;

import com.appsdeveloperblog.app.ws.service.UserService;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    private final UserService userDetailsService;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    public WebSecurity(UserService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().
                authorizeRequests()
                .antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL)
                .permitAll()
                .antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
                .permitAll()
                .anyRequest().authenticated().and()
                .addFilter( new AuthenticationFilter(authenticationManager()) )
                .addFilter( new AuthorizationFilter( authenticationManager() ))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        
        http.headers().frameOptions().disable();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

 
}

Generate Swagger API Documentation JSON

If we run our application now we can get the generated by Swagger JSON documentation of our REST API by opening the following URL in the browser window. I assume you are running your Spring Boot application locally, if so the try this URL:

http://localhost:8080/<CONTEXT PATH HERE>/v2/api-docs

Please note: 

In the URL above you will need to make sure that you provide a correct port number and the Context Path if you have provided one in your application.properties file. If you do not have the context path configured in your application.properties file, then do not provide any context path in the URL above.

For example, if your application properties file has the following entry:

server.servlet.context-path=/mobile-app-ws
server.port=8888

then you will need to open the /v2/api-docs or the swagger-ui.htm pages this way:

http://localhost:8888/mobile-app-ws/swagger-ui.html

and

http://localhost:8888/mobile-app-ws/v2/api-docs

When you open your browser window, you should see something like this:

You can copy the JSON from this window and preview it in the Swagger Editor project here: https://editor.swagger.io

Swagger Documentation Web UI

Provided that you have added the above-mentioned Swagger and the SpringFox dependencies, you can now preview your Swagger documentation in a very user-friendly Web UI.

To preview your REST API documentation in a user-friendly web interface, open the following URL in your browser window. Please note that your Spring Boot app needs to be running.

http://localhost:8888/<CONTEXT PATH HERE>/swagger-ui.html

Please note that: 

In the URL above you will need to make sure that you provide a correct port number and the correct Context Path if you have provided one in the application.properties file of your Spring Boot project. If you do not have the context path configured in your application.properties file, then do not provide any context path in the URL above.

When you open the above URL in the browser window, you should see something like this:

Send HTTP Requests with Swagger

How when you have Swagger added to your project, you can use its Swagger UI page to work with your API, send HTTP requests and receive HTTP responses.

  1. Open the above mentions Swagger UI page using the same URL:
http://localhost:8888/<CONTEXT PATH HERE>/swagger-ui.html

2. Click on one of the API Requests. For example, for me to be able to GET or UPDATE user details I first need to create user details, so I will click on HTTP Post requests and start with that.

3. Once you have the above view opened, click on the Try it out button, so you can provide HTTP Body payload. So I clicked on the Try it out button and then replaced the content in the Example Value text field with the JSON payload I want to send in HTTP Request body. Also, notice that below the Example value text field, I have changed the Parameter Content Type option to application/json.

4. Click on the blue button with label Execute to send the HTTP Request. Once I clicked on the Execute button I got the Response back which is on the picture below. Note, that in the case of your HTTP Request, you will get a different HTTP Response.

I hope this tutorial on how to add Swagger to your Spring Boot project was helpful to you. If you would like to learn Swagger in greater details and enjoy learning by watching video lessons, then have a look at the list of below video courses. One of them might be just what you are looking for.


Leave a Reply

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