Sub topic 1
What OpenAPI describes and why generate it from code
Prerequisites
This chapter assumes you can already:
- Build REST controllers with Spring Boot (
@RestController,@GetMapping,@RequestBody). - Add a dependency in Maven or Gradle.
- Read JSON and recognize common HTTP status codes such as 200, 400 and 404.
- Use basic Bean Validation annotations such as
@NotBlank.
No springdoc code is written yet. This chapter explains what the library produces and why. Later chapters add the dependency and the annotations.
What an OpenAPI document is
The OpenAPI Specification (OAS) is a standard format for describing an HTTP API. The description is a single document, written in JSON or YAML, that a person or a program can read. It lists:
- Servers: the base URLs where the API runs.
- Paths and operations: each URL template, such as
/api/books/{id}, with the HTTP methods it accepts. - Parameters: path, query, header and cookie inputs, with types and whether they are required.
- Request bodies and responses: the media types, the status codes, and the shape of each payload.
- Schemas: reusable definitions of the JSON objects that appear in bodies.
- Security schemes: how a client authenticates, for example an HTTP bearer token.
- Metadata: title, version, description and tags used to group operations.
The document describes the contract of the API. It does not contain the implementation. A client developer can read it to learn what to send and what to expect. Tools can read it too, for example to build a documentation page, generate a client library, or run contract tests.
A small example
Suppose a controller exposes GET /api/books/{id}. A trimmed OpenAPI 3 document for that endpoint looks like this:
{
"openapi": "3.0.1",
"info": { "title": "Library API", "version": "1.0.0" },
"paths": {
"/api/books/{id}": {
"get": {
"tags": ["Books"],
"operationId": "getBook",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": { "type": "integer", "format": "int64" }
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/Book" }
}
}
}
}
}
}
},
"components": {
"schemas": {
"Book": {
"type": "object",
"properties": {
"id": { "type": "integer", "format": "int64" },
"title": { "type": "string" },
"author": { "type": "string" }
}
}
}
}
}Three structural points matter for the rest of the tutorial:
- Operations live under
paths, keyed by URL template and then by lowercase HTTP method. - Reusable object shapes live under
components.schemas. Operations refer to them with$ref, soBookis defined once and reused. - The
infield of a parameter says where the value travels:path,query,headerorcookie.
OpenAPI, Swagger and springdoc
These names are often mixed up.
| Name | What it is |
|---|---|
| OpenAPI Specification | The standard format for describing an HTTP API. |
| Swagger | The original name of the specification, and now the brand for a set of tools around it. |
| Swagger UI | A web page that renders an OpenAPI document and lets you send requests from the browser. |
| Swagger annotations | Java annotations such as `@Operation` and `@Schema` that add detail to generated output. |
| springdoc-openapi | A library that inspects a running Spring application and produces an OpenAPI document and a Swagger UI page. |
"Swagger 2" refers to the older specification version. Spring Boot 3 projects use OpenAPI 3.x, and springdoc 2.x generates version 3.0.1 by default. Springdoc 2.2 and later can emit 3.1 if you opt in with a property. Pick one version and stay on it, because some client generators do not yet handle 3.1.
Why generate the document from code
There are two ways to get an OpenAPI document.
- Design-first: write the YAML by hand before the code, then implement it.
- Code-first: write the controllers, then derive the document from them.
This tutorial uses code-first. The reasons are practical:
- The document cannot drift easily. A hand-written file is a second copy of the contract. When someone adds a query parameter to a controller and forgets the file, the docs are wrong. A generated document is built from the running code each time.
- Spring already knows most of the answer. Mappings, HTTP methods, path variables, request body types and return types are all present in the controller signatures. Springdoc reads them and fills in the operations.
- Bean Validation constraints carry over. Constraints such as
@NotBlankand@Size(max = 200)become schema rules without extra work. - The starting cost is low. One dependency gives you a working document and a browsable page before you write a single annotation.
Code-first has real costs, and you should weigh them:
- The code becomes the source of truth, so a refactor that changes a response type silently changes the public contract. Review the generated document in code review, and test it (a later chapter covers this).
- Reflection cannot see everything. A method that returns
ResponseEntity<?>, or a controller that throws a custom exception handled elsewhere, produces vague or incomplete output until you add annotations. - Prose quality is your job. Descriptions, examples and error explanations do not exist in the code, so you add them with annotations.
- If several teams must agree on a contract before anyone writes code, design-first fits better. You can still use springdoc then, to check that the implementation matches.
How springdoc builds the document
At application startup and on request, springdoc scans the Spring MVC handler mappings. For each mapped method it reads the signature, then merges in any Swagger annotations and configuration properties. The result is serialized and served over HTTP.
Here is a controller with no documentation annotations at all:
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/books")
public class BookController {
public record Book(Long id, String title, String author) {
}
private final Map<Long, Book> books =
Map.of(42L, new Book(42L, "Dune", "Frank Herbert"));
@GetMapping("/{id}")
public ResponseEntity<Book> getBook(@PathVariable long id) {
Book book = books.get(id);
return book == null
? ResponseEntity.notFound().build()
: ResponseEntity.ok(book);
}
}From this code alone, springdoc can infer:
- The path
/api/books/{id}and thegetmethod. - A required
pathparameter namedidof typeintegerwith formatint64. - A
200response whose body is aBookwithid,titleandauthorproperties.
It cannot infer that the endpoint returns 404, because ResponseEntity.notFound() is a runtime decision rather than a type. It also cannot infer that 42 is a sensible example, or that the title is limited to 200 characters. Those details need annotations, which the later chapters add.
Common errors in the mental model
- Treating the generated document as complete. It describes what the code reveals. Error responses, examples and business rules are often missing until you add them.
- Documenting endpoints that are not meant to be public. Everything mapped by Spring MVC is a candidate. Actuator and internal endpoints may appear unless you restrict scanning.
- Confusing the document with the UI. The JSON document is the product. Swagger UI is only one consumer of it. If you turn the UI off, the JSON can still be served, and the reverse is not possible.
- Mixing library generations. The starter for Spring Boot 3 is springdoc 2.x. The 1.x line targets Spring Boot 2 and uses different artifact names, so tutorials written for it will not match.
What comes next
The next chapter adds the starter dependency and shows the two default endpoints. The chapters after it improve the output step by step: metadata, operations, schemas, parameters, responses, security, grouping and hiding. The last chapters cover production exposure, build-time generation and testing.
Exercise
A controller method is declared as public ResponseEntity<Book> getBook(@PathVariable long id) and returns ResponseEntity.notFound().build() when the book is missing. A generated OpenAPI document lists only a 200 response for it. Why is the 404 missing, and what does this tell you about code-first generation?
Show answer
Springdoc reads method signatures, and the 404 is chosen at runtime inside the method body, so it is not visible in the signature. Code-first generation documents what the code structure reveals. Behavior such as extra status codes has to be added explicitly with annotations like @ApiResponse, and the generated output should be reviewed for gaps like this.
Exercise
Name two situations where a design-first approach is a better fit than a code-first one.
Show answer
Examples: several teams must agree on a contract before implementation starts, so the YAML is the shared artifact. Or an API is public and stable, and changes to the contract must be a deliberate decision rather than a side effect of refactoring a controller.