Spring Boot & Spring Cloud

API Documentation with springdoc-openapi: OpenAPI 3 and Swagger UI for Spring Boot

Intermediate6 min readUpdated

You will be able to publish an OpenAPI 3 description and Swagger UI for a Spring Boot 3 service with springdoc-openapi, enrich it with operation, schema and security annotations where inference falls short, split it into groups, export it at build time for client generation, and keep it from lying about your API.

What you will learn

  • Explain what the OpenAPI Specification describes and how springdoc-openapi derives it from Spring MVC at runtime
  • Add springdoc-openapi to a Spring Boot 3 project and configure the api-docs and Swagger UI paths
  • Document operations, responses, schemas and parameters with the swagger-core annotations
  • Describe authentication with security schemes and document error responses consistently
  • Export the description at build time and generate typed clients from it

An API without a description is an API that clients learn by trial and error. The OpenAPI Specification gives you a machine-readable contract that tools turn into interactive documentation, typed client libraries, contract tests and gateway configuration. springdoc-openapi produces that contract from a Spring Boot application at runtime by inspecting controllers, so the description follows the code instead of drifting away from it. This page shows how to set it up on Spring Boot 3, where inference stops and annotations begin, how to describe security and errors, and how to make the generated file part of your build rather than a runtime curiosity.

What OpenAPI describes

An OpenAPI document (JSON or YAML) lists an API's paths, the operations on each path, their parameters, request bodies and responses, the schemas of those bodies, the security schemes the API accepts, and metadata such as title, version, contact and servers. Version 3.0 was released in 2017 and is what most tooling expects; 3.1 aligned the schema object with JSON Schema 2020-12. springdoc 2.x emits 3.0 by default and 3.1 when springdoc.api-docs.version=openapi_3_1 is set.

"Swagger" survives as the name of the tooling around the specification: Swagger UI renders a document as a browsable console, and the swagger-core annotations (io.swagger.v3.oas.annotations) are how you add information Java signatures do not carry. springdoc-openapi is the bridge between Spring's view of your controllers and those artifacts; it is a community project, not part of the Spring portfolio, and it is the de facto choice since Springfox stopped keeping up.

Setup on Spring Boot 3

One dependency for Spring MVC applications:

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

Use springdoc-openapi-starter-webflux-ui for WebFlux, and the -api variants (springdoc-openapi-starter-webmvc-api) when you want the description without Swagger UI. The 2.x line is the one for Spring Boot 3; 1.x targeted Boot 2 and javax packages.

Start the application and you have:

  • /v3/api-docs — the description in JSON, /v3/api-docs.yaml in YAML
  • /swagger-ui/index.html — Swagger UI reading that description

Common configuration lives under springdoc.*:

springdoc:
  api-docs:
    path: /openapi            # default /v3/api-docs
  swagger-ui:
    path: /docs               # default /swagger-ui.html
    operations-sorter: method
    tags-sorter: alpha
    try-it-out-enabled: false
  paths-to-match: /api/**     # ignore health checks, error pages, etc.
  show-actuator: false
  default-produces-media-type: application/json

paths-to-match and packages-to-scan restrict what appears; without them, every handler mapping in the context is documented, including Boot's /error. With Spring Security, permit /v3/api-docs/** and /swagger-ui/** (or your custom paths) explicitly, otherwise the UI loads but the description request is redirected to a login page.

What is inferred and what is not

springdoc walks the RequestMappingHandlerMapping and derives most of the document without any annotation:

Inferred fromAppears as
@RequestMapping paths and HTTP methodsPaths and operations
@PathVariable, @RequestParam, @RequestHeaderParameters, with required from the annotation
@RequestBody typeRequest body schema
Return type or ResponseEntity<T>Response schema for the default status
@ResponseStatusResponse status code
Jakarta Bean Validation constraints (@NotNull, @Size, @Min, @Pattern, @Email…)Schema required, minLength, minimum, pattern, format
Jackson annotations (@JsonProperty, @JsonIgnore)Property names and omissions
Records, enums, java.time, Optional, Page<T>Schemas; Pageable becomes page/size/sort query parameters
@RestControllerAdvice methods with @ResponseStatusAdditional responses on every operation

What it cannot know: human-readable summaries and descriptions, which error statuses a specific operation returns, examples, deprecation, which parameters are mutually exclusive, and how to authenticate. That is the job of annotations.

Enriching with annotations

The annotations come with the starter. The useful set is small:

@RestController
@RequestMapping("/api/orders")
@Tag(name = "Orders", description = "Create and track customer orders")
class OrderController {

    @Operation(
        summary = "Get an order by id",
        description = "Returns the order with its lines and current status. Cancelled orders are still returned."
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "The order"),
        @ApiResponse(responseCode = "404", description = "No order with that id",
                     content = @Content(mediaType = "application/problem+json",
                                        schema = @Schema(implementation = ProblemDetail.class)))
    })
    @GetMapping("/{id}")
    OrderResponse get(
            @Parameter(description = "Order identifier", example = "10042")
            @PathVariable long id) {
        return OrderResponse.from(orders.get(id));
    }

    @Operation(summary = "Place an order")
    @ApiResponse(responseCode = "201", description = "Order created",
                 headers = @Header(name = "Location", description = "URL of the new order"))
    @PostMapping
    ResponseEntity<OrderResponse> create(@Valid @RequestBody CreateOrderRequest request) { /* ... */ }
}

Schema-level detail goes on the DTOs:

@Schema(description = "A request to place an order")
public record CreateOrderRequest(
        @Schema(description = "Identifier of an existing customer", example = "42")
        @NotNull Long customerId,

        @ArraySchema(arraySchema = @Schema(description = "At least one line"))
        @NotEmpty List<@Valid OrderLine> lines) {

    public record OrderLine(
            @Schema(example = "ABC-12345", pattern = "[A-Z]{3}-\\d{5}") @Sku String sku,
            @Schema(minimum = "1", maximum = "999") @Min(1) @Max(999) int quantity) {}
}

Notice the division of labour: the validation constraints already produce required, minimum and maximum, so @Schema adds description and examples rather than repeating rules. @Hidden removes an operation, parameter or property; @Parameter(hidden = true) hides a single parameter such as an injected Principal; deprecated = true on @Operation marks an endpoint for retirement.

Since the document is generated from live beans, mistakes show up immediately in Swagger UI. Run the application locally after adding annotations and read the result as a consumer would; an @ApiResponse claiming 404 on an operation whose handler never throws is worse than no annotation at all.

Application-level metadata

Title, version, contact and servers come from an OpenAPI bean or from properties:

@Bean
OpenAPI shopApi(BuildProperties build) {
    return new OpenAPI()
            .info(new Info()
                    .title("Shop API")
                    .version(build.getVersion())          // from build-info, not a hard-coded string
                    .description("Orders, customers and catalogue for the shop front end")
                    .license(new License().name("Proprietary")))
            .servers(List.of(new Server().url("https://api.example.com")));
}

Taking the version from BuildProperties (generated by the Boot Maven or Gradle plugin) means the description version moves with every release without anyone remembering to edit a string.

Security schemes

An API behind OAuth 2.0 or a bearer token needs to say so, otherwise Swagger UI's "Try it out" fails with 401 and generated clients have no way to attach credentials. Declare the scheme once and reference it:

@Configuration
@SecurityScheme(
    name = "bearer-jwt",
    type = SecuritySchemeType.HTTP,
    scheme = "bearer",
    bearerFormat = "JWT",
    description = "Access token issued by the identity provider"
)
@OpenAPIDefinition(security = @SecurityRequirement(name = "bearer-jwt"))   // applies to every operation
class OpenApiSecurityConfig {}

For OAuth 2.0 flows, type = SecuritySchemeType.OAUTH2 with flows = @OAuthFlows(authorizationCode = @OAuthFlow(authorizationUrl = ..., tokenUrl = ..., scopes = ...)) lets Swagger UI run the authorisation-code flow against your identity provider; springdoc.swagger-ui.oauth.client-id supplies the client. Public operations opt out with @SecurityRequirements (the plural, empty) on the method. springdoc's Spring Security integration, bundled in the starter and active whenever Spring Security is on the classpath, hides @AuthenticationPrincipal parameters so they do not show up as request parameters.

Documenting errors once

If your API returns RFC 9457 problem details (see the error handling guide), you do not want to repeat the 400 and 500 responses on every operation. An OperationCustomizer bean adds them globally:

@Bean
OperationCustomizer commonErrorResponses() {
    return (operation, handlerMethod) -> {
        ApiResponses responses = operation.getResponses();
        responses.addApiResponse("400", problemResponse("Validation failed or malformed request"));
        responses.addApiResponse("500", problemResponse("Unexpected server error"));
        return operation;
    };
}

private static io.swagger.v3.oas.models.responses.ApiResponse problemResponse(String description) {
    return new io.swagger.v3.oas.models.responses.ApiResponse()
            .description(description)
            .content(new Content().addMediaType("application/problem+json",
                    new MediaType().schema(new Schema<>().$ref("#/components/schemas/ProblemDetail"))));
}

Customizers exist at several levels (OpenApiCustomizer for the whole document, OperationCustomizer, ParameterCustomizer, PropertyCustomizer) and are the right tool for anything cross-cutting; annotations are for the specifics of one operation.

Groups and large APIs

One document for a service with a public API, an internal admin API and a partner API is hard to read and leaks internal endpoints to external consumers. GroupedOpenApi splits it, each group served at /v3/api-docs/{group} and selectable in Swagger UI:

@Bean
GroupedOpenApi publicApi() {
    return GroupedOpenApi.builder().group("public").pathsToMatch("/api/public/**").build();
}

@Bean
GroupedOpenApi adminApi() {
    return GroupedOpenApi.builder().group("admin").pathsToMatch("/api/admin/**")
            .addOperationCustomizer((op, method) -> op.addTagsItem("admin")).build();
}

The same can be expressed with springdoc.group-configs[0].group properties. In a microservice landscape, a gateway can aggregate each service's /v3/api-docs into one Swagger UI through springdoc.swagger-ui.urls, so consumers get one entry point without the services knowing about each other.

Making the description a build artifact

A description that only exists on a running server is hard to diff, review or feed to code generators. The springdoc-openapi-maven-plugin starts the application during the integration-test phase, downloads /v3/api-docs, and writes openapi.json (or YAML) into the build directory; the Gradle plugin does the same with a generateOpenApiDocs task. Commit the output, and a pull request that changes the API shows the change in the contract alongside the code.

That file feeds OpenAPI Generator (openapi-generator-maven-plugin) to produce typed clients in TypeScript, Java, Kotlin, Python and others, and can be published to an API portal or gateway. It is also the input for contract tests and for breaking-change detection tools that compare two versions of a description.

Common mistakes

Documenting the error path with @ResponseStatus on exception classes. springdoc reads @ResponseStatus on @ExceptionHandler methods in advice classes and adds those responses to every operation, whether or not the operation can raise them. Use targeted @ApiResponse annotations or a customizer instead.

Leaving the default paths-to-match. Actuator, /error and any servlet you forgot appear in the public document.

Exposing Swagger UI on a production API without authentication. The UI itself is harmless; the "Try it out" button wired to production credentials is not. Protect it or disable it there.

Trusting inferred schemas for polymorphic types. A List<Payment> where Payment is an interface produces an empty schema. Use @Schema(oneOf = {...}) with a discriminator, or Jackson's @JsonTypeInfo and @JsonSubTypes, which springdoc understands.

Pinning an old springdoc version. Each Spring Boot minor release tends to need a matching springdoc release; the project's site lists the compatibility table. A mismatch shows up as an empty document or a startup failure in SpringDocConfiguration.

Describing an API that never existed. Annotations that promise fields, statuses or parameters the code does not implement are the fastest way to lose consumers' trust in the documentation. Review Swagger UI against real responses after every change.

Key takeaways

  • OpenAPI is the standard machine-readable API contract; springdoc-openapi generates it from Spring MVC or WebFlux controllers at runtime and serves Swagger UI on top.
  • Spring Boot 3 needs springdoc 2.x (springdoc-openapi-starter-webmvc-ui); Springfox is not an option.
  • Inference covers paths, parameters, bodies, validation constraints and Jackson annotations; @Operation, @ApiResponse, @Schema and @Parameter add the human context tools cannot infer.
  • Declare security schemes once with @SecurityScheme and apply them globally so the UI and generated clients can authenticate.
  • Use customizers for cross-cutting content such as problem-detail error responses, and GroupedOpenApi to publish separate documents for different audiences.
  • Export the description at build time, commit it, and generate clients from it so the contract is reviewed like code.

Sources and further reading

Frequently asked questions

Is springdoc-openapi the same as Springfox?
No. Springfox was the older library that generated Swagger 2 descriptions and has not had a release compatible with Spring Boot 3. springdoc-openapi is a separate community project built for OpenAPI 3; version 2.x targets Spring Boot 3 and uses the io.swagger.v3 annotations. Migrating means swapping the dependency and renaming annotations such as @ApiOperation to @Operation and @ApiModelProperty to @Schema.
Where is Swagger UI served in Spring Boot 3 with springdoc?
At /swagger-ui/index.html by default; /swagger-ui.html redirects there. The raw description is at /v3/api-docs in JSON and /v3/api-docs.yaml in YAML. Both paths are configurable with springdoc.swagger-ui.path and springdoc.api-docs.path, and both must be permitted in your Spring Security configuration if the rest of the API is protected.
Should the description be generated from code or written first?
Code-first, which is what springdoc does, keeps the description honest because it is derived from what actually runs, and it suits teams that own both ends. Contract-first, where the OpenAPI file is written by hand and interfaces are generated from it, gives consumers a stable contract earlier and works better across teams. Many projects do code-first and pin the exported file in version control to review changes.
Can I turn springdoc off in production?
Yes: springdoc.api-docs.enabled=false and springdoc.swagger-ui.enabled=false remove both endpoints, and you can bind them to a profile. Many teams keep the description available behind authentication because it is useful to consumers, but hide Swagger UI, since an interactive console pointed at production is a convenient way to make mistakes.