Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Globally set the response content schema for specific status codes #2880

Unanswered
jochenberger asked this question in Q&A
Discussion options

We have a lot of methods that return a specific type of object, e.g.

@ApiResponse(
 responseCode = "200",
 description = "Person loaded")
 @ApiResponse(
 responseCode = "404",
 description = "Person not found",
 content =
 @Content(
 mediaType = MediaType.APPLICATION_JSON_VALUE,
 schema = @Schema(implementation = ErrorResponse.class)))
 @GetMapping("/{uuid}")
 public Person getPerson(

Now everywhere I want to document the 404 (or any other error) response, I need to specify the content schema ErrorResponse, or otherwise, Person ends up as the content schema for the 404 response.
Is it possible to define that mapping application-wide so I don't have to repeat it in so many places?

You must be logged in to vote

Replies: 1 comment 1 reply

Comment options

I may just have found a solution myself:

@Bean
 public OperationCustomizer errorResponseSchemas(
 final SpringDocConfigProperties springDocConfigProperties) {
 Schema schema =
 AnnotationsUtils.resolveSchemaFromType(
 ErrorResponse.class, null, null, springDocConfigProperties.isOpenapi31());
 Content content =
 new Content()
 .addMediaType(
 org.springframework.http.MediaType.APPLICATION_JSON_VALUE,
 new MediaType().schema(schema));
 return (operation, handlerMethod) -> {
 operation
 .getResponses()
 .forEach(
 (status, response) -> {
 if (HttpStatus.resolve(Integer.valueOf(status)).is4xxClientError()) {
 response.setContent(content);
 }
 });
 return operation;
 };
 }

Is this how it's supposed to be done? Is this the correct way to get hold of the Schema instance?

You must be logged in to vote
1 reply
Comment options

There are also other ways of realizing it. If you are using a ControllerAdvice then that should be able to lead to response documentation (if your controller advice is configured correctly).

It should also be possible to realize it by for example creating a Controller-interface that all of your controllers implement, and that that interface then is annotated with your @ApiResponse(responseCode = "404", ...) documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /