Swagger UI tutorial for Spring Boot users

This article will show you how to document and interact with your Spring Boot REST Services using Swagger UI. For the purpose of this example, we will be using springdoc-openapi library.

Getting started with SpringDoc OpenAPI

This java library lets you automate the generation of REST API documentation for your Spring Boot projects. Springdoc-openapi, behind the hoods, examines the application at runtime to infer API semantics based on spring configurations, class structure and various annotations.

Let’s create a simple REST project as an example:

spring init -dweb swagger-demo

Then, add SpringDoc OpenAPI dependency to it:

<dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>1.6.6</version>
</dependency>

Within our Project, we will add a minimalist Controller:

@RestController
public class CustomerController
{
   @Autowired
   CustomerRepository repository;

    @RequestMapping("/list")
    public List<Customer> findAll()
    {
        return repository.getData();
    }

    @RequestMapping("/one/{id}")
    public Customer findOne(@PathVariable int id)
    {
        return repository.getData().get(id);

    }
}

For the sake of brevity we don’t include also the CustomerRepository and Customer Class. You will find the full source code of this project is available at the end of this tutorial.

Include as well an Application Class to bootstrap your Spring Boot application:

@SpringBootApplication

public class DemoApplication {

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

   
}

You are now ready to go! Launch your application:

mvn install spring-boot:run

Firstly, let’s check that everything works as expected by querying the API Docs for our Controller. This is available at the following default URL: http://localhost:8080/v3/api-docs/ 

Next, access the Swagger UI at: http://localhost:8080/swagger-ui/index.html

Here you can access all the available REST Endpoint and use the default templates to use HTTP Operations:

Swagger UI default Path

By default, the Swagger UI is available at the following endpoint:
http://server:port/context-path/swagger-ui.html
To publish the Swagger UI on a different Path, set the following property in your application.properties file:

# swagger-ui custom path
springdoc.swagger-ui.path=/custom-swagger-ui.html

How to customize the Operation description

There is a set of annotations you can place on your REST operations to provide a description of the single operations. You can also add a custom response description depending on the response code.

As an example, take a look at the following example:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;


@RestController
public class CustomerController
{
   @Autowired
   CustomerRepository repository;

   @Operation(summary = "List all customers")
   @ApiResponses(value = { 
     @ApiResponse(responseCode = "200", description = "Found the following customers", 
       content = { @Content(mediaType = "application/json", 
         schema = @Schema(implementation = Customer.class)) }),
     @ApiResponse(responseCode = "500", description = "Internal server error", 
       content = @Content)}) 
    @RequestMapping("/list")
    public List<Customer> findAll()
    {
        return repository.getData();
    }

    @RequestMapping("/one/{id}")
    public Customer findOne(@PathVariable int id)
    {
        return repository.getData().get(id);

    }
}

As you can see, the findAll method now has a custom @Operation summary and two custom responses as a result of the response code.

Further customizations you can apply

Out of the box, all packages will be available in the Swagger UI. To restrict the list of packages you want to make accessible from the UI, you can use the following property:

springdoc.packagesToScan=com.sample, com.demo

Furthermore, you can set list of paths to include using the following property:

springdoc.pathsToMatch=/v1, /api/balance/**

Source code

The source code for this article is available here: https://github.com/fmarchioni/masterspringboot/tree/master/rest/swagger-demo