Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 119 ยท Spring Boot

OpenAPI and Swagger Docs

Document a Spring Boot REST API with OpenAPI 3 and springdoc. Learn the spec structure, annotations, Swagger UI, code-first versus contract-first, and spotting breaking changes.

A REST API is only as useful as its documentation. If a front-end developer, a partner company or your own mobile team has to read your controllers to learn which fields a request needs, you will be answering questions forever. The standard answer is OpenAPI: a machine-readable description of an HTTP API, written as JSON or YAML, listing every path, operation, parameter, request body, response and error. From that single file tools can render interactive documentation, generate client libraries, create mock servers and check that requests and responses match the contract.

In this lesson you will see what an OpenAPI document looks like (and build one in Java), how springdoc-openapi generates it from your Spring controllers, how to refine the output with annotations, and how to treat the document as a contract that catches breaking changes. It assumes you have written a controller as in REST Controllers and know the design guidelines from REST API Design.

OpenAPI, Swagger and springdoc: who is who

  • OpenAPI Specification (OAS) is the standard, maintained by the OpenAPI Initiative. Current documents declare openapi: 3.1.0 (3.0.x is still very common).
  • Swagger was the original name of the spec. Today it mostly names a family of tools: Swagger UI (the browser page where you read and try an API) and Swagger Editor. "Swagger 2.0" is the old format that predates OpenAPI 3.
  • springdoc-openapi is the library that inspects a running Spring application, reads its controllers and model classes, and publishes the OpenAPI document plus a bundled Swagger UI.

Anatomy of an OpenAPI document

An OpenAPI document has a few top-level sections.

Section Purpose
openapi Version of the specification
info Title, version, description, contact
servers Base URLs of the API
paths Every URL, with its HTTP operations
components Reusable schemas, parameters, responses and security schemes
security / tags Default security requirements and operation groups

Each operation lists parameters, an optional requestBody, and responses by status code. Schemas follow JSON Schema, and shared ones are referenced with $ref so a Product is defined once. Because a document is just JSON, you can build it with the Jackson tree model from Advanced Jackson. Seeing it assembled makes the structure concrete:

Java Building an OpenAPI document by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real documents are bigger, but they have exactly this shape. Nobody writes them by hand in a code-first project; springdoc does it for you.

Adding springdoc to Spring Boot

Add one dependency. The UI starter includes the generator and Swagger UI:

XML
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>${springdoc.version}</version>
</dependency>

springdoc 2.x targets Spring Boot 3 and springdoc 3.x targets Spring Boot 4; check the compatibility table in its documentation for the exact version. (Use the webflux variant for reactive applications and starter-webmvc-api if you do not want the UI.) Start the application and two URLs appear with no configuration:

  • /v3/api-docs returns the OpenAPI document as JSON (/v3/api-docs.yaml for YAML).
  • /swagger-ui.html redirects to the interactive Swagger UI, where every operation can be expanded and executed with a Try it out button.

springdoc discovers @RestController classes, their mappings, parameters (@PathVariable, @RequestParam, @RequestBody), return types, and constraints from Bean Validation annotations (@NotNull becomes required, @Size(max = 40) becomes maxLength: 40). Your validation work from Validation and Error Handling therefore documents itself.

flowchart LR
    A["Controllers and records"] --> B["springdoc scans at startup"]
    B --> C["/v3/api-docs<br/>OpenAPI JSON"]
    C --> D["Swagger UI"]
    C --> E["Client code generators"]
    C --> F["Contract tests"]

One generated document feeds documentation, client generation and checks.

Common properties go in application.properties:

PROPERTIES
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/docs
springdoc.swagger-ui.operations-sorter=method
springdoc.paths-to-match=/api/**

Describing your API with annotations

The generated text is accurate about structure but silent about meaning. Add the intent with annotations from io.swagger.v3.oas.annotations:

Java
@OpenAPIDefinition(info = @Info(title = "Shop API", version = "1.0", description = "Products and orders"))
@Configuration
class OpenApiConfig { }

@RestController
@RequestMapping("/api/products")
@Tag(name = "products", description = "Browse and manage the catalog")
class ProductController {

    @Operation(summary = "Get one product", description = "Returns the product, or 404 if it does not exist.")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "The product"),
        @ApiResponse(responseCode = "404", description = "No product with this id",
                     content = @Content(schema = @Schema(implementation = ProblemDetail.class)))
    })
    @GetMapping("/{id}")
    Product get(@Parameter(description = "Product id", example = "42") @PathVariable long id) { ... }
}

@Schema(description = "A product in the catalog")
record Product(
        @Schema(example = "42") long id,
        @Schema(example = "Trail tent", maxLength = 80) String name,
        @Schema(description = "Price in euros", example = "189.00") BigDecimal price) { }

The most valuable annotations are @Operation (a one-line summary that shows in the UI), @ApiResponse for error statuses that your @ControllerAdvice produces (springdoc cannot guess those), and @Schema(example = ...), because examples are what people copy first. You can also split a large API into groups with GroupedOpenApi beans, for example public, admin and v2, each with its own document and UI entry.

Do not annotate everything. Let the types and validation constraints speak, and add annotations where a human needs the reason, an example or an error case. Over-annotated controllers become unreadable and the text drifts out of date.

Security and visibility

Declare how clients authenticate so the UI gets an Authorize button, for instance a bearer token as in JWT Authentication:

Java
@SecurityScheme(name = "bearerAuth", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT")
@OpenAPIDefinition(security = @SecurityRequirement(name = "bearerAuth"))
class OpenApiConfig { }

Remember that your own Spring Security rules apply to /v3/api-docs and /swagger-ui/** too. Many teams allow them in development and staging, but disable them in production (springdoc.api-docs.enabled=false, springdoc.swagger-ui.enabled=false) or put them behind authentication, because a full map of the API helps attackers as well. Hide individual endpoints with @Hidden.

Code-first or contract-first

There are two ways to work, and both are legitimate:

  • Code-first: write the controllers, let springdoc generate the document. Quick, always matches the implementation, and best for internal APIs and small teams. The risk is that the contract changes accidentally when someone renames a field.
  • Contract-first: write the OpenAPI file first, review it with the consumers, then generate server interfaces and client SDKs from it (with the OpenAPI Generator Maven plugin, for example). Best when several teams or external customers depend on the API, because the contract is agreed and versioned before any code exists.

Either way, the document is the contract, and the most useful thing you can do with a contract is to protect it.

Treating the spec as a contract

Consumers rely on what the API returns. Removing a response field, renaming it or changing its type breaks them; adding a new optional field normally does not. Teams therefore commit the generated document (or fetch it in CI), compare it with the previous release, and fail the build on breaking differences. Dedicated tools such as oasdiff do this for whole documents. The model below reduces the idea to its core: it derives a flat schema from two versions of a Java record by reflection (a miniature of what springdoc does) and classifies the differences.

Java Detecting breaking changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same reasoning applies in the other direction for request bodies: adding a new required field breaks existing clients, while adding an optional one does not. When a breaking change is unavoidable, release a new version (/api/v2/...), keep the old one running for a deprecation period, and mark it with @Operation(deprecated = true) so the UI shows it struck through.

Two more uses of the document are worth knowing. Client generation: tools such as OpenAPI Generator produce typed clients in Java, TypeScript, Kotlin or Swift from /v3/api-docs, so consumers never hand-write HTTP calls. Contract testing: in a @SpringBootTest you can fetch /v3/api-docs and compare it with a checked-in snapshot, so any unintended change to the public surface shows up in code review. See Testing Spring Boot Applications for the test setup.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which URL does springdoc serve the machine-readable OpenAPI document on by default?

    /v3/api-docs returns the JSON document (add .yaml for YAML). /swagger-ui.html is the interactive UI that reads it.
  2. 2. What is the relationship between OpenAPI and Swagger UI?

    OpenAPI is the standard format. Swagger UI is one of many tools that read it, giving you browsable documentation with a Try it out button.
  3. 3. Your controller advice returns a 409 Conflict for duplicate names. Why is it worth adding an @ApiResponse for it?

    Statuses produced by exception handlers are not visible in the method signature, so springdoc cannot infer them. Documenting them tells clients what errors to expect.
  4. 4. Which change to a response body is normally backward compatible?

    Clients that ignore unknown fields keep working. Renames, removals and type changes break existing consumers.

Summary

  • OpenAPI is the standard, machine-readable description of an HTTP API (paths, operations, schemas, responses); Swagger UI renders it; springdoc-openapi generates it from your Spring controllers.
  • Add the springdoc starter and you get /v3/api-docs and /swagger-ui.html with no configuration; Bean Validation constraints become schema constraints.
  • Use @Operation, @ApiResponse, @Schema(example = ...), @Tag and @SecurityScheme where a human needs context; do not annotate everything.
  • Restrict or disable the docs endpoints in production, and hide internal operations with @Hidden.
  • Code-first is fast; contract-first suits many consumers. In both cases treat the document as a contract: diff it in CI and fail on removed fields, renamed fields and changed types.
  • Generate client SDKs from the spec and release breaking changes as a new API version.

Next: Layered Architecture.