DEV Community

Shubham Bhati
Shubham Bhati

Posted on

API Documentation with OpenAPI 3 and Swagger in Spring Boot

Openapi Swagger Spring Boot

Published 2026-08-12 by Shubham Bhati — Backend Engineer (Java 17, Spring Boot, Microservices).

Documenting Your Spring Boot APIs with OpenAPI 3 and Swagger

By Shubham Bhati, Backend Engineer (Java 17, Spring Boot, Microservices)

Remember that feeling? You've got a new API to integrate, but the docs are outdated, incomplete or nonexistent. You're left guessing request payloads, status codes and error formats. It's a massive time sink for frontend, mobile and even other backend teams. This isn't just annoying; it slows development and introduces bugs. Stop the madness. For your next Spring Boot project, embrace proper API documentation using OpenAPI 3 and Swagger. It's easier than you think and dramatically improves developer experience across your entire organization.

Quick Setup with springdoc-openapi

Integrating OpenAPI 3 into your Spring Boot application is straightforward, thanks to the springdoc-openapi library. This library automatically generates API documentation from your Spring annotations, aligning perfectly with the OpenAPI Specification. It also provides a ready-to-use Swagger UI to visualize and interact with your APIs directly from your browser. Getting started means adding a single dependency to your project.

For Maven users, 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>
Enter fullscreen mode Exit fullscreen mode

For Gradle users, add this to your build.gradle:

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0' // Use the latest stable version
Enter fullscreen mode Exit fullscreen mode

That's it. Restart your Spring Boot application, and your Swagger UI will be accessible at http://localhost:8080/swagger-ui.html (or your configured port).
Production Note: While springdoc-openapi is lightweight, always be mindful of adding dependencies, especially in microservices. More dependencies mean larger Docker images, potentially longer build times and a slightly increased memory footprint. Keep your dependency graph lean and purpose-driven to maintain optimal performance and resource utilization.

Documenting Your Controllers with Annotations

The real power of OpenAPI lies in detailing your API endpoints. springdoc-openapi leverages Javadoc-like annotations to describe operations, parameters and responses directly within your controller code. The key annotations are @Operation for method-level summaries and descriptions, and @ApiResponse for detailing possible HTTP responses, including status codes and response bodies. Providing clear, concise descriptions helps consumers understand your API's intent and behavior without guessing.

Consider this example of a simple user API:

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.*;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/users")
public class UserController {

    @Operation(summary = "Create a new user profile",
               description = "Registers a new user in the system with unique ID.")
    @ApiResponse(responseCode = "201", description = "User created successfully")
    @ApiResponse(responseCode = "400", description = "Invalid user data provided",
                 content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
    @ApiResponse(responseCode = "409", description = "User with provided email already exists")
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        // Service logic to create user
        user.setId(UUID.randomUUID());
        return ResponseEntity.status(HttpStatus.CREATED).body(user);
    }
}

// Example DTOs for documentation
record User(UUID id, String name, String email) {}
record ErrorResponse(String timestamp, int status, String error, String message, String path) {}
Enter fullscreen mode Exit fullscreen mode

Production Note: Thoroughly documenting all possible response codes (200, 201, 400, 401, 403, 404, 500) and their respective error structures is critical. Unhandled or unexpected error responses are a common source of client-side bugs and support requests. Defining a consistent ErrorResponse schema and using it across your API significantly improves client resilience and reduces the "guesswork" for integrations. This clarity helps maintain a high p99 availability for your API by reducing unexpected client failures.

Customizing and Securing Your OpenAPI Docs

While defaults are good, you'll often want to customize your API documentation's global information and security definitions. You can configure general API details like title, description and version using a @Configuration class or application.yml. For securing your APIs, OpenAPI 3 supports various schemes like Basic Auth, Bearer Token (JWT) and OAuth2. You define these globally and then apply them to specific operations.

Here's how you might configure global info and add JWT security:

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import org.springframework.context.annotation.Configuration;

@Configuration
@OpenAPIDefinition(
    info = @Info(
        title = "User Management API",
        version = "1.0",
        description = "API for managing user profiles and authentication.",
        contact = @Contact(name = "Shubham Bhati", email = "shubham.bhati@example.com")
    ),
    security = @SecurityRequirement(name = "bearerAuth")
)
@SecurityScheme(
    name = "bearerAuth",
    type = SecuritySchemeType.HTTP,
    scheme = "bearer",
    bearerFormat = "JWT",
    description = "Provide a valid JWT token in the Authorization header."
)
public class OpenAPIConfig {
    // No bean definitions needed here, just annotations
}
Enter fullscreen mode Exit fullscreen mode

You can also customize the Swagger UI path or disable it in production via application.yml:

springdoc:
  swagger-ui:
    path: /swagger-ui-custom.html
    disable-swagger-default-url: true # Disables default /swagger-ui/index.html
  api-docs:
    path: /api-docs # Custom path for OpenAPI JSON
Enter fullscreen mode Exit fullscreen mode

Production Note: Consistent security documentation is vital for automated client SDK generation and successful integration with API gateways like Kong or Zuul. Ensure your security definitions precisely match your application's authentication mechanisms. Regularly reviewing and updating your OpenAPI documentation with every API change is crucial; outdated documentation is a source of confusion that can undermine trust in your API.

Common Pitfalls

  • Forgetting to update documentation: Code changes, but documentation doesn't. This leads to inaccurate docs, which can be worse than no docs. Treat documentation as part of your code review process.
  • Missing error responses: Only documenting 2xx success codes leaves API consumers in the dark about how to handle common problems like bad input or authentication failures.
  • Over-documenting trivial fields: Not every simple boolean or string needs an extensive description. Focus on complex business rules, edge cases and semantic meaning.
  • Inconsistent security definitions: If your API uses JWT but your docs describe Basic Auth, clients will struggle to connect. Ensure your @SecurityScheme accurately reflects your actual security implementation.

Conclusion

Well-documented APIs are a hallmark of mature, developer-friendly services. By adopting OpenAPI 3 and Swagger with springdoc-openapi in your Spring Boot projects, you not only clarify your API contracts but also foster better collaboration within your teams. Stop wasting time debugging undocumented interfaces and start building higher-quality APIs today. Your frontend, mobile and integration partners will thank you.


Openapi Swagger Spring Boot in production

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)