OpenAPI for Spring Boot: what springdoc reads and how to shape it

springdoc-openapi generates an OpenAPI document and Swagger UI from your Spring MVC controllers, using what Spring already knows about each endpoint. This page runs the two halves of that process, endpoint discovery and constraints turned into JSON Schema, then runs springdoc 3.2 on Spring Boot 4.1 and prints the real /v3/api-docs output, with annotations, security schemes and groups.

Contents

What OpenAPI is and how springdoc builds the document

OpenAPI is a standard format, in JSON or YAML, for describing an HTTP API: its paths, the operations on each path, the parameters, the request and response bodies, the status codes and the security schemes. The current version of the specification is 3.1. From one OpenAPI document, tools can render interactive documentation such as Swagger UI, generate client libraries in many languages, mock the API, and check in CI that a change has not broken clients.

There are two ways to get the document. In the contract-first approach you write the YAML by hand, review it with client teams, and generate server interfaces from it. In the code-first approach you write the controllers and let a library generate the document from them. For Spring Boot, the code-first library is springdoc-openapi. It is a community project, not part of Spring itself.

springdoc works by reading what Spring MVC already knows about your application. At startup, Spring MVC builds a table of every handler method with its path, HTTP methods and content types. springdoc walks that table, and for each method it inspects the parameters and their annotations, the return type, and the Bean Validation constraints on the classes involved. It turns Java types into JSON Schema, adds whatever you declared with OpenAPI annotations, and serves the result.

springdoc-openapi versions and Spring Boot
springdoc lineSpring BootNotes
3.x4.0 and 4.13.0.x for Boot 4.0; 3.1.x and 3.2.x for Boot 4.1
2.x3.xThe last line for Spring Boot 3
1.x2.xArtifacts named springdoc-openapi-ui, without "starter"

The table comes from the compatibility matrix on springdoc.org; the latest release at the time of writing is 3.2.0. All programs on this page run with Spring Boot 4.1, Spring Framework 7.0, Hibernate Validator and springdoc 3.2.0, which brings swagger-core 2.2.55 and Swagger UI 5.34.0. The first two programs show the information springdoc reads; the later ones start an application and print the document springdoc serves. Because springdoc is on the classpath of every program, the first one runs with -Dlogging.level.org.springdoc=ERROR, which hides two startup warnings that the third program explains.

What a generator can learn from a controller

Before adding any annotation, it is worth seeing how much is already known. This program starts an application with a small product controller, then reads Spring MVC's RequestMappingHandlerMapping, the same table springdoc reads, and prints each operation the way a generator has to understand it:

Java
package demo.inventory;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import java.lang.reflect.Parameter;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.core.MethodParameter;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@SpringBootApplication
public class EndpointInventory {

    public record Product(long id, String name, int stock) {}

    public record NewProduct(@NotBlank String name, @Min(0) int stock) {}

    @RestController
    @RequestMapping("/api/products")
    static class ProductController {
        @GetMapping
        public List<Product> list(@RequestParam(defaultValue = "0") int page,
                                  @RequestParam(required = false) String name) {
            return List.of();
        }

        @GetMapping("/{id}")
        public Product get(@PathVariable long id) {
            return new Product(id, "lamp", 3);
        }

        @PostMapping(consumes = "application/json", produces = "application/json")
        public ResponseEntity<Product> create(@Valid @RequestBody NewProduct body,
                                              @RequestHeader("X-Request-Id") String requestId) {
            return ResponseEntity.ok(new Product(1, body.name(), body.stock()));
        }

        @DeleteMapping("/{id}")
        public void delete(@PathVariable long id) {
        }
    }

    // Describes one parameter the way a documentation generator has to
    static String describe(MethodParameter p) {
        Parameter param = p.getParameter();
        String type = p.getParameterType().getSimpleName();
        if (p.hasParameterAnnotation(PathVariable.class)) {
            return "path   " + param.getName() + ": " + type + " (required)";
        }
        if (p.hasParameterAnnotation(RequestBody.class)) {
            return "body   " + type + (p.hasParameterAnnotation(Valid.class) ? " (validated)" : "");
        }
        if (p.hasParameterAnnotation(RequestHeader.class)) {
            RequestHeader h = p.getParameterAnnotation(RequestHeader.class);
            return "header " + h.value() + ": " + type + (h.required() ? " (required)" : "");
        }
        RequestParam q = p.getParameterAnnotation(RequestParam.class);
        if (q != null) {
            boolean required = q.required() && ValueConstants.DEFAULT_NONE.equals(q.defaultValue());
            return "query  " + param.getName() + ": " + type
                    + (required ? " (required)" : " (optional)");
        }
        return "other  " + type;
    }

    // java.util.List<demo.inventory.EndpointInventory$Product> becomes List<Product>
    static String shortTypeName(HandlerMethod method) {
        String full = method.getMethod().getGenericReturnType().getTypeName();
        return full.replaceAll("[\\w.]+\\.", "").replaceAll("\\w+\\$", "");
    }

    public static void main(String[] args) {
        try (var context = new SpringApplicationBuilder(EndpointInventory.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            RequestMappingHandlerMapping mapping = context.getBean(
                    "requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
            Map<RequestMappingInfo, HandlerMethod> methods = mapping.getHandlerMethods();

            methods.entrySet().stream()
                    .filter(e -> e.getValue().getBeanType() == ProductController.class)
                    .sorted(Comparator.comparing((Map.Entry<RequestMappingInfo, HandlerMethod> e)
                            -> e.getKey().getPatternValues().toString())
                            .thenComparing(e -> e.getKey().getMethodsCondition().toString()))
                    .forEach(e -> {
                        RequestMappingInfo info = e.getKey();
                        HandlerMethod method = e.getValue();
                        System.out.println(info.getMethodsCondition().getMethods() + " "
                                + info.getPatternValues() + "  -> "
                                + shortTypeName(method));
                        if (!info.getConsumesCondition().isEmpty()) {
                            System.out.println("    consumes " + info.getConsumesCondition());
                        }
                        for (MethodParameter p : method.getMethodParameters()) {
                            System.out.println("    " + describe(p));
                        }
                    });
        }
    }
}
Output
[DELETE] [/api/products/{id}]  -> void
    path   id: long (required)
[GET] [/api/products/{id}]  -> Product
    path   id: long (required)
[GET] [/api/products]  -> List<Product>
    query  page: int (optional)
    query  name: String (optional)
[POST] [/api/products]  -> ResponseEntity<Product>
    consumes [application/json]
    body   NewProduct (validated)
    header X-Request-Id: String (required)
  • Each entry pairs a RequestMappingInfo, with the HTTP method and path pattern, and a HandlerMethod, with the Java method. Four mappings produced four OpenAPI operations: DELETE and GET on /api/products/{id}, and GET and POST on /api/products.
  • Path variables are always required. page is optional because it has a default value, and name because of required = false. springdoc applies the same rules when it sets required on each parameter.
  • The return types tell the generator the response schema: List<Product> becomes an array of Product, and ResponseEntity<Product> is unwrapped to Product. A method returning void has no body to describe.
  • The POST mapping declares consumes, and its body parameter is validated, so the generator can document the content type and look for constraints on NewProduct.
  • Parameter names such as page and id come from the class file, which works because the code was compiled with -parameters, as the Spring Boot build plugins do. Without it, a generator sees only arg0.

What the table cannot provide is meaning: a summary of what each operation does, which error statuses it returns, and examples. Those come from OpenAPI annotations or from Javadoc, as shown below. A generator also follows the request and response types into their fields, which the next program does for a request body.

From Bean Validation constraints to JSON Schema

A schema is only useful to client developers if it states the rules a server will enforce. Bean Validation constraints already state them, and springdoc translates the common ones into JSON Schema keywords. This program does the same translation for a sign-up record, using the validator's own metadata API, so that the mapping from each annotation to each keyword is visible:

Java
package demo.schema;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import jakarta.validation.metadata.ConstraintDescriptor;
import jakarta.validation.metadata.PropertyDescriptor;
import java.lang.reflect.RecordComponent;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.LoggerFactory;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;

// Builds the JSON Schema that an OpenAPI generator derives from a request record
public class SchemaFromConstraints {

    public record NewCustomer(
            @NotBlank @Size(max = 40) String name,
            @NotNull @Email String email,
            @Min(18) @Max(120) int age,
            @Pattern(regexp = "[A-Z]{2}") String country,
            BigDecimal creditLimit,
            LocalDate birthday,
            @Size(max = 5) List<String> tags) {}

    static Map<String, Object> typeOf(Class<?> type) {
        Map<String, Object> schema = new LinkedHashMap<>();
        if (type == String.class) {
            schema.put("type", "string");
        } else if (type == int.class || type == Integer.class) {
            schema.put("type", "integer");
            schema.put("format", "int32");
        } else if (type == BigDecimal.class) {
            schema.put("type", "number");
        } else if (type == LocalDate.class) {
            schema.put("type", "string");
            schema.put("format", "date");
        } else if (List.class.isAssignableFrom(type)) {
            schema.put("type", "array");
        } else {
            schema.put("type", "object");
        }
        return schema;
    }

    public static void main(String[] args) {
        // Without Spring Boot, Logback logs at DEBUG; keep Hibernate Validator quiet
        ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("ROOT").setLevel(Level.WARN);
        Map<String, Object> properties = new LinkedHashMap<>();
        List<String> required = new ArrayList<>();

        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            Validator validator = factory.getValidator();
            for (RecordComponent component : NewCustomer.class.getRecordComponents()) {
                String name = component.getName();
                Map<String, Object> schema = typeOf(component.getType());
                if (component.getType().isPrimitive()) {
                    required.add(name);               // a primitive can never be absent
                }
                PropertyDescriptor property = validator.getConstraintsForClass(NewCustomer.class)
                        .getConstraintsForProperty(name);
                if (property != null) {
                    List<ConstraintDescriptor<?>> constraints = new ArrayList<>(
                            property.getConstraintDescriptors());   // a Set: sort for output
                    constraints.sort(Comparator.comparing(
                            c -> c.getAnnotation().annotationType().getSimpleName()));
                    for (ConstraintDescriptor<?> c : constraints) {
                        Map<String, Object> a = c.getAttributes();
                        switch (c.getAnnotation()) {
                            case NotBlank n -> {
                                required.add(name);
                                schema.put("minLength", 1);
                            }
                            case NotNull n -> required.add(name);
                            case Email e -> schema.put("format", "email");
                            case Min m -> schema.put("minimum", a.get("value"));
                            case Max m -> schema.put("maximum", a.get("value"));
                            case Pattern p -> schema.put("pattern", a.get("regexp"));
                            case Size s -> schema.put(component.getType() == String.class
                                    ? "maxLength" : "maxItems", a.get("max"));
                            default -> { }
                        }
                    }
                }
                properties.put(name, schema);
            }
        }

        Map<String, Object> schema = new LinkedHashMap<>();
        schema.put("type", "object");
        schema.put("required", required.stream().distinct().toList());
        schema.put("properties", properties);
        JsonMapper json = JsonMapper.builder().enable(SerializationFeature.INDENT_OUTPUT).build();
        System.out.println(json.writeValueAsString(Map.of("NewCustomer", schema)));
    }
}
Output
{
  "NewCustomer" : {
    "type" : "object",
    "required" : [ "name", "email", "age" ],
    "properties" : {
      "name" : {
        "type" : "string",
        "minLength" : 1,
        "maxLength" : 40
      },
      "email" : {
        "type" : "string",
        "format" : "email"
      },
      "age" : {
        "type" : "integer",
        "format" : "int32",
        "maximum" : 120,
        "minimum" : 18
      },
      "country" : {
        "type" : "string",
        "pattern" : "[A-Z]{2}"
      },
      "creditLimit" : {
        "type" : "number"
      },
      "birthday" : {
        "type" : "string",
        "format" : "date"
      },
      "tags" : {
        "type" : "array",
        "maxItems" : 5
      }
    }
  }
}
  • @NotBlank on name became two things: an entry in required and minLength: 1. @Size(max = 40) added maxLength: 40.
  • @NotNull @Email on email made it required with format: email. Format values are hints to tools; JSON Schema validators do not have to check them.
  • age is an int, so it is required even without an annotation, and @Min(18) @Max(120) became minimum and maximum. In Spring Boot 4, Jackson 3 rejects a missing primitive, as shown in Spring Boot @RestController, so required is the honest description.
  • @Pattern carried its regular expression over unchanged. Java and JSON Schema regular expressions differ in some details, so keep patterns simple if clients will validate with them.
  • BigDecimal became number, LocalDate became string with format: date, and the List with @Size(max = 5) became an array with maxItems: 5.

This is a simplified version of what springdoc does with the swagger-core library, and the real document in the next section differs from it in two places: a primitive int is not listed as required, and @Size(max = 40) next to @NotBlank gives minLength: 0. The real generator also handles nested objects, enums, inheritance and Jackson annotations such as @JsonProperty. The point is that well-annotated records give accurate documentation for free, while a Map<String, Object> parameter tells the generator nothing.

Adding springdoc to a Spring Boot 4 application

For a Spring MVC application, one dependency adds the document and Swagger UI: org.springdoc:springdoc-openapi-starter-webmvc-ui, version 3.2.0 for Spring Boot 4.1. For the document without the UI, use springdoc-openapi-starter-webmvc-api; WebFlux applications use the matching webflux artifacts. No code is needed. With the dependency on the classpath, springdoc's auto-configuration serves these URLs:

Default springdoc endpoints
URLContent
/v3/api-docsThe OpenAPI document as JSON
/v3/api-docs.yamlThe same document as YAML
/swagger-ui.htmlSwagger UI, which loads the document
/v3/api-docs/{group}One group, when groups are configured

This program adds the dependency to a small product controller, without a single springdoc class or annotation in the code. It requests the four URLs, then prints the whole JSON document with the random port replaced by PORT:

Java
package demo.openapi.defaults;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;

@SpringBootApplication
public class ApiDocsDefault {

    public record Product(long id, String name, int stock) {}

    public record NewProduct(@NotBlank @Size(max = 40) String name, @Min(0) int stock) {}

    @RestController
    @RequestMapping("/api/products")
    static class ProductController {
        @GetMapping
        public List<Product> list(@RequestParam(defaultValue = "0") int page) {
            return List.of();
        }

        @GetMapping("/{id}")
        public Product get(@PathVariable long id) {
            return new Product(id, "lamp", 3);
        }

        @PostMapping
        public Product create(@Valid @RequestBody NewProduct body) {
            return new Product(1, body.name(), body.stock());
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(ApiDocsDefault.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN",
                            "logging.pattern.console=%-5level %logger{36} - %msg%n")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();
            for (String path : List.of("/v3/api-docs", "/v3/api-docs.yaml",
                    "/swagger-ui.html", "/swagger-ui/index.html")) {
                HttpResponse<String> response = http.send(HttpRequest.newBuilder(
                        URI.create("http://localhost:" + port + path)).build(),
                        HttpResponse.BodyHandlers.ofString());
                System.out.println("GET " + path + " -> " + response.statusCode() + " "
                        + response.headers().firstValue("Content-Type").orElse("")
                        + response.headers().firstValue("Location")
                                .map(l -> " Location: " + l.replace(":" + port, ":PORT"))
                                .orElse(""));
            }
            String json = http.send(HttpRequest.newBuilder(
                    URI.create("http://localhost:" + port + "/v3/api-docs")).build(),
                    HttpResponse.BodyHandlers.ofString()).body();
            ObjectMapper mapper = JsonMapper.builder()
                    .enable(SerializationFeature.INDENT_OUTPUT).build();
            JsonNode doc = mapper.readTree(json);
            System.out.println(mapper.writeValueAsString(doc).replace(":" + port, ":PORT"));
        }
    }
}
Output
WARN  o.s.c.events.SpringDocAppInitializer - SpringDoc /v3/api-docs endpoint is enabled by default. To disable it in production, set the property 'springdoc.api-docs.enabled=false'
WARN  o.s.c.events.SpringDocAppInitializer - SpringDoc /swagger-ui.html endpoint is enabled by default. To disable it in production, set the property 'springdoc.swagger-ui.enabled=false'
GET /v3/api-docs -> 200 application/json
GET /v3/api-docs.yaml -> 200 application/vnd.oai.openapi
GET /swagger-ui.html -> 302  Location: /swagger-ui/index.html
GET /swagger-ui/index.html -> 200 text/html
{
  "openapi" : "3.1.0",
  "info" : {
    "title" : "OpenAPI definition",
    "version" : "v0"
  },
  "servers" : [ {
    "url" : "http://localhost:PORT",
    "description" : "Generated server url"
  } ],
  "paths" : {
    "/api/products" : {
      "get" : {
        "tags" : [ "product-controller" ],
        "operationId" : "list",
        "parameters" : [ {
          "name" : "page",
          "in" : "query",
          "required" : false,
          "schema" : {
            "type" : "integer",
            "format" : "int32",
            "default" : 0
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "OK",
            "content" : {
              "*/*" : {
                "schema" : {
                  "type" : "array",
                  "items" : {
                    "$ref" : "#/components/schemas/Product"
                  }
                }
              }
            }
          }
        }
      },
      "post" : {
        "tags" : [ "product-controller" ],
        "operationId" : "create",
        "requestBody" : {
          "content" : {
            "application/json" : {
              "schema" : {
                "$ref" : "#/components/schemas/NewProduct"
              }
            }
          },
          "required" : true
        },
        "responses" : {
          "200" : {
            "description" : "OK",
            "content" : {
              "*/*" : {
                "schema" : {
                  "$ref" : "#/components/schemas/Product"
                }
              }
            }
          }
        }
      }
    },
    "/api/products/{id}" : {
      "get" : {
        "tags" : [ "product-controller" ],
        "operationId" : "get",
        "parameters" : [ {
          "name" : "id",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "integer",
            "format" : "int64"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "OK",
            "content" : {
              "*/*" : {
                "schema" : {
                  "$ref" : "#/components/schemas/Product"
                }
              }
            }
          }
        }
      }
    }
  },
  "components" : {
    "schemas" : {
      "NewProduct" : {
        "type" : "object",
        "properties" : {
          "name" : {
            "type" : "string",
            "maxLength" : 40,
            "minLength" : 0
          },
          "stock" : {
            "type" : "integer",
            "format" : "int32",
            "minimum" : 0
          }
        },
        "required" : [ "name" ]
      },
      "Product" : {
        "type" : "object",
        "properties" : {
          "id" : {
            "type" : "integer",
            "format" : "int64"
          },
          "name" : {
            "type" : "string"
          },
          "stock" : {
            "type" : "integer",
            "format" : "int32"
          }
        }
      }
    }
  }
}
  • The two WARN lines come from springdoc 3 at startup: both the document and Swagger UI are on by default, and springdoc reminds you to switch them off in production with the two properties it names.
  • /v3/api-docs returned JSON, and /v3/api-docs.yaml the same document with the media type application/vnd.oai.openapi. /swagger-ui.html is a redirect: it answered 302 with Location: /swagger-ui/index.html, the page served from the Swagger UI webjar.
  • The document declares "openapi" : "3.1.0". Without an OpenAPI bean, the title is OpenAPI definition and the version v0, and the server URL is taken from the incoming request, labelled Generated server url.
  • Every operation got the tag product-controller, made from the class name, and an operationId equal to the method name: list, create and get. Client generators use the operationId as the method name, so method names become part of the API.
  • page is an optional query parameter with "default" : 0, and id a required path parameter with format: int64, as the first program predicted. List<Product> became an array of $ref to the Product schema.
  • Every response is documented as 200 with content type */*: springdoc does not know which media types the converters will produce, or that a missing product causes a 404.
  • In NewProduct, @NotBlank made name required, and @Size(max = 40) added maxLength: 40, but also minLength: 0, the default min of @Size, which replaced the 1 that @NotBlank alone gives (the next program shows that case). stock got minimum: 0 but is not in required, although a missing primitive is rejected by Jackson 3.

The behaviour is controlled with springdoc.* properties. These are the ones most applications set, with their documented defaults:

  • springdoc.api-docs.path: /v3/api-docs; the path of the JSON document.
  • springdoc.swagger-ui.path: /swagger-ui.html; the path of the UI.
  • springdoc.api-docs.enabled and springdoc.swagger-ui.enabled: true; set them to false to switch off the document or only the UI.
  • springdoc.packages-to-scan and springdoc.paths-to-match: limit which controllers and paths are documented.
  • springdoc.show-actuator: false; Actuator endpoints are left out unless set.
  • springdoc.api-docs.version: openapi_3_1; set openapi_3_0 for tools that do not read 3.1 yet.

If Spring Security protects the application, the springdoc paths need a permitAll() rule, or the UI and document return 401. Whether to expose them in production is a decision about the audience: a public API benefits from it, while an internal API often switches the UI off with a profile and publishes the document elsewhere.

Describing operations with annotations

The annotations come from swagger-core's io.swagger.v3.oas.annotations package, which springdoc depends on. They add what the code cannot say: summaries, error responses, examples and grouping. This program annotates one operation, leaves a second one plain, and adds the document-wide beans discussed in the next section. It prints which paths each document contains, then parts of the public document by JSON pointer:

Java
package demo.openapi.annotated;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import jakarta.validation.constraints.NotBlank;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;

@SpringBootApplication
public class ApiDocsAnnotated {

    @Schema(description = "A product in the catalogue")
    public record Product(
            @Schema(description = "Unique id", example = "42") long id,
            @Schema(description = "Display name", example = "Desk lamp") String name,
            @Schema(description = "Units in stock", minimum = "0") int stock) {}

    public record Rename(@NotBlank String name) {}

    @RestController
    @RequestMapping("/api/products")
    @Tag(name = "Products", description = "The product catalogue")
    static class ProductController {
        @Operation(summary = "Get one product",
                   description = "Returns the product with the given id.")
        @ApiResponse(responseCode = "200", description = "The product")
        @ApiResponse(responseCode = "404", description = "No product with this id",
                     content = @Content(schema = @Schema(implementation = ProblemDetail.class)))
        @GetMapping("/{id}")
        public Product get(@Parameter(description = "Product id", example = "42")
                           @PathVariable long id) {
            return new Product(id, "Desk lamp", 3);
        }

        @PutMapping("/{id}/name")
        public Product rename(@PathVariable long id, @RequestBody Rename body) {
            return new Product(id, body.name(), 3);
        }
    }

    @RestController
    static class AdminController {
        @DeleteMapping("/admin/cache")
        public void clearCache() {
        }
    }

    @Bean
    OpenAPI shopApi() {
        return new OpenAPI()
                .info(new Info().title("Shop API").version("2.0")
                        .description("Orders, products and customers"))
                .components(new Components().addSecuritySchemes("bearer",
                        new SecurityScheme().type(SecurityScheme.Type.HTTP)
                                .scheme("bearer").bearerFormat("JWT")))
                .addSecurityItem(new SecurityRequirement().addList("bearer"));
    }

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

    @Bean
    GroupedOpenApi adminApi() {
        return GroupedOpenApi.builder().group("admin").pathsToMatch("/admin/**").build();
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(ApiDocsAnnotated.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN", "logging.level.org.springdoc=ERROR")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();
            ObjectMapper mapper = JsonMapper.builder()
                    .enable(SerializationFeature.INDENT_OUTPUT).build();
            for (String path : new String[] {"/v3/api-docs", "/v3/api-docs/public",
                    "/v3/api-docs/admin"}) {
                HttpResponse<String> response = http.send(HttpRequest.newBuilder(
                        URI.create("http://localhost:" + port + path)).build(),
                        HttpResponse.BodyHandlers.ofString());
                JsonNode doc = mapper.readTree(response.body());
                System.out.println("GET " + path + " -> " + response.statusCode()
                        + ", paths " + doc.path("paths").propertyNames());
            }
            JsonNode doc = mapper.readTree(http.send(HttpRequest.newBuilder(
                    URI.create("http://localhost:" + port + "/v3/api-docs/public")).build(),
                    HttpResponse.BodyHandlers.ofString()).body());
            for (String pointer : new String[] {"/info", "/security", "/tags",
                    "/components/securitySchemes", "/paths/~1api~1products~1{id}/get",
                    "/components/schemas/Product", "/components/schemas/Rename"}) {
                System.out.println(pointer + ":");
                System.out.println(mapper.writeValueAsString(doc.at(pointer)));
            }
        }
    }
}
Output
GET /v3/api-docs -> 200, paths [/api/products/{id}/name, /api/products/{id}, /admin/cache]
GET /v3/api-docs/public -> 200, paths [/api/products/{id}/name, /api/products/{id}]
GET /v3/api-docs/admin -> 200, paths [/admin/cache]
/info:
{
  "title" : "Shop API",
  "description" : "Orders, products and customers",
  "version" : "2.0"
}
/security:
[ {
  "bearer" : [ ]
} ]
/tags:
[ {
  "name" : "Products",
  "description" : "The product catalogue"
} ]
/components/securitySchemes:
{
  "bearer" : {
    "type" : "http",
    "scheme" : "bearer",
    "bearerFormat" : "JWT"
  }
}
/paths/~1api~1products~1{id}/get:
{
  "tags" : [ "Products" ],
  "summary" : "Get one product",
  "description" : "Returns the product with the given id.",
  "operationId" : "get",
  "parameters" : [ {
    "name" : "id",
    "in" : "path",
    "description" : "Product id",
    "required" : true,
    "schema" : {
      "type" : "integer",
      "format" : "int64"
    },
    "example" : 42
  } ],
  "responses" : {
    "200" : {
      "description" : "The product",
      "content" : {
        "*/*" : {
          "schema" : {
            "$ref" : "#/components/schemas/Product"
          }
        }
      }
    },
    "404" : {
      "description" : "No product with this id",
      "content" : {
        "*/*" : {
          "schema" : {
            "$ref" : "#/components/schemas/ProblemDetail"
          }
        }
      }
    }
  }
}
/components/schemas/Product:
{
  "type" : "object",
  "description" : "A product in the catalogue",
  "properties" : {
    "id" : {
      "type" : "integer",
      "format" : "int64",
      "description" : "Unique id",
      "example" : 42
    },
    "name" : {
      "type" : "string",
      "description" : "Display name",
      "example" : "Desk lamp"
    },
    "stock" : {
      "type" : "integer",
      "format" : "int32",
      "description" : "Units in stock",
      "minimum" : 0
    }
  }
}
/components/schemas/Rename:
{
  "type" : "object",
  "properties" : {
    "name" : {
      "type" : "string",
      "minLength" : 1
    }
  },
  "required" : [ "name" ]
}
  • @Tag replaced the generated tag: the operation is listed under Products, and the tag's description appears in the top-level tags list.
  • @Operation supplied summary and description, and @Parameter added the description and "example" : 42 to the id parameter.
  • The two @ApiResponse annotations replaced the generated 200 OK. The 404 response refers to a ProblemDetail schema, which springdoc generated from Spring's class.
  • @Schema on the record and its components added descriptions, examples and minimum: 0 to the Product schema.
  • The Rename schema has minLength: 1 and required from @NotBlank alone. Its controller parameter has no @Valid, so the server never checks the constraint: the document promises a rule that is not enforced. springdoc reads the annotations on the type, not whether validation runs.
  • @Hidden on a controller or method, or @Operation(hidden = true), leaves it out of the document.

Annotations make controllers longer, and too many of them hide the code. springdoc can also read Javadoc instead: method comments become operation descriptions and field comments become schema descriptions, when the therapi-runtime-javadoc library and its annotation processor are added to the build. Without that library, the Javadoc support fails silently.

Document-wide settings, security and groups

Some information belongs to the whole API rather than one operation: its title and version, the servers, and how clients authenticate. springdoc takes these from an OpenAPI bean. Groups split a large API into several documents. The previous program declares both, in the bean methods shopApi, publicApi and adminApi:

  • The Info object replaced the defaults: the /info output shows the title Shop API, version 2.0 and the description, which Swagger UI shows at the top.
  • The SecurityScheme appears under components/securitySchemes as http with scheme: bearer, and the SecurityRequirement as the top-level security list, which applies it to every operation. Swagger UI shows an Authorize button that adds the token to each request.
  • Each GroupedOpenApi became its own document. /v3/api-docs/public held the two /api paths and /v3/api-docs/admin only /admin/cache, while /v3/api-docs still held all three. Swagger UI offers a selector between the groups.
  • An OpenApiCustomizer bean changes the finished document, for example to sort tags. According to the springdoc documentation, a customizer bean applies to the default document only. Groups take their own customizers through the builder's addOpenApiCustomizer, and a GlobalOpenApiCustomizer bean applies to every group.

Keeping the document honest

  • Publish it from the build: the springdoc-openapi-maven-plugin has a generate goal that downloads /v3/api-docs to a file, while the Spring Boot Maven plugin's start and stop goals run the application around it during the integration-test phase. Commit that file, or publish it, so that client teams see each change.
  • Diff it in CI: compare the generated document with the previous release using an OpenAPI diff tool, and fail the build on breaking changes. Combined with API versioning, this catches changes that need a new version.
  • Use real types: records with constraints produce precise schemas, as the second program showed. Map, Object and JsonNode parameters produce empty ones.
  • Document errors once: return ProblemDetail from a @RestControllerAdvice, as in Spring Boot exception handling, so that every error response has the same documented schema.
  • Paging parameters: for Spring Data Pageable parameters, annotate them with springdoc's @ParameterObject, so that page, size and sort appear as separate query parameters.

Choosing how to document an API

OpenAPI approaches for Spring Boot
SituationUse
Existing controllers, documentation wanted quicklyspringdoc-openapi-starter-webmvc-ui with no code
Document only, UI hosted elsewherespringdoc-openapi-starter-webmvc-api
Summaries, examples and error responses@Operation, @ApiResponse, @Schema, or Javadoc with therapi
Authentication in Swagger UIA SecurityScheme in the OpenAPI bean
Public and internal endpoints in one applicationGroupedOpenApi beans
Tools that only read OpenAPI 3.0springdoc.api-docs.version=openapi_3_0
API designed with clients before codingContract first: write the YAML and generate interfaces
Catching breaking changesGenerate the document in the build and diff it in CI

Whichever approach you pick, the document can only be as precise as the controllers behind it. For writing those controllers, see Spring Boot @RestController.