Sub topic 10
Documenting responses and error payloads
A client of your API needs to know two things about each endpoint: what a successful call returns, and what the failures look like. springdoc-openapi infers the success case from your code. Error cases need more help. This chapter shows what is inferred, how to describe the rest with @ApiResponse, how to document a shared error body, and how to apply common responses to every operation.
This chapter assumes you have a working springdoc setup, a controller annotated with @Operation, and a model annotated with @Schema. It also assumes you know @RestControllerAdvice and @ExceptionHandler from Spring MVC.
What springdoc infers on its own
For each handler method, springdoc builds a response entry from the code:
- The return type becomes the schema of the success response.
- The status code is
200unless the method has@ResponseStatus. For example,@ResponseStatus(HttpStatus.CREATED)produces201. - A
voidmethod produces a response with no body. @ExceptionHandlermethods in a@RestControllerAdvicethat carry@ResponseStatusare added as responses on the operations, with the handler's return type as the body schema.
That last point is useful, but it has limits. The status is only inferred from @ResponseStatus. If your handler returns ResponseEntity<ApiError> and chooses the status at runtime, springdoc cannot know it, so you must document it yourself. Inference also cannot know which operations can really throw which exception. It attaches advice responses broadly.
The diagram shows how the final response list for one operation is assembled.
Defining a shared error payload
Use one error shape across the API and give it its own schema. Here it is as a record, with the same @Schema approach you used for request models.
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "Error returned for any failed request")
public record ApiError(
@Schema(description = "HTTP status code", example = "404")
int status,
@Schema(description = "Short name of the error", example = "Not Found")
String error,
@Schema(description = "Explanation for the client", example = "Book 42 does not exist")
String message) {
}Next, the exception and the advice class that maps it to a response.
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(long id) {
super("Book " + id + " does not exist");
}
}import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiError handleNotFound(BookNotFoundException ex) {
return new ApiError(404, "Not Found", ex.getMessage());
}
}With this in place, the generated document already lists a 404 response whose body references the ApiError schema. You wrote no OpenAPI annotation for it.
If you use Spring's built-in ProblemDetail (RFC 7807 style) instead of a custom type, springdoc can describe it in the same way. Return ProblemDetail from the handler and the schema is generated from that class.
Declaring responses explicitly with @ApiResponse
Explicit annotations give you control over descriptions, media types, examples and headers. Put @ApiResponses (or a single @ApiResponse) on the handler method.
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.net.URI;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/books")
@Tag(name = "Books", description = "Operations on the book catalog")
public class BookCreateController {
private final BookService service;
public BookCreateController(BookService service) {
this.service = service;
}
@Operation(summary = "Create a book")
@ApiResponses({
@ApiResponse(
responseCode = "201",
description = "Book created",
headers = @Header(
name = "Location",
description = "URL of the new book",
schema = @Schema(type = "string", example = "/api/books/43")),
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = Book.class))),
@ApiResponse(
responseCode = "400",
description = "Validation failed",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = ApiError.class),
examples = @ExampleObject(
name = "blankTitle",
value = "{\"status\":400,\"error\":\"Bad Request\",\"message\":\"title must not be blank\"}")))
})
@PostMapping
public ResponseEntity<Book> create(@Valid @RequestBody Book book) {
Book saved = service.save(book);
return ResponseEntity.created(URI.create("/api/books/" + saved.id())).body(saved);
}
}BookService is the same service used by the earlier controller examples. Its save method returns the stored Book with an id.
Several attributes of @ApiResponse matter in practice:
| Attribute | Purpose |
|---|---|
| `responseCode` | The status code as a string, or `"default"` for any code not listed |
| `description` | Required by the OpenAPI specification, so always set it |
| `content` | Body description: media type, schema and examples |
| `headers` | Response headers such as `Location` or rate-limit headers |
An @ApiResponse without content does not say the body is empty. It leaves the inferred body in place. To state explicitly that a response has no body, use content = @Content, as the 404 in the earlier BookController example does.
Why the explicit schema matters for ResponseEntity
The return type ResponseEntity<?>, or a method that returns a raw Object, gives springdoc nothing to infer. The result is a response with no useful schema. Whenever you use those types, put @Schema(implementation = ...) inside @Content.
Lists
A method returning List<Book> is inferred as an array of Book. If you override content, state the array yourself with @ArraySchema:
import io.swagger.v3.oas.annotations.media.ArraySchema;
@ApiResponse(
responseCode = "200",
description = "All books",
content = @Content(
mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = Book.class))))Applying responses to every operation
Repeating a 401 or 500 response on every method is noisy. There are two levels to avoid it.
On a controller class, @ApiResponse is repeatable and applies to each operation in that class:
@RestController
@RequestMapping("/api/authors")
@ApiResponse(responseCode = "401", description = "Missing or invalid token", content = @Content)
public class AuthorController {
// every operation here documents a 401
}For the whole API, register an OpenApiCustomizer bean. It receives the finished document and can change it.
import io.swagger.v3.oas.models.responses.ApiResponse;
import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiResponsesConfig {
@Bean
public OpenApiCustomizer serverErrorCustomizer() {
return openApi -> openApi.getPaths().values().forEach(pathItem ->
pathItem.readOperations().forEach(operation ->
operation.getResponses().putIfAbsent(
"500",
new ApiResponse().description("Unexpected server error"))));
}
}putIfAbsent keeps any 500 you documented on a specific operation. Note that this ApiResponse is the model class from io.swagger.v3.oas.models, not the annotation of the same name.
Common mistakes
- Documenting what the code does not do. An
@ApiResponsefor404on an endpoint that never returns one misleads clients. The annotation is not checked against behavior, so review it with the code. - Missing
description. The specification requires it. Some validators reject documents without it. - Status mismatch. If the method returns
201throughResponseEntitybut the annotation says200, the document shows both or the wrong one. Keep them in step. - Handlers without
@ResponseStatus. The status is not inferred, so the error is missing from the document unless you add@ApiResponseannotations.
Exercise
A handler method in your @RestControllerAdvice returns ResponseEntity<ApiError> and picks the status code at runtime. The 404 response is missing from the generated document. Why, and what are two ways to fix it?
Show answer
springdoc infers the status of an exception handler only from @ResponseStatus, and a runtime choice inside ResponseEntity is invisible to it. Fix it either by adding @ResponseStatus to the handler (if the status is fixed), or by declaring @ApiResponse(responseCode = "404", description = "...", content = @Content(schema = @Schema(implementation = ApiError.class))) on the handler or on the controller methods or class that can produce it.
Exercise
Write the annotation that documents a 204 response with no body on a delete operation, and explain how it differs from an @ApiResponse that has only responseCode and description.
Show answer
@ApiResponse(responseCode = "204", description = "Book deleted", content = @Content). The empty @Content states that the response has no body. Without it, springdoc may keep an inferred body from the method's return type, so the document could describe a body that is never sent.