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 What a generator can learn from a controller From Bean Validation constraints to JSON Schema Adding springdoc to a Spring Boot 4 application Describing operations with annotations Document-wide settings, security and groups Keeping the document honest Choosing how to document an API
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 line | Spring Boot | Notes |
|---|---|---|
| 3.x | 4.0 and 4.1 | 3.0.x for Boot 4.0; 3.1.x and 3.2.x for Boot 4.1 |
| 2.x | 3.x | The last line for Spring Boot 3 |
| 1.x | 2.x | Artifacts named springdoc-openapi-ui |
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
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
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));
}
});
}
}
}
[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
, with the HTTP method and path pattern, and aRequestMappingInfo , with the Java method. Four mappings produced four OpenAPI operations:HandlerMethod andDELETE onGET , and/api/products/{id} andGET onPOST ./api/products - Path variables are always required.
is optional because it has a default value, andpage because ofname . springdoc applies the same rules when it setsrequired = false on each parameter.required - The return types tell the generator the response schema:
becomes an array ofList<Product> , andProduct is unwrapped toResponseEntity<Product> . A method returningProduct has no body to describe.void - The
mapping declaresPOST , and its body parameter is validated, so the generator can document the content type and look for constraints onconsumes .NewProduct - Parameter names such as
andpage come from the class file, which works because the code was compiled withid , as the Spring Boot build plugins do. Without it, a generator sees only-parameters .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:
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)));
}
}
{
"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
}
}
}
}
on@NotBlank became two things: an entry inname andrequired .minLength: 1 added@Size(max = 40) .maxLength: 40 on@NotNull @Email made it required withemail . Format values are hints to tools; JSON Schema validators do not have to check them.format: email is anage , so it is required even without an annotation, andint became@Min(18) @Max(120) andminimum . In Spring Boot 4, Jackson 3 rejects a missing primitive, as shown inmaximumSpring Boot @RestController , so required is the honest description. 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.@Pattern becameBigDecimal ,number becameLocalDate withstring , and theformat: date withList became an@Size(max = 5) witharray .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@Size(max = 40)@NotBlankminLength: 0@JsonPropertyMap<String, Object>
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-uispringdoc-openapi-starter-webmvc-apiwebflux
| URL | Content |
|---|---|
/v3/api-docs | The OpenAPI document as JSON |
/v3/api-docs.yaml | The same document as YAML |
/swagger-ui.html | Swagger 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
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"));
}
}
}
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
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.WARN returned JSON, and/v3/api-docs the same document with the media type/v3/api-docs.yaml .application/vnd.oai.openapi is a redirect: it answered 302 with/swagger-ui.html , the page served from the Swagger UI webjar.Location: /swagger-ui/index.html- The document declares
. Without an"openapi" : "3.1.0" bean, the title isOpenAPI and the versionOpenAPI definition , and the server URL is taken from the incoming request, labelledv0 .Generated server url - Every operation got the tag
, made from the class name, and anproduct-controller equal to the method name:operationId ,list andcreate . Client generators use theget as the method name, so method names become part of the API.operationId is an optional query parameter withpage , and"default" : 0 a required path parameter withid , as the first program predicted.format: int64 became anList<Product> ofarray to the$ref schema.Product- Every response is documented as
with content type200 : springdoc does not know which media types the converters will produce, or that a missing product causes a 404.*/* - In
,NewProduct made@NotBlank required, andname added@Size(max = 40) , but alsomaxLength: 40 , the defaultminLength: 0 ofmin , which replaced the 1 that@Size alone gives (the next program shows that case).@NotBlank gotstock but is not inminimum: 0 , although a missing primitive is rejected by Jackson 3.required
The behaviour is controlled with springdoc.*
:springdoc.api-docs.path ; the path of the JSON document./v3/api-docs :springdoc.swagger-ui.path ; the path of the UI./swagger-ui.html andspringdoc.api-docs.enabled :springdoc.swagger-ui.enabled ; set them totrue to switch off the document or only the UI.false andspringdoc.packages-to-scan : limit which controllers and paths are documented.springdoc.paths-to-match :springdoc.show-actuator ; Actuator endpoints are left out unless set.false :springdoc.api-docs.version ; setopenapi_3_1 for tools that do not read 3.1 yet.openapi_3_0
If Spring Security protects the application, the springdoc paths need a permitAll()
Describing operations with annotations
The annotations come from swagger-core's io.swagger.v3.oas.annotationspublic
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)));
}
}
}
}
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" ]
}
replaced the generated tag: the operation is listed under@Tag , and the tag's description appears in the top-levelProducts list.tags supplied@Operation andsummary , anddescription added the description and@Parameter to the"example" : 42 parameter.id- The two
annotations replaced the generated@ApiResponse . The 404 response refers to a200 OK schema, which springdoc generated from Spring's class.ProblemDetail on the record and its components added descriptions, examples and@Schema to theminimum: 0 schema.Product- The
schema hasRename andminLength: 1 fromrequired alone. Its controller parameter has no@NotBlank , 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.@Valid on a controller or method, or@Hidden , leaves it out of the document.@Operation(hidden = true)
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
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 OpenAPIshopApipublicApiadminApi
- The
object replaced the defaults: theInfo output shows the title/info , versionShop API and the description, which Swagger UI shows at the top.2.0 - The
appears underSecurityScheme ascomponents/securitySchemes withhttp , and thescheme: bearer as the top-levelSecurityRequirement list, which applies it to every operation. Swagger UI shows an Authorize button that adds the token to each request.security - Each
became its own document.GroupedOpenApi held the two/v3/api-docs/public paths and/api only/v3/api-docs/admin , while/admin/cache still held all three. Swagger UI offers a selector between the groups./v3/api-docs - An
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'sOpenApiCustomizer , and aaddOpenApiCustomizer bean applies to every group.GlobalOpenApiCustomizer
Keeping the document honest
- Publish it from the build: the
has aspringdoc-openapi-maven-plugin goal that downloadsgenerate to a file, while the Spring Boot Maven plugin's/v3/api-docs andstart goals run the application around it during the integration-test phase. Commit that file, or publish it, so that client teams see each change.stop - 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 andObject parameters produce empty ones.JsonNode - Document errors once: return
from aProblemDetail , as in@RestControllerAdviceSpring Boot exception handling , so that every error response has the same documented schema. - Paging parameters: for Spring Data
parameters, annotate them with springdoc'sPageable , so that@ParameterObject ,page andsize appear as separate query parameters.sort
Choosing how to document an API
| Situation | Use |
|---|---|
| Existing controllers, documentation wanted quickly | springdoc-openapi-starter-webmvc-ui |
| Document only, UI hosted elsewhere | springdoc-openapi-starter-webmvc-api |
| Summaries, examples and error responses | @Operation@ApiResponse@Schema |
| Authentication in Swagger UI | A SecuritySchemeOpenAPI |
| Public and internal endpoints in one application | GroupedOpenApi |
| Tools that only read OpenAPI 3.0 | springdoc.api-docs.version=openapi_3_0 |
| API designed with clients before coding | Contract first: write the YAML and generate interfaces |
| Catching breaking changes | Generate 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