Reputation: 21
Hi I would like to define own responses like possible error responses and also defining the default response incase I build my responses by my self like return Response.status(OK).entity(new MyResponseObject())
Something like this: https://swagger.io/docs/specification/describing-responses/
How can I do it?
Upvotes: 2
Views: 2213
Reputation: 3378
You can use io.quarkus:quarkus-smallrye-openapi
extension to add necessary annotations to your project. You can do it by adding dependency in Maven or Gradle.
For Gradle:
implementation("io.quarkus:quarkus-smallrye-openapi")
For Maven:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-openapi</artifactId>
</dependency>
By default SmallRye OpenAPI extension will check what type method return and it will use it in generated documentation. In your example it will be probably Response
which will be converted just to empty JSON object.
You can change your code to just return MyResponseObject object from method like this:
@GET
@Path("/")
public MyResponseObject someMethod() {
return new MyResponseObject();
}
In this case MyResponseObject will be automatically mapped to OpenAPI schema (all properties will be mapped to JSON object properties).
If you have more than one response e.g. response with object and response with error you can use annotations. SmallRye OpenAPI extension provides two annotations for this:
APIResponse
- for describing single responseAPIResponses
- for describing multiple responses from single methodBoth from org.eclipse.microprofile.openapi.annotations.responses
package.
Here is example with two different response codes:
@APIResponses({
@APIResponse(responseCode = "204", description = "Reservation confirmed"),
@APIResponse(
responseCode = "422",
description = "Reservation can not be confirmed",
content = @Content(mediaType = APPLICATION_JSON,
schema = @Schema(implementation = GlobalError.class))
)
})
public Response confirm(@PathParam("reservationId") long reservationId) {
final var result = reservationService.confirm(reservationId);
if (result.isOK()) {
return Response.status(Response.Status.NO_CONTENT).build();
} else {
return Response.status(422).entity(new GlobalError(result.getError())).build();
}
}
I added two APIResponse
annotations, one for each response code.
First APIResponse is for 204 (reservation confirmed) and nothing is returned that's why content
and schema
is not set for it.
Second APIResponse is for 422 (reservation can not be confirmed). In this annotation I set custom schema with my class, which is returned when user got 422 from API. You can also add description, which will added to your API documentation and displayed in Swagger.
Upvotes: 1