Published 2026-08-15 by Shubham Bhati — Backend Engineer (Java 17, Spring Boot, Microservices).
Clear Your API Chaos with OpenAPI 3 and Swagger in Spring Boot
Remember that sinking feeling when a new developer joins your team, and the first question is, "Where's the API documentation?" Or worse, you push a breaking change, and consumers find out through production errors. Undocumented APIs are a major bottleneck, slowing down development, fostering miscommunication, and making onboarding a nightmare. This is where openapi swagger spring boot becomes your best friend. It transforms your API into a self-documenting asset, providing clarity and efficiency. Let's get your Spring Boot applications talking clearly.
Getting Started: Springdoc-OpenAPI Setup
To integrate OpenAPI 3 and Swagger UI into your Spring Boot application, the springdoc-openapi-starter-webmvc-ui dependency is all you need. This library automatically scans your Spring components and generates an OpenAPI specification, which Swagger UI then renders beautifully.
Add this to your pom.xml:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- Use the latest stable version -->
</dependency>
With just this dependency, your application will expose the OpenAPI JSON at /v3/api-docs and the Swagger UI at /swagger-ui.html. For production, consider using a specific version of springdoc that aligns with your Spring Boot version to avoid unexpected build failures or runtime issues. This small setup cost pays dividends by making your API contract visible and machine-readable, saving countless hours explaining endpoints and data models. It also helps with API gateways and client generation tools which can consume the spec directly.
Documenting Controllers and Models
While springdoc does a great job generating a basic spec, you'll want to add richer details. OpenAPI annotations empower you to describe endpoints, parameters, responses and data schemas clearly.
Here’s an example using common annotations:
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Operation(summary = "Get a product by its ID", description = "Retrieves details of a single product based on the provided product ID.")
@ApiResponse(responseCode = "200", description = "Product found successfully",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = Product.class)))
@ApiResponse(responseCode = "404", description = "Product not found")
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
// ... implementation
return new Product(id, "Example Product", 29.99);
}
}
class Product { // Example DTO
public Long id;
public String name;
public double price;
public Product(Long id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
}
This code uses @Operation for a high-level summary and description. @ApiResponse defines expected HTTP status codes and the associated response bodies. For models, springdoc automatically picks up your DTOs, but @Schema can be used to add descriptions or examples to fields if needed. In production, ensure these descriptions are kept up-to-date with code changes. Clear documentation of all possible responses, especially error codes, is critical for consumers to handle API interactions gracefully without encountering unexpected behavior.
Customizing Swagger UI and Security
Swagger UI is powerful, but you'll often want to customize its behavior or add security definitions. You can configure springdoc properties in your application.yaml or application.properties.
For example, to change the Swagger UI path and add a JWT security scheme:
springdoc:
swagger-ui:
path: /api/docs
groups-on-top: true # Organizes API groups at the top
try-it-out-enabled: true # Enable the "Try it out" feature
api-docs:
path: /api/v3/api-docs
info:
title: My Service API
version: 1.0.0
description: "API documentation for My Spring Boot Service"
components:
security-schemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
This YAML snippet reconfigures the documentation endpoints and adds a bearerAuth security scheme. After this, you can apply @SecurityRequirement(name = "bearerAuth") to your controllers or methods. For production, always restrict access to /api/docs and /swagger-ui.html paths. You can achieve this using Spring Security by protecting these endpoints, ensuring only authorized personnel can view or interact with your API documentation. This prevents unauthorized users from easily discovering your API's attack surface.
Common Pitfalls
- Not updating documentation: Stale documentation is worse than no documentation. Always update
@Operationand@ApiResponsewhen changing endpoints or models. - Exposing Swagger UI in production: Leaving Swagger UI unprotected in production is a major security risk. Restrict access using Spring Security or disable it completely for production profiles.
- Over-documenting: Don't annotate every single getter/setter or obvious field. Focus on clarity for complex logic, business rules, and error conditions.
- Ignoring error responses: Clearly define
4xxand5xxresponses using@ApiResponse. Consumers need to know how to handle errors gracefully.
Conclusion
OpenAPI 3 and Swagger UI with springdoc-openapi offer an indispensable solution for API documentation in Spring Boot. By investing a little effort upfront, you create a living, breathing contract for your APIs, reducing friction for developers, speeding up integration, and improving overall project clarity. Make documentation a core part of your development workflow, not an afterthought. Your team and future API consumers will thank you.
Further Reading
Written by **Shubham Bhati* — Backend Engineer at AlignBits LLC, specializing in Java 17, Spring Boot, microservices, and AI integration. Connect on LinkedIn, GitHub, or read more at shubh2-0.github.io.*
Top comments (0)