-
-
Notifications
You must be signed in to change notification settings - Fork 545
Globally set the response content schema for specific status codes #2880
-
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?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 1 reply
-
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?
Beta Was this translation helpful? Give feedback.
All reactions
-
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.
Beta Was this translation helpful? Give feedback.