Building REST APIs in Java is easier than ever thanks to Spring Boot. But building APIs is only half of the work—documenting them is equally essential. This is where OpenAPI (formerly Swagger) becomes a critical tool. It provides a standardized way to describe REST endpoints, request/response models, authentication, and more.
In this tutorial, we will cover everything you need to know to use OpenAPI with Spring Boot, including:
- What OpenAPI is
- How to add it to a Spring Boot project
- How to generate automatic API documentation
- How to customize metadata and schemas
- How to document models and parameters
- How to expose Swagger UI
- Useful annotations with examples
- Generating client code from OpenAPI specs
This article uses OpenAPI 3 and Springdoc, the modern implementation for Spring Boot.
What Is OpenAPI?
OpenAPI is a specification to describe RESTful APIs in a structured format (JSON or YAML). Tools like Swagger UI, ReDoc, and automatic client generators rely on it to produce:
- Interactive API documentation
- API validation
- Mock servers
- Client SDKs (Java, JS, Python, Go, etc.)
- Server stubs
In Java, the most popular tool for generating OpenAPI specs automatically is:
Springdoc OpenAPI
This library integrates seamlessly with Spring Boot and scans your code to produce an OpenAPI document automatically.
Setup: Adding Springdoc to Your Spring Boot App
Add the Springdoc dependency to pom.xml:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version>
</dependency>
For Spring WebFlux projects:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
<version>2.6.0</version>
</dependency>
Run your Spring Boot application and navigate to:
http://localhost:8080/swagger-ui.htmlYou should now see a full interactive API documentation UI.
Basic Controller Example
Let’s build a simple REST controller and see how Springdoc generates documentation automatically.
BookController.java
@RestController
@RequestMapping("/api/books")
public class BookController {
private final Map<Integer, Book> books = new HashMap<>();
@GetMapping
public List<Book> getBooks() {
return new ArrayList<>(books.values());
}
@GetMapping("/{id}")
public Book getBook(@PathVariable int id) {
return books.get(id);
}
@PostMapping
public Book createBook(@RequestBody Book book) {
book.setId(books.size() + 1);
books.put(book.getId(), book);
return book;
}
}
Book.java model
public class Book {
private int id;
private String title;
private String author;
// getters & setters
}
Springdoc detects:
- endpoints
- request parameters
- request bodies
- response types
And generates the full OpenAPI spec.
Customizing OpenAPI Metadata
Create a config class to set metadata like title, version, and description.
OpenAPIConfig.java
@Configuration
public class OpenAPIConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("Book API")
.version("1.0.0")
.description("A simple example API for managing books")
.contact(new Contact()
.name("API Support")
.email("<a href="mailto:support@example.com" target="_blank" rel="noreferrer noopener">support@example.com</a>")
)
);
}
}
This metadata will appear automatically in Swagger UI.
Using OpenAPI Annotations
Springdoc supports OpenAPI 3 annotations, allowing deeper customization.
Documenting Operations
@Operation
@Operation(
summary = "Get a book by ID",
description = "Returns a single book object"
)
@GetMapping("/{id}")
public Book getBook(@PathVariable int id) {
return books.get(id);
}
Documenting Parameters
@Parameter
@GetMapping("/{id}")
@Operation(summary = "Get a book by ID")
public Book getBook(
@Parameter(description = "ID of the book")
@PathVariable int id
) {
return books.get(id);
}
Describing Response Codes
@ApiResponse
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Success"),
@ApiResponse(responseCode = "404", description = "Book not found")
})
Full example:
@GetMapping("/{id}")
@Operation(summary = "Get a book by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Book found"),
@ApiResponse(responseCode = "404", description = "Book not found")
})
public ResponseEntity<Book> getBook(@PathVariable int id) {
Book book = books.get(id);
return book != null ? ResponseEntity.ok(book) : ResponseEntity.notFound().build();
}
Documenting Models
Using @Schema annotation.
Book.java
@Schema(description = "Book entity")
public class Book {
@Schema(description = "Unique identifier", example = "1")
private int id;
@Schema(description = "Book title", example = "The Hobbit")
private String title;
@Schema(description = "Author name", example = "J.R.R. Tolkien")
private String author;
// Getters & Setters
}
Swagger UI will now show clear model information.
Documenting Authentication (JWT Example)
In OpenAPI, security schemes must be declared.
Update OpenAPIConfig.java
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.components(new Components().addSecuritySchemes("bearerAuth",
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
))
.addSecurityItem(new SecurityRequirement().addList("bearerAuth"))
.info(new Info().title("Book API with JWT"));
}
Swagger UI now shows an “Authorize” button.
Example With POST Body Documentation
@PostMapping
@Operation(summary = "Create a new book")
@ApiResponses({
@ApiResponse(responseCode = "201", description = "Book created")
})
public ResponseEntity<Book> createBook(
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "Book to be created"
)
@RequestBody Book book) {
book.setId(books.size() + 1);
books.put(book.getId(), book);
return ResponseEntity.status(HttpStatus.CREATED).body(book);
}
Exporting OpenAPI Specification
Springdoc exposes the spec automatically:
YAML
http://localhost:8080/v3/api-docs.yamlJSON
http://localhost:8080/v3/api-docs
You can use this file for:
- API versioning
- Mock servers
- Code generation
- Contract-first development
Generating Client SDKs
(OpenAPI → Java / TypeScript / Python)
You can generate API clients using:
- OpenAPI Generator
- Swagger Codegen
Example (TypeScript client):
openapi-generator-cli generate \
-i http://localhost:8080/v3/api-docs.yaml \
-g typescript-fetch \
-o ./client-sdkConclusion
OpenAPI + Spring Boot is one of the most powerful combinations for building and documenting REST APIs. With Springdoc, you get:
- Automatic OpenAPI generation
- Interactive Swagger UI
- Easy annotations for customization
- Clean, professional API documentation
- Simple integration with JWT and request/response models
- Ability to generate client SDKs instantly
This tutorial covered:
- Setting up OpenAPI with Spring Boot
- Customizing metadata
- Using annotations (
@Operation,@ApiResponse,@Schema, etc.) - Documenting models, parameters, and security
- Exporting OpenAPI docs
- Generating client SDKs
