Learnitweb

Swagger with Spring Boot

1. Introduction

In this tutorial, we’ll discuss how to add Swagger to the Spring Boot.

2. Add Swagger Dependency

In pom.xml, add:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.5.0</version> <!-- Use the latest available -->
</dependency>

3. Access Swagger UI

After starting your app, open in browser:

https://localhost:8080/swagger-ui/index.html

4. Annotations

In a Spring Boot application using Springdoc OpenAPI (Swagger), you can use a variety of OpenAPI annotations to document your APIs. These annotations come from the io.swagger.v3.oas.annotations package and help define metadata, parameters, responses, examples, and schema details.

Here’s a complete and detailed list of important Swagger/OpenAPI annotations used in Spring Boot:

4.1 API Documentation Annotations

These are used at the class level or method level to describe the overall controller or endpoint.

@Operation: Describes an individual API endpoint (used on methods).

@Operation(
    summary = "Add a new student",
    description = "This endpoint allows you to add a student to the list"
)

@Tag: Categorizes endpoints under a named section in Swagger UI.

@Tag(name = "Student API", description = "Operations related to student management")

4.2 Parameter Annotations

Used to describe request parameters, headers, or path variables.

@Parameter: Provides details for method parameters like query, path, or header parameters.

@Parameter(description = "ID of the student to retrieve")
@PathVariable int id

@Parameters: Container for multiple @Parameter annotations.

4.3 Request and Response Documentation

@RequestBody

  • Marks a method parameter as the body of the HTTP request.
  • Can be combined with OpenAPI’s @RequestBody (from Swagger) for schema description.
@io.swagger.v3.oas.annotations.parameters.RequestBody(
    description = "Student object to be added",
    required = true
)
public ResponseEntity<Student> addStudent(@RequestBody Student student)

@ApiResponse: Describes a possible response from the API.

@ApiResponse(
    responseCode = "200",
    description = "Student added successfully"
)

@ApiResponses: Group multiple @ApiResponse annotations together.

@ApiResponses({
    @ApiResponse(responseCode = "200", description = "Success"),
    @ApiResponse(responseCode = "400", description = "Invalid input"),
    @ApiResponse(responseCode = "500", description = "Server error")
})

4.4 Schema and Model Annotations

@Schema: Used on model fields or classes to define descriptions, examples, constraints, etc.

@Schema(description = "Name of the student", example = "Alice", required = true)
private String name;

@ArraySchema: Used to describe an array-type response.

@ArraySchema(schema = @Schema(implementation = Student.class))

5. Example Annotations

To show sample values in Swagger UI.

@ExampleObject: Used to define examples for request or response bodies.

@ExampleObject(
    name = "Sample Student",
    summary = "A sample student",
    value = "{\"id\": 1, \"name\": \"Alice\", \"age\": 20}"
)

@Examples: Container for multiple @ExampleObjects.

6. Global Documentation Configuration

@OpenAPIDefinition: Used at the application level to define metadata like title, version, and servers.

@OpenAPIDefinition(
    info = @Info(
        title = "Student Management API",
        version = "1.0",
        description = "API for managing students"
    ),
    servers = @Server(url = "https://localhost:8080", description = "Local Server")
)

7. Miscellaneous

@Hidden: Hides a controller or endpoint from Swagger documentation.

@Hidden
public String internalMethod() {
    // not visible in Swagger UI
}

8. Example Usage in Controller

@RestController
@RequestMapping("/students")
@Tag(name = "Student API", description = "Operations related to students")
public class StudentController {

    @GetMapping
    @Operation(summary = "Get all students", description = "Retrieve the list of all students")
    @ApiResponse(responseCode = "200", description = "Successful operation")
    public List<Student> getAllStudents() {
        return studentList;
    }

    @PostMapping
    @Operation(summary = "Add a new student")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "Student added successfully"),
        @ApiResponse(responseCode = "400", description = "Invalid input")
    })
    public Student addStudent(
        @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "Student object to be added",
            required = true,
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(value = "{\"id\":1,\"name\":\"Alice\",\"age\":20}")
            )
        )
        @RequestBody Student student
    ) {
        studentList.add(student);
        return student;
    }
}