Sub topic 3
Documenting responses and error payloads
Assume you know Spring MVC controllers, HTTP status codes, Maven, JSON, and basic Bean Validation. springdoc-openapi infers many successful responses, but explicit responses make errors and client behavior clear.
Responses and error payloads
Describe each status code and its response schema. An error payload is a JSON object returned when a request fails.
@Operation(summary = "Get a book")
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "Book found",
content = @Content(schema = @Schema(implementation = Book.class))),
@ApiResponse(
responseCode = "404",
description = "Book does not exist",
content = @Content(schema = @Schema(implementation = ApiError.class)))
})
@GetMapping("/{id}")
public Book getBook(@PathVariable long id) {
return service.findById(id);
}
@Schema(description = "Standard error response")
public record ApiError(
@Schema(example = "BOOK_NOT_FOUND") String code,
@Schema(example = "No book has id 42") String message) {
}Use @Content without a schema when a response has no body, such as a typical 204 No Content response.
Bearer token authentication
Declare a bearer scheme once, then reference it on protected operations. Swagger UI will show an Authorize button and send the token in the Authorization header.
@Configuration
@SecurityScheme(
name = "bearerAuth",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "JWT")
class OpenApiSecurityConfig {
}
@SecurityRequirement(name = "bearerAuth")
@GetMapping("/private")
public Book privateBook() {
return service.getPrivateBook();
}The documentation describes authentication. It does not authenticate requests by itself.
Groups, hiding, and production exposure
Use GroupedOpenApi when public and administrative endpoints need separate documents.
@Bean
GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("public")
.pathsToMatch("/api/**")
.build();
}Use @Hidden on an internal controller or method. Use @Schema(hidden = true) for a model that should not appear in the schema.
@Hidden
@RestController
class InternalHealthController {
}Protect documentation routes with Spring Security, or disable them in production:
springdoc:
api-docs:
enabled: false
swagger-ui:
enabled: falseBuild-time generation and testing
The springdoc-openapi-maven-plugin can fetch the running application’s document during a build. Configure its apiDocsUrl, then inspect the generated JSON in CI.
A test can verify that important paths and responses remain documented:
@SpringBootTest
@AutoConfigureMockMvc
class OpenApiTest {
@Autowired MockMvc mvc;
@Test
void documentsBookLookup() throws Exception {
mvc.perform(get("/v3/api-docs"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.paths['/api/books/{id}']").exists())
.andExpect(jsonPath("$.paths['/api/books/{id}'].get.responses.404").exists());
}
}Exercise
Which annotation hides an internal controller from the generated OpenAPI document?
Show answer
Use @Hidden on the controller or method.