Integrating Swagger 3 (OpenAPI Specification) with Spring Boot: A Comprehensive Guide

In this post, we’ll talk about integrating Swagger 3 with Springboot to create models and API documentation using OpenAPI.

What is Swagger?

Swagger is an open-source software framework for designing, building, and documenting RESTful APIs. It uses a specification format known as the OpenAPI Specification to describe the structure of an API and enable interactive documentation, client generation, and server stub generation. Swagger provides a simple, easy-to-use interface for developers to interact with APIs and helps to ensure consistency and scalability of these APIs.

What is Open API?

The OpenAPI Specification (OAS) is a standardized, language-agnostic, and human-readable format for describing RESTful APIs. It is used to define the structure of an API, including its endpoints, request and response parameters, authentication methods, and more. The OpenAPI Specification is the foundation of the Swagger framework and provides a way for developers to describe and document their APIs in a machine-readable format.

Let us see an example for Generating models and API Documentation,

Project Structure:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javainfinite</groupId>
	<artifactId>swagger</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>swagger</name>
	<description>Open-UI and Models for Swagger</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

We have included the necessary dependency for integrating swagger 3 OpenAPI with our springboot application.

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

Employee.java

package com.javainfinite.swagger.model;

import io.swagger.v3.oas.annotations.media.Schema;

@Schema
public class Employee {

    @Schema(name = "Employee ID", description = "Employee Unique ID", required = true, minLength = 2,
            defaultValue = "3546")
    private Integer employeeId;

    @Schema(name = "Employee Name", description = "Employee Name", defaultValue = "Alpha")
    private String employeeName;

    @Schema(name = "Employee Department", description = "Employee working Department", defaultValue = "Development")
    private String employeeDepartment;

    public Integer getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(Integer employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeDepartment() {
        return employeeDepartment;
    }

    public void setEmployeeDepartment(String employeeDepartment) {
        this.employeeDepartment = employeeDepartment;
    }
}

To help Swagger comprehend how to construct the model, we developed a model class and included annotations relating to Swagger.

@Schema:

The @Schema annotation is used in the OpenAPI Specification to define the structure of a data model or an object in an API. We can also define various properties with Schema annotation like default value, minimum length, maximum length, required attribute etc.

SwaggerController.java

package com.javainfinite.swagger.controller;

import com.javainfinite.swagger.model.Employee;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@RestController
public class SwaggerController {

    @PostMapping(value = "/employee", consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @Tag(name = "Employee details", description = "Employee Releated Information")
    @Operation(description = "Employee Sample API")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "201", description = "Employee successfully saved"),
            @ApiResponse(responseCode = "404", description = "Employee Not Found", content = @Content)
    })
    public Employee saveEmployee(@RequestBody Employee employee) {

        return employee;
    }

    @GetMapping(value = "/employee/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @Tag(name = "Employee details", description = "Employee Releated Information")
    @Operation(description = "Get employee details")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Employee Found"),
            @ApiResponse(responseCode = "404", description = "Employee Not Found", content = @Content)
    })
    public Employee getEmployee(@PathVariable(value = "23", required = true) Integer id) {

        return new Employee();

    }

    @GetMapping(value = "/manager")
    @Tag(name = "Manager Details", description = "Manager Related Information")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Manager Found"),
            @ApiResponse(responseCode = "404", description = "Manager Not Found", content = @Content)
    })
    public String getManager() {
        return "Manager available";
    }


}

@Tag:

The @Tag annotation is used in the OpenAPI Specification (part of the Swagger framework) to group related endpoints or operations under a common category.

@Operation:

@Operation annotation is used in the OpenAPI Specification (part of the Swagger framework) to define a single operation or endpoint in an API. An operation represents a single request/response interaction between a client and a server, and is defined by its method (e.g. GET, POST, PUT, etc.), path, parameters, and expected responses.

@ApiResponses:

The @ApiResponses annotation is used in the OpenAPI Specification (part of the Swagger framework) to specify the possible responses that an API operation can return. This annotation provides a way to define a set of response objects, each of which corresponds to a specific HTTP status code and describes the expected structure of the response body.

SwaggerApplication.java

package com.javainfinite.swagger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SwaggerApplication {

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

}

Now let us run our application,

Let us go to browser and type,

http://localhost:8080/swagger-ui.html,

We have our Employee model generated in Swagger,

@Tag has grouped the related API’s together,

Let us try to look into our Post – /employee endpoint,

We have our responses @ApiResponses – 201 and 404 and also @Operation information.

Let us try to look into our Get method,

How can we generate API Documentation?

http://localhost:8080/swagger-ui/v3/api-docs.yaml

This will generate a yaml file with all the API’s information. Below us the yaml file generated by the above mentioned URL.

openapi: 3.0.1
info:
  title: OpenAPI definition
  version: v0
servers:
- url: http://localhost:8080
  description: Generated server url
tags:
- name: Employee details
  description: Employee Releated Information
- name: Manager Details
  description: Manager Related Information
paths:
  /employee:
    post:
      tags:
      - Employee details
      description: Employee Sample API
      operationId: saveEmployee
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Employee'
        required: true
      responses:
        "201":
          description: Employee successfully saved
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Employee'
        "404":
          description: Employee Not Found
  /manager:
    get:
      tags:
      - Manager Details
      operationId: getManager
      responses:
        "200":
          description: Manager Found
          content:
            '*/*':
              schema:
                type: string
        "404":
          description: Manager Not Found
  /employee/{id}:
    get:
      tags:
      - Employee details
      description: Get employee details
      operationId: getEmployee
      parameters:
      - name: "23"
        in: path
        required: true
        schema:
          type: integer
          format: int32
      responses:
        "200":
          description: Employee Found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Employee'
        "404":
          description: Employee Not Found
components:
  schemas:
    Employee:
      required:
      - Employee ID
      type: object
      properties:
        Employee ID:
          minLength: 2
          type: integer
          description: Employee Unique ID
          format: int32
          default: 3546
        Employee Name:
          type: string
          description: Employee Name
          default: Alpha
        Employee Department:
          type: string
          description: Employee working Department
          default: Development

We have successfully generated Swagger-ui with all API’s, Swagger models and also generated API Documentation.

By Sri

Leave a Reply

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