jax-rs

What is the JAX-RS equivalent of ProducesResponseType?


.Net Core (aka .Net 8 or higher, nowadays) has a nice little annotation named ProducesResponseType.

It lets you indicate explicitly what a REST endpoint can return. It helps a lot when you use auto-generation tools for the client : Not only Response classes, but also the service class in its entirety (it knows what to do with each http code).

Notice how it does not only indicate the type OR the http code, but possible combinations of both:

[ProducesResponseType(typeof(DepartmentDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]

I would like to know what my options are in Java. Either vanilla Java, or JAX-RS, or Spring.

At the moment my legacy code looks like this (below). @Produces is a start, but not as complete as the ProducesResponseType mechanism.

@PUT
@Path("/my-endpoint/{id}")
@Produces({MediaType.APPLICATION_JSON,})
@Consumes(MediaType.APPLICATION_JSON)
public Response doTheThing(...

Solution

  • If your client would be generated based on OpenAPI description you could annotate your methods similar to this:

     @GET
        @Produces(MediaType.APPLICATION_JSON)
        @APIResponseSchema(value = InventoryList.class,
            responseDescription = "host:properties pairs stored in the inventory.",
            responseCode = "200")
        @Operation(
            summary = "List inventory contents.",
            description = "Returns the currently stored host:properties pairs in the "
            + "inventory.")
        public InventoryList listContents() {
            return manager.list();
        }
    

    Check this tutorial for some general information - https://openliberty.io/guides/microprofile-openapi.html#augmenting-the-existing-jakarta-restful-web-services-annotations-with-openapi-annotations

    And here are more complex examples: https://github.com/eclipse/microprofile-open-api/blob/main/tck/src/main/java/org/eclipse/microprofile/openapi/apps/airlines/JAXRSApp.java