Streamlining API Documentation: Integrating Swagger 3 with Spring Boot


Introduction

In case of microservice's application, where you have a number of microservice's running and communicating using REST API's, it becomes hard to go through the code and understand what a REST service consumes and produces and then test it using curl or postman or on any such tool and then use it in code.

To answer this issue, we have Swagger UI (also know as Open API) which is used to document the API's. A swagger UI helps us understand what a particular URL consumes and produces. We can even consume the API through Swagger UI by passing what it needs and get the result in both successful and failure scenario. It has a robust documentation which is displayed on the Swagger UI thus explaining each parameter and the URL itself.

API documentation is crucial for effective communication and collaboration in software development. Swagger, now known as OpenAPI, provides tools for generating interactive API documentation that enhances the development experience. In this tutorial, we'll explore how to integrate Swagger 3 with a Spring Boot application to automate API documentation generation.

Prerequisites

Before we begin, ensure you have the following:

  • Basic knowledge of Spring Boot and RESTful APIs.
  • JDK installed on your machine (Java 8 or higher).
  • Maven or Gradle for dependency management.
  • IDE (Eclipse, IntelliJ IDEA, etc.) installed.

Step 1: Setting Up a Spring Boot Project

Let's start by setting up a new Spring Boot project using Spring Initializr. Follow these steps:

  1. Go to Spring Initializr.

  2. Fill in the project metadata:

    • Project: Maven or Gradle (choose your preferred build tool).
    • Language: Java.
    • Spring Boot Version: Choose the latest stable version.
    • Group: com.example (or your preferred group identifier).
    • Artifact: swagger3-demo (or your preferred artifact name).
    • Dependencies: Add Spring Web and Springfox for Swagger 3 integration.

  3. Click on Generate to download the project zip file.

  4. Extract the downloaded zip file and open it in your preferred IDE.

Step 2: Configuring Swagger 3 in Spring Boot

Now, let's configure Swagger 3 in our Spring Boot application. We'll create a configuration class to customize Swagger settings and enable API documentation generation.

Create SwaggerConfig.java Configuration Class

java
package com.example.swagger3demo.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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; @Configuration @EnableSwagger2WebMvc public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("com.example.swagger3demo.controllers")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger 3 Demo API") .description("API documentation using Swagger 3 in Spring Boot") .version("1.0.0") .build(); } }

Explanation:

  • @Configuration: Marks the class as a Spring configuration class.
  • @EnableSwagger2WebMvc: Enables Swagger 3 integration with Spring MVC.
  • @Bean public Docket api(): Configures a Docket bean that specifies the Swagger settings.
    • .select(): Initializes a builder for the API selector.
    • .apis(RequestHandlerSelectors.basePackage("com.example.swagger3demo.controllers")): Specifies the base package where Spring will scan for API controllers.
    • .paths(PathSelectors.any()): Specifies which paths to include in the documentation (here, all paths are included).
    • .apiInfo(apiInfo()): Provides metadata about the API (title, description, version).

Step 3: Creating API Controllers with Swagger Annotations

Let's create a simple API controller and annotate it with Swagger 3 annotations to document our APIs.

Create DemoController.java

java
package com.example.swagger3demo.controllers; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") @Tag(name = "Demo API Controller", description = "Operations pertaining to demo API") public class DemoController { @GetMapping("/hello") @Operation(summary = "Get hello message") public String hello() { return "Hello, Swagger 3!"; } }

Explanation:

  • @RestController: Marks the class as a controller that handles RESTful requests.
  • @RequestMapping("/api"): Maps all API endpoints in this controller to /api.
  • @Tag(name = "Demo API Controller", description = "Operations pertaining to demo API"): Provides a tag for grouping related operations in Swagger UI.
  • @GetMapping("/hello"): Maps HTTP GET requests on /api/hello to the hello() method.
  • @Operation(summary = "Get hello message"): Provides a summary for the hello() operation in Swagger UI.

Step 4: Running and Testing Swagger UI

Now, let's run our Spring Boot application and test the Swagger 3 integration by accessing Swagger UI in a web browser.

  1. Run the Spring Boot application:

    • Open your IDE.
    • Right-click on the main class (Swagger3DemoApplication) and select Run As > Spring Boot App.
  2. Open a web browser and navigate to http://localhost:8080/swagger-ui/index.html.

    • You should see Swagger UI loaded with your API documentation.
  3. Explore the documented APIs:

    • Expand the Demo API Controller tag.
    • Click on GET /api/hello to view details about the hello() operation, including parameters and responses.

Conclusion

In this tutorial, we've covered how to integrate Swagger 3 with a Spring Boot application for automated API documentation generation. By following these steps, you can enhance your API development process with clear and interactive documentation that improves collaboration and understanding among team members.

Additional Resources

Final Thoughts

Effective API documentation is essential for building and maintaining successful software projects. With Swagger 3 and Spring Boot, you can streamline the documentation process and ensure that your APIs are well-documented and easy to understand. Happy documenting!

Post a Comment

0 Comments