API documentation with OpenAPI
Generate interactive API docs.
By Invicly Tech, , in Backend Java Development. About 9 minutes to read.
In short
OpenAPI is a standard description of a REST API. springdoc-openapi generates it from your controllers, and Swagger UI turns it into interactive docs where you can try calls.
Explained simply
When another team, a mobile developer or your future self wants to use your API, they need to know the URLs, the fields to send, and what comes back. OpenAPI is a standard file format, in JSON or YAML, that describes exactly that. Many tools understand it.
Writing that file by hand is slow and it quickly goes out of date. springdoc-openapi reads your Spring controllers while the app runs and builds the file for you. Add one dependency, start the app, and the description is live at /v3/api-docs.
Swagger UI turns that file into a web page. Every endpoint is listed with its parameters and example bodies, and a Try it out button sends a real request from the browser. It is often the fastest way for someone new to understand and test your API.
You can add detail with annotations: a summary for each endpoint, a list of possible error codes, and descriptions or examples for fields. The better the description, the more useful it is for people and for tools that generate client code in other languages.
Press Play on a diagram to walk through it one step at a time.
- 1Add springdoc starter
springdoc-openapi-starter-webmvc-ui dependency
- 2App scans controllers
Reads mappings, parameters and DTO fields
- 3Spec at /v3/api-docs
Machine-readable OpenAPI JSON
- 4Swagger UI page
Browse and try endpoints at /swagger-ui.html
- 5Clients generated
Optional: generate typed clients from the spec
- info
- title
- version
- description
- servers
- Base URLs, such as https://api.example.com
- paths
- /books: get, post
- Parameters
- Responses by status code
- components
- schemas (DTOs)
- securitySchemes (bearer JWT)
- security
- Which scheme applies by default
- Swagger UI to Spring API: GET /v3/api-docs1GET /v3/api-docs
- Spring API to Swagger UI: Spec with bearer security scheme2Spec with bearer security scheme
- Developer to Swagger UI: Authorize: paste JWT3Authorize: paste JWT
- Developer to Swagger UI: Try it out on GET /api/books/74Try it out on GET /api/books/7
- Swagger UI to Spring API: GET /api/books/7 with Bearer token5GET /api/books/7 with Bearer token
- Spring API to Swagger UI: 200 OK with JSON body6200 OK with JSON body
In depth
Picking the right springdoc artifact and version
springdoc ships separate starters. springdoc-openapi-starter-webmvc-ui is for normal Spring MVC apps and includes Swagger UI. springdoc-openapi-starter-webflux-ui is the reactive version. The -api variants (webmvc-api, webflux-api) generate only the spec, without the UI, which suits production builds where you do not want a docs page.
Versions follow Spring Boot: springdoc 1.x was for Boot 2 and is no longer maintained, 2.x is for Boot 3, and 3.x targets Boot 4. Mixing the wrong major versions is the most common reason the docs page shows a white screen or the app fails to start. Do not also add the old springfox library; it is unmaintained and conflicts with springdoc.
- Spec as JSON: /v3/api-docs; as YAML: /v3/api-docs.yaml
- UI: /swagger-ui.html redirects to /swagger-ui/index.html
- springdoc.swagger-ui.enabled=false turns off only the UI
- springdoc.api-docs.enabled=false turns off the spec too
What springdoc infers without any annotations
springdoc inspects each handler method. From @GetMapping, @PostMapping and friends it builds paths and HTTP methods. @PathVariable and @RequestParam become parameters, with required set from the annotation. The @RequestBody type and the return type become schemas under components, built by reading the class fields through Jackson, so @JsonProperty names and @JsonIgnore are respected.
Bean Validation annotations are translated as well: @NotNull and @NotBlank mark a field required, @Size becomes minLength and maxLength, @Min and @Max become minimum and maximum, and @Pattern becomes a regex pattern. Java records work the same as classes. What it cannot infer is meaning: why an endpoint exists, which error codes it returns, and what a field like status really holds. That is where annotations help.
- 1Mapping annotation
@PostMapping("/books") gives path and method
- 2Parameters
@PathVariable and @RequestParam become parameters
- 3Request body
DTO fields become a schema in components
- 4Validation rules
@Size, @NotBlank become constraints
- 5Return type
Becomes the 200 response schema
Annotations that make the docs worth reading
These come from the io.swagger.v3.oas.annotations package. @Tag(name = "Books") on a controller groups its endpoints. @Operation(summary = ..., description = ...) explains one endpoint. @ApiResponse(responseCode = "404", description = ...) documents each status code; add content = @Content(schema = @Schema(implementation = ProblemDetail.class)) to show the error body. @Parameter(description = ..., example = ...) explains a path or query parameter.
On DTOs, @Schema(description = ..., example = "Clean Code") adds help text and sample values, and accessMode = Schema.AccessMode.READ_ONLY marks fields like id that the server sets. @Hidden removes an endpoint or controller from the docs completely. Global information such as the title, version, contact and security schemes goes in a single OpenAPI bean rather than on every controller.
- Document the error format once, for example RFC 9457 ProblemDetail
- Real examples beat long descriptions
- Use @Hidden for internal or admin-only endpoints
Code-first, design-first and the spec in CI
Generating the spec from code is called code-first: the code is the source of truth and the docs can never drift. Design-first is the opposite: teams agree on an openapi.yaml before coding, often to let the frontend start early, then generate server interfaces from it with openapi-generator.
Either way, treat the spec as an artifact. A useful CI step starts the app, downloads /v3/api-docs, and saves it, or uses the springdoc-openapi Maven or Gradle plugin to do that during the build. With the file checked in, a pull request shows every API change as a diff, and a tool such as openapi-diff can fail the build on breaking changes like a removed field. The same file can generate typed clients, for example a TypeScript client for the web app, so field renames show up as compile errors instead of runtime bugs.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Add springdoc-openapi to the project~40m
- 2Annotate endpoints and schemas~40m
- 3Explore the API in Swagger UI~40m
Key points
- springdoc builds the spec automatically; annotations only add detail.
- Use @Operation for summaries and @ApiResponse for documented status codes.
- Validation annotations on DTOs show up as schema constraints.
- Disable or protect Swagger UI in production if the API is private.
Key terms
Tap a card to flip it. 0/4 known
Examples
// pom.xml: org.springdoc:springdoc-openapi-starter-webmvc-ui
@Operation(summary = "Get a book by id")
@ApiResponse(responseCode = "200", description = "Book found")
@ApiResponse(responseCode = "404", description = "No book with that id")
@GetMapping("/{id}")
BookDto get(@PathVariable Long id) {
return service.find(id);
}
// Open http://localhost:8080/swagger-ui.htmlDocumenting a create endpoint fully
POST /api/books returns 201 on success, 400 on invalid input and 409 when the ISBN exists. Step 1: group the controller with @Tag. Step 2: write a one-line summary. Step 3: list each response code, pointing errors at ProblemDetail. Step 4: add examples on the DTO fields. Open Swagger UI: the endpoint now shows sample JSON, field rules from validation, and all three outcomes.
@Tag(name = "Books")
@RestController @RequestMapping("/api/books")
class BookController {
@Operation(summary = "Add a book to the catalogue")
@ApiResponse(responseCode = "201", description = "Book created")
@ApiResponse(responseCode = "400", description = "Invalid input",
content = @Content(schema = @Schema(implementation = ProblemDetail.class)))
@ApiResponse(responseCode = "409", description = "ISBN already exists")
@PostMapping @ResponseStatus(HttpStatus.CREATED)
BookDto create(@Valid @RequestBody CreateBook body) { return service.create(body); }
}
record CreateBook(@Schema(example = "Clean Code") @NotBlank String title,
@Schema(example = "9780132350884") @Size(min = 13, max = 13) String isbn) {}Adding a JWT Authorize button
Your API uses bearer tokens, but Swagger UI calls fail with 401. Step 1: declare a bearer security scheme in an OpenAPI bean. Step 2: apply it globally with a security requirement. Step 3: allow the docs paths through Spring Security. Now Swagger UI shows an Authorize button; paste a token once and every Try it out request sends it.
@Bean
OpenAPI api() {
return new OpenAPI()
.info(new Info().title("Bookings API").version("v1"))
.components(new Components().addSecuritySchemes("bearer",
new SecurityScheme().type(SecurityScheme.Type.HTTP)
.scheme("bearer").bearerFormat("JWT")))
.addSecurityItem(new SecurityRequirement().addList("bearer"));
}
// In the SecurityFilterChain:
// .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()Quick reference
- Dependency for MVC apps: org.springdoc:springdoc-openapi-starter-webmvc-ui
- springdoc 2.x is for Spring Boot 3; 3.x for Boot 4; 1.x for Boot 2 (end of life)
- Spec: /v3/api-docs and /v3/api-docs.yaml; UI: /swagger-ui.html
- @Tag groups endpoints, @Operation describes one, @ApiResponse lists status codes
- @Schema(example = ...) on DTO fields gives realistic sample bodies
- @Hidden removes an endpoint from the generated docs
- springdoc.swagger-ui.enabled=false hides the UI in production
- Permit /v3/api-docs/** and /swagger-ui/** in Spring Security when docs are public
Common mistakes
- Leaving docs describing old behaviour by hand instead of generating them.
- Exposing internal admin endpoints in public docs.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add springdoc to a Spring Boot 3 Maven project and open Swagger UI.
- Exercise 2medium
Document GET /api/books/{id} with a parameter description and a 404 response, and give the id an example value.
- Exercise 3hard
Serve docs in dev and staging, but expose neither the spec nor the UI in production.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between Swagger and OpenAPI?
- OpenAPI is the name of the specification since version 3. Swagger is the older name and now refers to tools around it, like Swagger UI and Swagger Editor.
- Why does Swagger UI show a blank page or 404?
- Usually a springdoc version that does not match your Spring Boot version, or Spring Security blocking /swagger-ui/** and /v3/api-docs/**. Check both first.
- Can I generate a client from my spec?
- Yes. openapi-generator can produce clients for TypeScript, Java, Python, Go and many more languages from the /v3/api-docs file.
- Should production APIs expose Swagger UI?
- Public APIs often do, as developer docs. Private or internal APIs should disable it or put it behind authentication.