Enhancing API Documentation with OpenAPI 3 and Swagger UI in Spring Boot
Written on
1. Introduction
Effective documentation is vital for REST API development. This guide explores how to utilize Springdoc to automatically generate API documentation based on the OpenAPI 3 specification for applications built with Spring Boot 3.x.
2. Application Setup
Project Technical Stack
Spring Boot 3.3.0
Java 21
Spring Boot 3.X requires a minimum of JDK 17. You can use either JDK 17 or a later version.
3. Integrating springdoc-openapi with Spring Web MVC
To incorporate springdoc-openapi and Swagger UI into our Spring MVC application, include the springdoc-openapi-webmvc-ui dependency in the pom.xml file.
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version>
</dependency>
After adding the dependency and starting the application, the documentation can be accessed in JSON format at:
http://localhost:8080/v3/api-docs
For Open API definitions in YAML format, navigate to:
3.1. Creating the Book API
Let's outline our application controller like this:
@RestController
@RequestMapping("/api/book")
public class BookController {
private final List<Book> bookList = new ArrayList<>();
@PostMapping()
public Book createBook(@RequestBody final Book book) {
bookList.add(book);
return book;
}
@GetMapping
public List<Book> getBooks() {
return bookList;}
@GetMapping("/{id}")
public Book getById(@PathVariable String id) {
return bookList.stream()
.filter(book -> book.getId().equals(id))
.findAny()
.orElseThrow(() -> new RuntimeException("No Book With Given Id"));
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable String id) {
bookList.removeIf(book -> book.getId().equals(id));}
}
We can utilize the @OpenAPIDefinition annotation to provide general application and API-specific information. For detailed guidance on the @OpenAPIDefinition, refer to the official documentation.
@SpringBootApplication
@OpenAPIDefinition(info = @Info(title = "Spring Doc Open API Tutorial", version = "1.0", description = "Spring Doc Open API Tutorial"))
public class OpenApi3Application {
public static void main(String[] args) {
SpringApplication.run(OpenApi3Application.class, args);}
}
3.2. Swagger UI Integration with Web MVC for Book API
The springdoc-openapi dependency includes Swagger UI by default.
The Swagger UI for API documentation can be accessed at:
3.3. Swagger Header Information with OpenAPIDefinition Annotation
3.4. Swagger API Documentation for Book API
4. Setting up springdoc-openapi with Spring WebFlux
The springdoc-openapi library also supports integration with Spring WebFlux applications. To enable this, add the springdoc-openapi-webflux-ui dependency to the pom.xml file.
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
<version>2.6.0</version>
</dependency>
4.1. Defining the Book API in a Reactive Manner
Let's define our application controller in a reactive style:
@RestController
@RequestMapping("/api/reactive-book")
public class ReactiveBookController {
private final List<Book> bookList = new ArrayList<>();
@PostMapping()
public Mono<Book> createBook(@RequestBody final Mono<Book> bookMono) {
return bookMono.map(b -> {
bookList.add(b);
return b;
});
}
}
4.2. Swagger UI Integration with WebFlux for Reactive Book API
The default location for the Swagger UI page for Spring WebFlux applications is:
http://localhost:8080/webjars/swagger-ui/index.html
The springdoc-openapi library allows customization of Swagger UI properties, which can be achieved in Spring Boot applications with the prefix springdoc.swagger-ui.. You can find all available properties in the documentation.
springdoc:
swagger-ui:
path: /swagger-ui.html
enabled: true
4.3. Swagger API Documentation for Reactive Book API
5. Customizing API Documentation with @Schema, @Tag, @Operation, and @APIResponses Annotations
Let’s explore how to enhance our Book API and add descriptions using specific OpenAPI annotations.
We will annotate the BookController class with the @Tag annotation and use @Operation and @ApiResponses annotations on the /api/book POST endpoint.
@RestController
@RequestMapping("/api/book")
@Tag(name = "Book API Service", description = "Operations related to Book API Service")
public class BookController {
private final List<Book> bookList = new ArrayList<>();
@Operation(
description = "Create New Book",
summary = "Create New Book Entry",
requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "Book Record to Add",
required = true,
content = @Content(schema = @Schema(implementation = Book.class)))
)
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Book Record added successfully", content = @Content(schema = @Schema(implementation = Book.class))),
@ApiResponse(responseCode = "400", description = "Invalid Parameters", content = @Content),
@ApiResponse(responseCode = "500", description = "Internal Server error when adding Book Record", content = @Content)
})
@PostMapping()
public Book createBook(@RequestBody final Book book) {
bookList.add(book);
return book;
}
}
5.1. Customization Effect in Swagger UI After Adding @Tag and @Operation Annotations
The Example Value field displaying the endpoint's response has also been updated with actual values, which is expected.
5.2. Customization Effect in Swagger UI After Adding @Schema Annotation for Book Class
Adding an example value for the response or Model class can be achieved with the @Schema annotation in the response object:
@Data
public class Book {
@Schema(example = "1", description = "Id of the Book")
private String id;
@Schema(example = "Mathematics", description = "Name of the Book")
private String name;
}
5.3. Customization Effect in Swagger UI After Adding @ApiResponses Annotation
6. Summary
In this guide, we explored how to set up springdoc-openapi and integrate it with Swagger UI for both Spring WebMVC and WebFlux applications.
Additionally, we learned how to customize and enrich API documentation using specific OpenAPI annotations.
Thank You for Reading
- Feel free to provide your feedback.
- Stay tuned for more informative content.