How to use Swagger with Spring Boot
Swagger is a powerful tool used to document, visualize, and test REST APIs. In Spring Boot applications, Swagger helps developers and testers understand available APIs, request/response structures, and try APIs directly from a browser.
Today, Swagger is officially known as OpenAPI. In Spring Boot, the most commonly used implementation is springdoc-openapi, which automatically generates API documentation.
Why Use Swagger in Spring Boot?
- Automatically generates API documentation
- Provides an interactive UI (Swagger UI) to test APIs
- Improves collaboration between frontend, backend, and QA teams
- Reduces manual API documentation effort
- Helps new developers understand APIs quickly
Swagger vs OpenAPI (Simple Explanation)
- Swagger: Toolset (UI, Editor, Codegen)
- OpenAPI: Specification (standard for describing REST APIs)
Spring Boot uses OpenAPI Specification and renders it using Swagger UI.
Step 1: Add Swagger Dependency in Spring Boot
For Spring Boot (2.x and 3.x), the recommended library is springdoc-openapi.
Maven Dependency
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version>
</dependency>
Once this dependency is added, Swagger is automatically enabled. No additional configuration is required for basic usage.
Step 2: Run the Spring Boot Application
Start your Spring Boot application normally. After startup, Swagger UI becomes available at:
http://localhost:8080/swagger-ui.html
or
http://localhost:8080/swagger-ui/index.html
You will see a web page listing all available REST APIs.
Step 3: Create a Sample REST Controller
Swagger automatically scans REST controllers annotated with
@RestController and maps endpoints.
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public String getUser(@PathVariable int id) {
return "User ID: " + id;
}
@PostMapping
public String createUser(@RequestBody String user) {
return "User created: " + user;
}
}
Once the application is running, these endpoints will automatically appear in Swagger UI.
Step 4: Understanding Swagger UI
Swagger UI provides the following features:
- List of all REST endpoints grouped by controller
- HTTP methods (GET, POST, PUT, DELETE)
- Request parameters and request body
- Response status codes
- "Try it out" button to test APIs live
Step 5: Adding Swagger Annotations (Optional but Recommended)
Swagger annotations help improve documentation clarity. They describe APIs, parameters, and responses in detail.
Common Swagger Annotations
@Operation– Describes an API operation@ApiResponse– Describes API responses@Parameter– Describes parameters@Schema– Describes model fields
Example with Annotations
@Operation(summary = "Get user by ID", description = "Fetch user details using user ID")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "User found"),
@ApiResponse(responseCode = "404", description = "User not found")
})
@GetMapping("/{id}")
public String getUser(
@Parameter(description = "User ID", example = "101")
@PathVariable int id) {
return "User ID: " + id;
}
Step 6: Documenting Request and Response Models
Swagger automatically documents request/response objects.
You can enhance it using @Schema.
public class User {
@Schema(description = "Unique user ID", example = "1")
private int id;
@Schema(description = "User name", example = "Sandeep")
private String name;
@Schema(description = "User email", example = "user@example.com")
private String email;
}
These details will be visible in Swagger UI under Models section.
Step 7: Customizing Swagger Configuration
You can customize API title, description, and version using OpenAPI configuration.
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("User Management API")
.version("1.0")
.description("API documentation for User Management System"));
}
}
Step 8: Securing Swagger UI (Optional)
In production environments, Swagger UI should be secured or disabled. You can:
- Disable Swagger in production profile
- Protect Swagger URLs using Spring Security
Disable Swagger for Production
springdoc.api-docs.enabled=false
springdoc.swagger-ui.enabled=false
Best Practices for Using Swagger in Spring Boot
- Always add meaningful summaries and descriptions
- Document error responses clearly
- Use examples for request and response bodies
- Disable or secure Swagger in production
- Keep API versions updated
Conclusion
Swagger (OpenAPI) is an essential tool for modern Spring Boot applications. It provides automatic, interactive, and standardized API documentation. By integrating Swagger, teams can improve development speed, reduce misunderstandings, and ensure better API usability.
For REST-based microservices, Swagger is not optional anymore — it is a best practice.