I'm struggling on how to reuse an @Header annotation within my API specification using Quarkus and Eclipse Microprofile. I have a lot of methods which return a paginated list of objects and I want to deliver the information about the
- total amount of objects existing
- current offset
- current limit
as X-... Header, this currently looks like
@GET
@Path("/obj1")
@Operation(description = "get filtered list of obj1")
@APIResponse(
responseCode = "200",
headers = { @Header(name = "X-Length"),@Header(name = "X-Offset") ,@Header(name = "X-Limit")},
content = @Content(
mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation = Obj1.class, type = SchemaType.ARRAY)
)
)
Since the headers are always the same for every method returning a list, I don't want to copy & paste them on every method, since I'm also currently not sure about the naming.
Is it possible, and if so how, to declare this array once and reuse it like
paginationHeaders = { @Header(name = "X-Length"),@Header(name = "X-Offset") ,@Header(name = "X-Limit")}
...
@APIResponse(...
headers = paginationHeaders
Is there maybe another standardized way to return pagination information (but not in the response object) using Quarkus?
I tried searching via Google, browsing the Quarkus docs and defining a custom annotation.
At first I'd like to mention that passing pagination information to HTTP headers is not the best idea. For example firewalls or proxy servers can modify (even remove) HTTP headers. I'm going to show my preferred solution later.
Add pagination headers to response
However, reusing header constants is not fully supported neither OpenAPI nor Quarkus the MicroProfile OpenAPI Specification (and Smallrye OpenAPI implementation) supports to modify OpenAPI documentation programatically.
A REST resource
The
listExamples
operation has possible two responses, but the only one should contain pagination response headers. I've introduced a meta headerX-Paginated
to mark which response has to be modified.By implementing a custom OpenAPI filter it is possible to change OpenAPI definition programatically.
The following filter will change each occurrence of
X-Paginated
header toX-Length
,X-Offset
andX-Limit
triple.Note: Don't forget to register custom OASFilter(s) in application configuration file e.g.:
Add pagination properties to response
As I started I prefer to pass pagination properties in response body. Luckily it can be reusable, because Smallrye supports generic response types.
Pagination
holds the pagination propertiesFilterResult
contains the result list along with paginationNow, an enpoint like
will be generated in OpenAPI documentation as: