Swagger is a tool that allows an application to describe the structure of the APIs. Once the application has the form of the APIs, it can generate documentation for the APIs.

The documentation gets generated with the help of Swagger UI in the form of a web page. The different users of the APIs can then interact with them using the provided web page.

In this tutorial, you will learn how to get started with Swagger UI in Spring Boot.

Prerequisites

Project setup

To create a new project, go to Spring initializr to generate an empty Spring Boot project.

Select Maven in the Project section and Java in the Language section. In the Spring Boot section, select version 2.7.

In the Project Metadata section, enter the respective sections as shown below.

  • Group – com.restapitest
  • Artifact – swagger-ui
  • Package name – com.restapitest.swagger-ui
  • Packaging – Jar
  • Java – 17

The following image shows the dependencies and structure of the project.

Image showing project structure and dependencies

Press the GENERATE button to generate a ZIP file of the project. Unzip the new project, import it in IntelliJ, and add the following dependencies in the pom.xml file.

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
</dependency>

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

The following is a description of these dependencies.

  • Spring Web – Creating RESTful web services using the MVC model.
  • Springfox Swagger2 – design, build, and document RESTful APIs using the OpenAPI specification.
  • Springfox Swagger UI – A user interface to document the APIs as well as test the APIs.
  • Lombok – Generate getters, setters, and other helper methods for the application models.

Configure Swagger

Create a package named config under the package src/main/java/com/restapitest/swaggerui. This package will contain the configuration class.

Create a file named SwaggerConfig.java under the config package and copy and paste the following code into the file.

package com.restapitest.swarggerui.config;

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;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

To configure Swagger, you have defined a @Bean using the docket() method that returns a Docket instance.

The Docket builder is the default entry point into the springfox framework and provides convenient methods to configure it.

Since the Docket builder accepts a parameter for the OpenAPI specification, pass the argument DocumentationType.SWAGGER_2. The argument points to Swagger version 2 which is the latest version.

Calling the select() method on the builder initiates a new builder that will allow you to configure the API selection.

The apis() method configures the request handlers for the APIs. Pass the argument RequestHandlerSelectors.any() to select all the request handlers.

The paths() method configures the paths for the APIs. Pass the argument PathSelectors.any() to select all the paths.

When you call the build() method, the builder initiated by the select() method falls back to building the Docket.

Create a model for an Employee

Create a package named model under the package src/main/java/com/restapitest/swaggerui.

Create a file named Employee.java and copy and paste the following code into the file.

package com.restapitest.swarggerui.model;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class Employee {
    private Integer id;
    private String firstName;

    private String lastName;

    private String email;
}

The Employee class defines a prototype of an employee having the properties firstName, lastName, and email.

You will use this class in the next section to define a collection of employees that will be returned by one of the APIs.

The @Getter annotation will generate the getter methods for the fields. The @AllArgsConstructor annotation will generate a constructor containing all the fields.

Create a repository for the Employee

Create a package named repository under the package src/main/java/com/restapitest/swaggerui.

Create a file named EmployeeRepository.java and copy and paste the following code into the file.

package com.restapitest.swarggerui.repository;

import com.restapitest.swarggerui.model.Employee;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class EmployeeRepository {
    public List<Employee> getEmployees() {
       return List.of(
               new Employee(1,
                       "john",
                       "doe",
                       "john@javawhizz.com"),
               new Employee(2, 
                       "mary",
                       "public",
                       "mary@javawhizz.com"),
               new Employee(3,
                       "charles",
                       "darwin",
                       "charles@javawhizz.com")
       );
    }
}

The @Component annotation enables component scanning so that the class can be injected into other classes.

In this class, you have defined a method named getEmployees() that returns a list of Employees.

The List creates three employees who will be returned once the application gets the API request.

Create a controller for the Employee

Create a package named controller under the package src/main/java/com/restapitest/swaggerui.

Create a file named EmployeeController.java and copy and paste the following code into the file.

package com.restapitest.swarggerui.controller;

import com.restapitest.swarggerui.model.Employee;
import com.restapitest.swarggerui.repository.EmployeeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("api/v1")
@RequiredArgsConstructor
public class EmployeeController {
    private final EmployeeRepository employeeRepository;

    @GetMapping("/employees")
    public List<Employee> getEmployees() {
        return employeeRepository.getEmployees();
    }

    @GetMapping("/employee/{id}")
    public Employee findEmployeeById(@PathVariable("id") Integer id) {
        return employeeRepository.getEmployees()
                .stream()
                .filter(employee -> employee.getId().equals(id))
                .findFirst()
                .orElse(null);

    }
}

The first @GetMapping annotation defines the /employees endpoint that returns a collection of employees using the getEmployees() method.

To return a collection of employees, inject the EmployeeRepository in the class and call the getEmployees() method defined by the repository.

The second @GetMapping annotation defines the /employee/{id} endpoint that returns a single employee that matches the provided ID.

Call the getEmployees() method of EmployeeRepository inside the findEmployeeById() method and filter() the list returned to check if an employee with the provided ID exists.

The findfirst() method returns the first employee that matches the ID. If no match is found the orElse() method returns null.

Run the application

Before running the application, copy and paste the following property into the application.yaml file.

spring:
  mvc:
    path-match:
      matching-strategy: ant_path_matcher

The ant_path_matcher property sets the class responsible for matching the URLs. Generally, the property points to the AntPathMatcher implementation of PathMatcher.

To run the application, press the run icon located on the bottom right side of IntelliJ.

Tool bar containing the run icon of Intellij

Once the application has started, open your browser and go to localhost:8080/swagger-ui.html. You should see the following web page on your browser:

Swagger UI default page
The page contains the documentation of the APIs you have just created and you can also test the APIs on the page.

Test the API for all Employees

To test the /employees API endpoint, press the GET button that makes a request to /api/v1/employees.

Press the try it out button on the section that opens followed by Execute to make a GET request for a collection of employees. You should see the following once the request is complete:

Testing API to get all employees

Test the API for a single Employee

To test the /employee API endpoint, press the GET button that makes a request to /api/v1/employee/{id}.

Press the try it out button on the section that opens, enter the ID of the employee to filter on the id section then press the Execute button to make a GET request for a single employee. You should see the following once the request is complete:

Testing API for getting a single employee

Conclusion

In this tutorial, you have learned how to get started with Swagger using a Spring Boot application. Feel free to play around with the APIs. You can also create new APIs and check if they are being documented by Swagger. The application used a List data structure to test the APIs. However, you can implement your application to read the data from a database or a file. For visual learners, this tutorial is also available on Youtube. The code for this tutorial is also available on GitHub to help you compare the code.

Happy Coding!


0 Comments

Leave a Reply

Avatar placeholder

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