Sub topic 8
Documenting Request and Response Models
This chapter assumes you can write Spring Boot REST controllers, add the springdoc starter, and use basic Bean Validation annotations such as @NotBlank. Here you will learn how springdoc turns your Java types into the components/schemas section of the OpenAPI document, and how to improve that output.
How springdoc Builds Schemas
When a controller method takes a @RequestBody or returns an object, springdoc inspects the Java type and writes a schema for it. It uses the Swagger Core library for this. Each class becomes an entry under components/schemas. Operations point to that entry with a $ref, so the same model is described once and reused.
With no annotations at all, springdoc already gives you:
- Property names, taken from the same naming rules Jackson uses.
- Property types, such as
string,integerwithformat: int64, orarray. - A
requiredlist, based on constraint annotations. - Nested objects, collections, enums and
Maptypes.
Annotations add the human-facing details: descriptions, examples and access rules.
Describing a Model with @Schema
@Schema can sit on a class, a record component or a field. On a type it describes the whole model. On a property it describes one field.
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
@Schema(description = "A book in the catalog")
public record Book(
@Schema(description = "Unique identifier", example = "42", accessMode = Schema.AccessMode.READ_ONLY)
Long id,
@NotBlank
@Size(max = 200)
@Schema(description = "Title of the book", example = "Dune")
String title,
@NotBlank
@Schema(description = "Author name", example = "Frank Herbert")
String author) {
}The generated schema looks roughly like this:
{
"Book": {
"required": ["author", "title"],
"type": "object",
"description": "A book in the catalog",
"properties": {
"id": { "type": "integer", "format": "int64", "description": "Unique identifier", "readOnly": true, "example": 42 },
"title": { "type": "string", "description": "Title of the book", "example": "Dune", "maxLength": 200 },
"author": { "type": "string", "description": "Author name", "example": "Frank Herbert" }
}
}
}The exact key order and some details vary by springdoc version, but the content should match this shape.
The most useful @Schema attributes are:
| Attribute | Effect in the document |
|---|---|
| `description` | Text shown next to the field or model |
| `example` | Sample value used in Swagger UI request bodies |
| `accessMode` | `READ_ONLY` or `WRITE_ONLY`, which marks the field as response-only or request-only |
| `requiredMode` | `REQUIRED` or `NOT_REQUIRED`, which overrides the inferred requirement |
| `nullable` | Marks the value as allowed to be null |
| `allowableValues` | Restricts a string to a fixed set of values |
| `hidden` | Removes the field from the schema |
| `name` | Changes the schema name for a class |
How Bean Validation Is Reflected
springdoc reads Bean Validation annotations on the model and converts them into schema keywords. You do not need to repeat the rule in @Schema.
| Annotation | Schema result |
|---|---|
| `@NotNull`, `@NotBlank`, `@NotEmpty` | Property added to `required` |
| `@Size(min, max)` | `minLength` and `maxLength` for strings, `minItems` and `maxItems` for collections |
| `@Min`, `@Max` | `minimum` and `maximum` |
| `@Pattern` | `pattern` |
| `@Email` | `format: email` |
This is a strong reason to put constraints on the model instead of describing them in prose. The runtime check and the documentation then come from one source and cannot drift apart.
Separate Request and Response Models
A single class used for both input and output often causes confusion. A client sending a POST should not provide an id, but a client reading the result expects one. accessMode = READ_ONLY marks id as response-only, so Swagger UI leaves it out of the example request body.
Many teams go one step further and use separate types. This keeps the documented contract exact.
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
@Schema(description = "Data needed to create a book")
public record CreateBookRequest(
@NotBlank @Size(max = 200)
@Schema(description = "Title of the book", example = "Dune")
String title,
@NotBlank
@Schema(description = "Author name", example = "Frank Herbert")
String author) {
}import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "A book as returned by the API")
public record BookResponse(
@Schema(description = "Unique identifier", example = "42")
long id,
@Schema(description = "Title of the book", example = "Dune")
String title,
@Schema(description = "Author name", example = "Frank Herbert")
String author,
@Schema(description = "Publication status", allowableValues = {"DRAFT", "PUBLISHED"}, example = "PUBLISHED")
String status) {
}A controller then declares each type in its signature:
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/books")
public class BookCreateController {
private final BookService service;
public BookCreateController(BookService service) {
this.service = service;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public BookResponse create(@Valid @RequestBody CreateBookRequest request) {
return service.create(request);
}
}springdoc reads the parameter type for the request body and the return type for the response. @ResponseStatus(HttpStatus.CREATED) also changes the documented success code to 201.
Enums, Collections and Nesting
Enums are documented as a string with an enum list of the constant names. If you would rather use a Java enum than allowableValues, declare the field with that type:
public enum BookStatus { DRAFT, PUBLISHED }A List<BookResponse> return type produces an array whose items reference the BookResponse schema. A nested record is documented as its own entry in components/schemas and referenced by $ref.
For generic wrappers such as Page<BookResponse> or your own ApiResult<T>, springdoc resolves the type argument. The generated schema name combines the wrapper and the argument, for example PageBookResponse.
Common Problems
- Two classes share a simple name. If
com.a.Bookandcom.b.Bookboth appear, schemas can collide because the simple class name is the key. Give one a different name with@Schema(name = "LegacyBook"). - Jackson settings change the output. Annotations such as
@JsonProperty("book_title")and@JsonIgnorechange the documented property names and drop ignored fields, because springdoc follows Jackson's view of the type. - Constraints are missing. Constraints appear only if the validation API is on the classpath. Spring Boot's
spring-boot-starter-validationprovides it. - Entities leak into the contract. Returning a JPA entity exposes every field, including internal ones, and lazy relationships can produce large or recursive schemas. A dedicated response type avoids both problems.
- Examples that do not match the type.
example = "forty-two"on alongfield produces an invalid example. Swagger UI shows it, but clients that generate code or tests from the document may fail. - Field
exampleon required enums. For an enum field, the example should be one of the constants. Otherwise the value fails validation if copied into a request.
Checking the Result
Start the application and request the schema section of the document:
curl -s http://localhost:8080/v3/api-docs | jq '.components.schemas'You should see one entry per model type used by your operations. Open /swagger-ui.html and expand an operation. The "Schema" tab of the request body lists each property with its description, constraints and type, and the "Example Value" tab shows the example values you set.
Exercise
A POST /api/books endpoint uses one Book record for both the request and the response. The record has an id field. Swagger UI shows id in the example request body, and users keep sending it. Give two ways to fix the documentation, and say which one also gives you a stricter contract.
Show answer
First, add @Schema(accessMode = Schema.AccessMode.READ_ONLY) to id. Swagger UI then omits it from the request example and marks it readOnly in the schema. Second, split the model into a CreateBookRequest without id and a BookResponse with id. The second option gives the stricter contract, because the request schema cannot contain id at all. The first option only changes the document, and Jackson still accepts the field if a client sends it.
Exercise
Your CreateBookRequest has @NotBlank @Size(max = 200) String title, and the generated schema shows title in required with maxLength: 200. Requests with a blank title still return 201. What is missing?
Show answer
The controller parameter is not annotated with @Valid (or @Validated). springdoc reads the constraints to document them, but Spring only enforces them when validation is triggered on the @RequestBody argument. Add @Valid before @RequestBody.