Generate REST API Documentation for Spring Boot Project Using Swagger

Ramesh Fadatare
4 min readFeb 6, 2025

--

In our previous tutorial, we built a Spring Boot CRUD REST API for User Management using Spring Data JPA and MySQL. Now, we will extend that tutorial by generating REST API documentation using Swagger (Springdoc OpenAPI 3).

The prerequisite for this tutorial is you need to first Build RESTful Web Services Using Spring Boot, Spring Data JPA, and MySQL

πŸ“Œ Benefits of Using Swagger

βœ… Automatic API documentation generation.
βœ… Interactive UI for testing APIs.
βœ… Helps frontend developers understand API contracts.
βœ… Supports multiple response types and request schemas.

πŸš€ Step 1: Add Swagger Dependency

Spring Boot does not include Swagger by default, so we need to add the Springdoc OpenAPI dependency.

πŸ“Œ Add the following dependency to pom.xml

<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.8.3</version>
</dependency>

πŸ“Œ Explanation

βœ”οΈ springdoc-openapi-starter-webmvc-ui β†’ Provides a Swagger UI to interact with REST APIs.
βœ”οΈ Version 2.8.3 β†’ Latest stable version for OpenAPI 3.

πŸš€ Step 2: Enable Swagger in Spring Boot

Spring Boot automatically configures Swagger when the dependency is added, so we don’t need additional configuration.

To verify, start your Spring Boot application:

mvn spring-boot:run

Then, open your browser and go to:
πŸ‘‰ Swagger UI: http://localhost:8080/swagger-ui.html
πŸ‘‰ OpenAPI JSON: http://localhost:8080/v3/api-docs

πŸš€ Step 3: Customize the API documentation using OpenAPI 3 annotations in the REST Controller

To customize the API documentation, we use OpenAPI 3 annotations.

πŸ“Œ Modify UserController.java inside net.javaguides.usermanagement.controller

package net.javaguides.usermanagement.controller;

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;
import io.swagger.v3.oas.annotations.tags.Tag;
import net.javaguides.usermanagement.dto.UserDto;
import net.javaguides.usermanagement.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin("*")
@RestController
@RequestMapping("/api/users")
@Tag(name = "User Management", description = "APIs for managing users")
public class UserController {

private final UserService userService;

public UserController(UserService userService) {
this.userService = userService;
}

@Operation(summary = "Create a new user", description = "Add a new user to the system")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User created successfully",
content = @Content(schema = @Schema(implementation = UserDto.class))),
@ApiResponse(responseCode = "400", description = "Invalid request data",
content = @Content(schema = @Schema()))
})
@PostMapping
public ResponseEntity<UserDto> createUser(@RequestBody UserDto userDto) {
return ResponseEntity.ok(userService.createUser(userDto));
}

@Operation(summary = "Get user by ID", description = "Retrieve a user's details using their ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User found",
content = @Content(schema = @Schema(implementation = UserDto.class))),
@ApiResponse(responseCode = "404", description = "User not found",
content = @Content(schema = @Schema()))
})
@GetMapping("/{id}")
public ResponseEntity<UserDto> getUserById(@PathVariable Long id) {
return ResponseEntity.ok(userService.getUserById(id));
}

@Operation(summary = "Get all users", description = "Retrieve a list of all users in the system")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Users retrieved successfully",
content = @Content(schema = @Schema(implementation = UserDto.class)))
})
@GetMapping
public ResponseEntity<List<UserDto>> getAllUsers() {
return ResponseEntity.ok(userService.getAllUsers());
}

@Operation(summary = "Update a user", description = "Update an existing user's details")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User updated successfully",
content = @Content(schema = @Schema(implementation = UserDto.class))),
@ApiResponse(responseCode = "404", description = "User not found",
content = @Content(schema = @Schema()))
})
@PutMapping("/{id}")
public ResponseEntity<UserDto> updateUser(
@PathVariable Long id,
@RequestBody UserDto userDto) {
return ResponseEntity.ok(userService.updateUser(id, userDto));
}

@Operation(summary = "Delete a user", description = "Delete a user from the system using their ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "User deleted successfully"),
@ApiResponse(responseCode = "404", description = "User not found",
content = @Content(schema = @Schema()))
})
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return ResponseEntity.noContent().build();
}
}

πŸš€ Step 4: Explanation of Swagger Annotations

βœ”οΈ @Tag(name = "User Management", description = "APIs for managing users")
➑️ Defines a category for API documentation.

βœ”οΈ @Operation(summary = "...", description = "...")
➑️ Describes the purpose of each API endpoint.

βœ”οΈ @ApiResponses(value = {...})
➑️ Lists possible HTTP responses with status codes.

βœ”οΈ @ApiResponse(responseCode = "200", description = "Success", content = @Content(...))
➑️ Specifies a response type for successful API calls.

βœ”οΈ @ApiResponse(responseCode = "404", description = "User not found")
➑️ Handles cases where resources are missing.

πŸš€ Step 5: Start the Spring Boot Application

πŸ“Œ Run the application using:

mvn spring-boot:run

πŸ“Œ Swagger UI will be available at:
πŸ‘‰ Swagger UI: http://localhost:8080/swagger-ui.html
πŸ‘‰ OpenAPI JSON: http://localhost:8080/v3/api-docs

πŸš€ Step 6: Testing APIs in Swagger UI

1️⃣ Open http://localhost:8080/swagger-ui.html in your browser.
2️⃣ You will see a list of API endpoints for UserController.
3️⃣ Click on any API endpoint (e.g., POST /api/users).
4️⃣ Click Try it out, enter sample data, and click Execute.
5️⃣ Observe the API response and status codes.

🎯 Summary: What We Achieved

βœ”οΈ Added Swagger to our Spring Boot project.
βœ”οΈ Annotated REST Controller with OpenAPI 3 annotations.
βœ”οΈ Generated interactive API documentation.
βœ”οΈ Tested APIs directly from Swagger UI.

πŸŽ‰ Congratulations! You have successfully generated REST API documentation using Swagger! πŸš€πŸ”₯

--

--

No responses yet