Skip to lesson

Describing endpoints, parameters and responses

ShopLite's generated docs say create returns 200, name operations get_1, show "sku": "string" and list no errors. A tester who presses Execute on that example gets a 400 and cannot tell why.

@Tag and @Operation with a summary and description

@Operation is a Swagger annotation on a controller method that gives the endpoint a summary (the short line beside the URL), a longer description and a unique operationId. @Tag on the class names the group.

Here is the category controller with @Tag on the class and @Operation on each method.

Example 1 · CategoryController.java with @Tag and @Operation

Runs in: the shoplite-api Spring Boot project

Java
// src/main/java/com/shoplite/category/CategoryController.javapackage com.shoplite.category;
import java.net.URI;import java.util.List;
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.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import jakarta.validation.Valid;
@Tag(name = "Categories", description = "Product categories such as Mobiles and Books, at most one parent each")@RestController@RequestMapping("/api/v1/categories")class CategoryController {
    private final CategoryService service;
    CategoryController(CategoryService service) {        this.service = service;    }
    @Operation(operationId = "listCategories", summary = "List all categories",            description = "The whole list, ordered by id. Not paged: a store has only a handful of categories.")    @GetMapping    List<CategoryResponse> list() {        return service.findAll();    }
    @Operation(operationId = "getCategory", summary = "Get one category")    @GetMapping("/{id}")    CategoryResponse get(@PathVariable Long id) {        return service.get(id);    }
    @Operation(operationId = "createCategory", summary = "Create a category",            description = "Names are unique, ignoring case. parentId is optional and must be an existing category.")    @PostMapping    ResponseEntity<CategoryResponse> create(@Valid @RequestBody CategoryRequest request) {        CategoryResponse created = service.create(request);        URI location = ServletUriComponentsBuilder.fromCurrentRequest()                .path("/{id}").buildAndExpand(created.id()).toUri();        return ResponseEntity.created(location).body(created);    }
    @Operation(operationId = "replaceCategory", summary = "Replace a category",            description = "Send both name and parentId; parentId may be null for a top-level category.")    @PutMapping("/{id}")    CategoryResponse replace(@PathVariable Long id, @Valid @RequestBody CategoryRequest request) {        return service.replace(id, request);    }
    @Operation(operationId = "deleteCategory", summary = "Delete a category",            description = "Only a category with no products and no sub-categories can be deleted.")    @DeleteMapping("/{id}")    ResponseEntity<Void> delete(@PathVariable Long id) {        service.delete(id);        return ResponseEntity.noContent().build();    }}
Sample output
$ curl http://localhost:8080/v3/api-docs        (formatted and trimmed)
{
  "tags": [
    {
      "name": "Categories",
      "description": "Product categories such as Mobiles and Books, at most one parent each"
    },
    {
      "name": "Products",
      "description": "The store's catalogue: search, create, change and delete products"
    }
  ],
  "paths": {
    "/api/v1/categories": {
      "get": {
        "tags": [
          "Categories"
        ],
        "summary": "List all categories",
        "description": "The whole list, ordered by id. Not paged: a store has only a handful of categories.",
        "operationId": "listCategories",
        ...
      },
      "post": {
        "tags": [
          "Categories"
        ],
        "summary": "Create a category",
        "description": "Names are unique, ignoring case. parentId is optional and must be an existing category.",
        "operationId": "createCategory",
        ...
      }
    },
    "/api/v1/categories/{id}": { ... },
    ...
  }
}

What this code does

  • @Tag adds a top-level tags list with the description, and every operation now says "tags": ["Categories"] instead of category-controller.
  • Each @Operation sets summary, description and an operationId such as listCategories, replacing list_1.
  • Nothing about the HTTP behaviour changed: these annotations only feed the docs.

Without them, the group is the class name (category-controller) and the operationId is the method name made unique with a number: get, get_1, list_1. An operationId is the endpoint's unique name in the spec. Postman and client generators use it as a request or method name, so getCategory beats get_1.

Write the summary as a short command ("Create a category") and put rules in the description: what is unique, which fields are optional, what the endpoint will refuse.

An operationId must be unique across the whole API, not only in one controller. Use the pattern verb + resource: listProducts, getProduct, createProduct.

@Parameter for path and query parameters

@Parameter is a Swagger annotation in front of a method parameter that adds a description and an example. springdoc already knows its name, whether it is path or query, its type, default and required flag.

Here is the product list method with @Parameter on each query parameter.

Example 2 · ProductController.list with @Parameter on each query parameter

Runs in: the shoplite-api Spring Boot project

Java
// src/main/java/com/shoplite/product/ProductController.java (the list method; imports as in the file)    @Operation(operationId = "listProducts", summary = "Search products, one page at a time",            description = "Only active products unless includeInactive=true. Ties in the sort order are broken by id.")    @ApiResponse(responseCode = "200", description = "One page of products")    @ApiResponse(responseCode = "400", ref = "ValidationFailed")    @GetMapping    PageResponse<ProductResponse> list(            @Parameter(description = "Name or SKU contains this text, ignoring case", example = "redmi")            @RequestParam(required = false) String q,            @Parameter(description = "Only this category", example = "2")            @RequestParam(required = false) Long categoryId,            @Parameter(description = "Lowest price in rupees, inclusive", example = "10000")            @RequestParam(required = false) BigDecimal minPrice,            @Parameter(description = "Highest price in rupees, inclusive", example = "50000")            @RequestParam(required = false) BigDecimal maxPrice,            @Parameter(description = "true: only products with stock above 0")            @RequestParam(defaultValue = "false") boolean inStock,            @Parameter(description = "true: also show inactive products")            @RequestParam(defaultValue = "false") boolean includeInactive,            @Parameter(description = "Page number, starting at 0")            @RequestParam(defaultValue = "0") @Min(value = 0, message = "must be 0 or more") int page,            @Parameter(description = "Products per page, 1-100")            @RequestParam(defaultValue = "20") @Min(value = 1, message = "must be between 1 and 100")            @Max(value = 100, message = "must be between 1 and 100") int size,            @Parameter(description = "id, name, price or stock, with an optional ,asc or ,desc", example = "price,desc")            @RequestParam(defaultValue = "id,asc")            @Pattern(regexp = "^(id|name|price|stock)(,(asc|desc))?$",                     message = "must be one of id, name, price, stock") String sort) {        ProductFilter filter = new ProductFilter(q, categoryId, minPrice, maxPrice, inStock, includeInactive);        return service.search(filter, sort, page, size);    }
Sample output
$ curl http://localhost:8080/v3/api-docs        (formatted and trimmed)
{
  "paths": {
    "/api/v1/products": {
      "get": {
        ...
        "parameters": [
          {
            "name": "q",
            "in": "query",
            "description": "Name or SKU contains this text, ignoring case",
            "required": false,
            "schema": {
              "type": "string"
            },
            "example": "redmi"
          },
          {
            "name": "categoryId",
            "in": "query",
            "description": "Only this category",
            "required": false,
            "schema": {
              "type": "integer",
              "format": "int64"
            },
            "example": 2
          },
          ...
          {
            "name": "size",
            "in": "query",
            "description": "Products per page, 1-100",
            "required": false,
            "schema": {
              "type": "integer",
              "format": "int32",
              "default": 20,
              "maximum": 100,
              "minimum": 1
            }
          },
          {
            "name": "sort",
            "in": "query",
            "description": "id, name, price or stock, with an optional ,asc or ,desc",
            "required": false,
            "schema": {
              "type": "string",
              "default": "id,asc",
              "pattern": "^(id|name|price|stock)(,(asc|desc))?$"
            },
            "example": "price,desc"
          }
        ],
        ...
      }
    }
  }
}

What this code does

  • description and example come from @Parameter; in: query, required: false and the types come from @RequestParam.
  • default: 20, minimum: 1 and maximum: 100 on size come from defaultValue and the @Min and @Max constraints, with no extra work.
  • In Swagger UI, Try it out fills the boxes with the examples (redmi, 2, 10000, 50000, price,desc) and page 0 and size 20 from the defaults; inStock gets a true/false drop-down.

Constraints on the parameter flow into its schema: @Min(0) becomes minimum: 0, @Max(100) becomes maximum: 100, @Pattern becomes pattern. What no annotation can say is the meaning: is minPrice inclusive? Is page counted from 0 or 1? That goes in the description.

The example is what Swagger UI pre-fills for Try it out, so choose values that work with the seed data: product 1, category 2, sort=price,desc.

@ApiResponse for 201, 400, 404 and 409 with the ProblemDetail schema

@ApiResponse is a Swagger annotation that documents one status code of an operation: responseCode, description and optionally headers and content. Once a method has any, springdoc uses only your list.

First try: Spring's ProblemDetail class as the 404 schema. Then the version ShopLite uses, with a docs-only record and shared responses.

Example 3 · A first try: Spring's ProblemDetail class as the 404 schema

Runs in: the shoplite-api Spring Boot project

Java
// CategoryController.java, a first try at documenting the 404@Operation(operationId = "getCategory", summary = "Get one category")@ApiResponse(responseCode = "200", description = "The category")@ApiResponse(responseCode = "404", description = "No category has this id",        content = @Content(mediaType = "application/problem+json",                schema = @Schema(implementation = ProblemDetail.class)))   // Spring's class@GetMapping("/{id}")CategoryResponse get(@Parameter(description = "Category id", example = "2") @PathVariable Long id) {    return service.get(id);}
Sample output
$ curl http://localhost:8080/v3/api-docs.yaml        (trimmed)
paths:
  /api/v1/categories/{id}:
    get:
      ...
      responses:
        "404":
          description: No category has this id
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetail"
...
components:
  schemas:
    ProblemDetail:
      type: object
      properties:
        type:
          type: string
          format: uri
        title:
          type: string
        status:
          type: integer
          format: int32
        detail:
          type: string
        instance:
          type: string
          format: uri
        properties:
          type: object
          additionalProperties: {}

$ curl http://localhost:8080/api/v1/categories/99        (the real error body)
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Category 99 was not found.","instance":"/api/v1/categories/99"}

What this code does

  • The 404 now appears with application/problem+json, and the default 200 OK became "The category" from the first @ApiResponse.
  • But the schema is generated from Spring's class: type and instance as uri, and a properties object. Spring writes those extra properties as top-level fields, so a real error never contains properties.
  • There is also no errors field for validation errors. Example 4 replaces this with a schema that matches the real JSON.

Example 4 · ApiProblem.java, InvalidField.java and the shared responses in OpenApiConfig.java

Runs in: the shoplite-api Spring Boot project

ApiProblem.javaJava
package com.shoplite.common;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
/** * Documentation only: the exact JSON of a ShopLite error. The handler builds a Spring ProblemDetail; * this record describes what the client receives, including the "errors" extension. */@Schema(name = "ProblemDetail", description = "Every ShopLite error (RFC 9457), sent as application/problem+json")public record ApiProblem(        @Schema(description = "The problem kind; clients branch on it",                example = "https://shoplite.example/problems/not-found")        String type,
        @Schema(description = "Fixed text for the kind", example = "Resource not found")        String title,
        @Schema(description = "Same as the HTTP status code", example = "404")        int status,
        @Schema(description = "One sentence about this occurrence, safe to show a user",                example = "Product 99 was not found.")        String detail,
        @Schema(description = "The request path", example = "/api/v1/products/99")        String instance,
        @Schema(description = "Only for validation-failed: every broken field",                requiredMode = Schema.RequiredMode.NOT_REQUIRED)        List<InvalidField> errors) {}
package com.shoplite.common;
import io.swagger.v3.oas.annotations.media.Schema;
/** One broken field inside a validation-failed problem. */@Schema(description = "One invalid field or query parameter")public record InvalidField(        @Schema(description = "Field name; items use items[0].quantity", example = "price")        String field,
        @Schema(description = "What is wrong with it", example = "must be greater than 0")        String message) {}
package com.shoplite.common;
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
import io.swagger.v3.core.converter.ModelConverters;import io.swagger.v3.oas.models.Components;import io.swagger.v3.oas.models.OpenAPI;import io.swagger.v3.oas.models.info.Contact;import io.swagger.v3.oas.models.info.Info;import io.swagger.v3.oas.models.media.Content;import io.swagger.v3.oas.models.media.MediaType;import io.swagger.v3.oas.models.media.Schema;import io.swagger.v3.oas.models.responses.ApiResponse;
/** ShopLite's API docs: the cover page (info) and the error responses every controller refers to by name. */@Configurationclass OpenApiConfig {
    private static final String PROBLEMS = "https://shoplite.example/problems/";
    @Bean    OpenAPI shopLiteOpenApi() {        Components components = new Components();        ModelConverters.getInstance().readAll(ApiProblem.class).forEach(components::addSchemas);
        components.addResponses("ValidationFailed", problem("Invalid fields, or a body that is not valid JSON",                example("validation-failed", "Validation failed", 400, "The request has 1 invalid field.",                        "/api/v1/products", List.of(invalid("price", "must be greater than 0")))));        components.addResponses("NotFound", problem("No resource has this id",                example("not-found", "Resource not found", 404, "Product 99 was not found.",                        "/api/v1/products/99", null)));        components.addResponses("AlreadyExists", problem("The name or SKU is already used",                example("already-exists", "Resource already exists", 409,                        "A product with SKU MOB-RN13 already exists.", "/api/v1/products", null)));        components.addResponses("InUse", problem("Still used by other data, so it cannot be deleted",                example("in-use", "Resource in use", 409,                        "Category 1 has sub-categories and cannot be deleted.", "/api/v1/categories/1", null)));        components.addResponses("RuleBroken", problem("Refers to data that does not exist",                example("rule-broken", "Business rule broken", 422, "Category 42 does not exist.",                        "/api/v1/products", null)));
        return new OpenAPI()                .info(new Info()                        .title("ShopLite API")                        .version("v1")                        .description("REST API of ShopLite, a small online store for India. "                                + "Money is in rupees with two decimals; errors use Problem Details (RFC 9457).")                        .contact(new Contact()                                .name("ShopLite API team")                                .email("api@shoplite.example")                                .url("https://shoplite.example")))                .components(components);    }
    private static ApiResponse problem(String description, Map<String, Object> example) {        MediaType mediaType = new MediaType()                .schema(new Schema<>().$ref("#/components/schemas/ProblemDetail"))                .example(example);        return new ApiResponse()                .description(description)                .content(new Content().addMediaType("application/problem+json", mediaType));    }
    private static Map<String, String> invalid(String field, String message) {        Map<String, String> error = new LinkedHashMap<>();        error.put("field", field);        error.put("message", message);        return error;    }
    private static Map<String, Object> example(String kind, String title, int status, String detail,                                               String instance, List<Map<String, String>> errors) {        Map<String, Object> body = new LinkedHashMap<>();        body.put("type", PROBLEMS + kind);        body.put("title", title);        body.put("status", status);        body.put("detail", detail);        body.put("instance", instance);        if (errors != null) {            body.put("errors", errors);        }        return body;    }}
Sample output
$ curl http://localhost:8080/v3/api-docs        (formatted and trimmed)
{
  "paths": {
    "/api/v1/products": {
      "post": {
        ...
        "responses": {
          "201": {
            "description": "Created",
            "headers": {
              "Location": {
                "description": "URL of the new product",
                "style": "simple"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProductResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/ValidationFailed"
          },
          "409": {
            "$ref": "#/components/responses/AlreadyExists"
          },
          "422": {
            "$ref": "#/components/responses/RuleBroken"
          }
        }
      }
    },
    ...
  },
  "components": {
    "schemas": {
      "ProblemDetail": {
        "description": "Every ShopLite error (RFC 9457), sent as application/problem+json",
        "properties": {
          "type": {
            "type": "string",
            "description": "The problem kind; clients branch on it",
            "example": "https://shoplite.example/problems/not-found"
          },
          "title": {
            "type": "string",
            "description": "Fixed text for the kind",
            "example": "Resource not found"
          },
          "status": {
            "type": "integer",
            "format": "int32",
            "description": "Same as the HTTP status code",
            "example": 404
          },
          "detail": {
            "type": "string",
            "description": "One sentence about this occurrence, safe to show a user",
            "example": "Product 99 was not found."
          },
          "instance": {
            "type": "string",
            "description": "The request path",
            "example": "/api/v1/products/99"
          },
          "errors": {
            "type": "array",
            "description": "Only for validation-failed: every broken field",
            "items": {
              "$ref": "#/components/schemas/InvalidField"
            }
          }
        }
      },
      ...
    },
    "responses": {
      "ValidationFailed": {
        "description": "Invalid fields, or a body that is not valid JSON",
        "content": {
          "application/problem+json": {
            "schema": {
              "$ref": "#/components/schemas/ProblemDetail"
            },
            "example": {
              "type": "https://shoplite.example/problems/validation-failed",
              "title": "Validation failed",
              "status": 400,
              "detail": "The request has 1 invalid field.",
              "instance": "/api/v1/products",
              "errors": [
                {
                  "field": "price",
                  "message": "must be greater than 0"
                }
              ]
            }
          }
        }
      },
      "NotFound": { ... },
      "AlreadyExists": { ... },
      "InUse": { ... },
      "RuleBroken": { ... }
    }
  }
}

What this code does

  • ApiProblem is only for the docs: @Schema(name = "ProblemDetail") names it like the standard, and its fields are exactly what ShopLite sends, including errors. ModelConverters turns it into schemas inside the OpenAPI bean.
  • Each error is declared once under components.responses with its own example body. Controllers point to them by name: @ApiResponse(responseCode = "409", ref = "AlreadyExists") became "$ref": "#/components/responses/AlreadyExists".
  • createProduct now documents exactly the contract's statuses: 201 with a Location header, 400, 409 and 422. The method itself is shown below this example.

springdoc cannot see inside a method. ResponseEntity.created(...) decides 201 at runtime, so the generated spec says 200. A thrown ResourceNotFoundException is turned into 404 by the global handler, which the method signature does not show, so no error appears. Errors must be listed by hand, as application/problem+json.

Spring's ProblemDetail is documented wrong: the spec shows a properties field that never appears in a real response and has no errors field. ShopLite describes the real JSON with a docs-only record, declares each error once in the OpenAPI bean under components.responses, and a method just writes @ApiResponse(responseCode = "404", ref = "NotFound").

Find the bug

Spot the wrong doc line

Click the line that makes the docs untrue.

The create method answers 201 Created. Which line is wrong?

Round 1 of 2
Document every status the ShopLite contract lists for the endpoint, and no others: a 409 that can never happen is as misleading as a missing one.

@Schema on DTO records: descriptions and example values

@Schema is a Swagger annotation that describes a class or one of its fields in components.schemas: description, example, defaultValue and more. On a record, it goes on the record component.

Here are the create request and the product response records, with @Schema next to the validation annotations.

Example 5 · CreateProductRequest.java and ProductResponse.java with @Schema

Runs in: the shoplite-api Spring Boot project

CreateProductRequest.javaJava
// src/main/java/com/shoplite/product/CreateProductRequest.javapackage com.shoplite.product;
import java.math.BigDecimal;
import io.swagger.v3.oas.annotations.media.Schema;import jakarta.validation.constraints.DecimalMax;import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Digits;import jakarta.validation.constraints.NotBlank;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.PositiveOrZero;import jakarta.validation.constraints.Size;
/** Body of POST /api/v1/products. stock and isActive are optional (defaults 0 and true). */@Schema(description = "A new product")public record CreateProductRequest(        @Schema(description = "Unique code: 3-20 characters, A-Z, 0-9 or -", example = "ACC-KB100")        @NotBlank(message = "must not be blank")        @Sku        String sku,
        @Schema(example = "Zebronics Wireless Keyboard")        @NotBlank(message = "must not be blank")        @Size(min = 2, max = 120, message = "must be 2-120 characters")        String name,
        @Schema(description = "Id of an existing category", example = "4")        @NotNull(message = "must not be null")        Long categoryId,
        @Schema(description = "Price in rupees, at most two decimals", example = "999.00")        @NotNull(message = "must not be null")        @DecimalMin(value = "0.00", inclusive = false, message = "must be greater than 0")        @DecimalMax(value = "99999999.99", message = "must be at most 99999999.99")        @Digits(integer = 8, fraction = 2, message = "must have at most 2 decimals")        BigDecimal price,
        @Schema(description = "Units in stock; 0 when left out", example = "30", defaultValue = "0")        @PositiveOrZero(message = "must be 0 or more")        Integer stock,
        @Schema(description = "true when left out", example = "true", defaultValue = "true")        Boolean isActive) {}
// src/main/java/com/shoplite/product/ProductResponse.javapackage com.shoplite.product;
import java.math.BigDecimal;
import io.swagger.v3.oas.annotations.media.Schema;
/** The product JSON from the API contract. */@Schema(description = "A product in the catalogue")public record ProductResponse(        @Schema(description = "Server-generated id", example = "1")        Long id,
        @Schema(description = "Stock keeping unit, unique", example = "MOB-RN13")        String sku,
        @Schema(example = "Redmi Note 13 5G")        String name,
        @Schema(example = "2")        Long categoryId,
        @Schema(description = "Name of the product's category", example = "Mobiles")        String categoryName,
        @Schema(description = "Price in rupees, two decimals", example = "17999.00")        BigDecimal price,
        @Schema(description = "Units in stock", example = "40")        int stock,
        @Schema(description = "false: hidden from normal searches", example = "true")        boolean isActive) {}
Sample output
$ curl http://localhost:8080/v3/api-docs        (formatted and trimmed)
{
  "components": {
    "schemas": {
      "CreateProductRequest": {
        "type": "object",
        "description": "A new product",
        "properties": {
          "sku": {
            "type": "string",
            "description": "Unique code: 3-20 characters, A-Z, 0-9 or -",
            "example": "ACC-KB100",
            "minLength": 1,
            "pattern": "^[A-Z0-9-]{3,20}$"
          },
          "name": {
            "type": "string",
            "example": "Zebronics Wireless Keyboard",
            "maxLength": 120,
            "minLength": 2
          },
          "categoryId": {
            "type": "integer",
            "format": "int64",
            "description": "Id of an existing category",
            "example": 4
          },
          "price": {
            "type": "number",
            "description": "Price in rupees, at most two decimals",
            "example": 999.0,
            "exclusiveMinimum": 0.00,
            "maximum": 99999999.99
          },
          "stock": {
            "type": "integer",
            "format": "int32",
            "default": 0,
            "description": "Units in stock; 0 when left out",
            "example": 30,
            "minimum": 0
          },
          "isActive": {
            "type": "boolean",
            "default": true,
            "description": "true when left out",
            "example": true
          }
        },
        "required": [
          "categoryId",
          "name",
          "price",
          "sku"
        ]
      },
      ...
    }
  }
}

Swagger UI, POST /api/v1/products, Request body, Example Value:
{
  "sku": "ACC-KB100",
  "name": "Zebronics Wireless Keyboard",
  "categoryId": 4,
  "price": 999,
  "stock": 0,
  "isActive": true
}

What this code does

  • Each @Schema adds a description and an example; the record-level @Schema describes the whole body ("A new product").
  • The Example Value Swagger UI builds is now a working request. stock shows 0, the defaultValue, not the example 30; price shows 999, because a JSON number has no trailing zeros.
  • The rules (minLength, pattern, exclusiveMinimum, required) were already there: they come from the validation annotations, as Example 6 shows.

Examples make Swagger UI useful. Without them, the Example Value is "sku": "string", "categoryId": 0, which fails validation the moment someone presses Execute. With them, a tester presses Execute on a body that works.

Two things to know. Swagger UI prefers defaultValue over example when it builds the example body, so stock shows 0 here, not 30. And an example number loses trailing zeros: "999.00" becomes 999.0 in the spec and 999 on the page. JSON treats them as the same number; the description states the two-decimal rule.

Bean Validation constraints showing up in the docs automatically

Bean Validation is the set of annotations, such as @NotBlank, @Size and @DecimalMin, that declare rules on a field. springdoc reads them and writes the matching rules into the schema on its own.

This record has only validation annotations and no @Schema. springdoc still shows the rules.

Example 6 · Validation annotations only: what springdoc reads without any @Schema

Runs in: the shoplite-api Spring Boot project

CreateProductRequest.javaJava
// src/main/java/com/shoplite/product/CreateProductRequest.java (from the Validation module, no @Schema yet)public record CreateProductRequest(        @NotBlank(message = "must not be blank")        @Sku        String sku,
        @NotBlank(message = "must not be blank")        @Size(min = 2, max = 120, message = "must be 2-120 characters")        String name,
        @NotNull(message = "must not be null")        Long categoryId,
        @NotNull(message = "must not be null")        @DecimalMin(value = "0.00", inclusive = false, message = "must be greater than 0")        @DecimalMax(value = "99999999.99", message = "must be at most 99999999.99")        @Digits(integer = 8, fraction = 2, message = "must have at most 2 decimals")        BigDecimal price,
        @PositiveOrZero(message = "must be 0 or more")        Integer stock,
        Boolean isActive) {}
// src/main/java/com/shoplite/product/Sku.java (the custom constraint, shortened)@Pattern(regexp = "^[A-Z0-9-]{3,20}$")@ReportAsSingleViolation@Constraint(validatedBy = {})public @interface Sku { ... }
Sample output (before any @Schema was added)
$ curl http://localhost:8080/v3/api-docs.yaml        (trimmed)
...
components:
  schemas:
    CreateProductRequest:
      type: object
      properties:
        sku:
          type: string
          minLength: 1
          pattern: "^[A-Z0-9-]{3,20}$"
        name:
          type: string
          maxLength: 120
          minLength: 2
        categoryId:
          type: integer
          format: int64
        price:
          type: number
          exclusiveMinimum: 0.00
          maximum: 99999999.99
        stock:
          type: integer
          format: int32
          minimum: 0
        isActive:
          type: boolean
      required:
      - categoryId
      - name
      - price
      - sku
    ...

What this code does

  • required lists exactly the @NotNull and @NotBlank fields; stock and isActive are optional, as the contract says for POST.
  • @Size gave minLength/maxLength, @NotBlank gave minLength: 1, @DecimalMin(inclusive = false) gave exclusiveMinimum: 0.00, and the custom @Sku gave its pattern.
  • @Digits(integer = 8, fraction = 2) left no trace: OpenAPI has no "at most two decimals" rule, so Example 5 says it in the description.

@NotNull and @NotBlank put the field in required, @Size becomes minLength and maxLength, @Pattern becomes pattern, @DecimalMin(inclusive = false) becomes exclusiveMinimum, @DecimalMax becomes maximum and @PositiveOrZero becomes minimum: 0. The custom @Sku showed its pattern too, because it is built from @Pattern. So the rule is written once, in the record, and both the server and the docs follow it; Swagger UI shows it in the Schema tab, such as [2, 120] characters.

Some rules have no OpenAPI word: @Digits(fraction = 2) (at most two decimals) and business rules such as "the category must exist" or "SKU must be unique". Put those in @Schema(description = ...) and in the @Operation description.

Next step

Check your understanding

12 quick questions