Why use REST @Produces annotation

So, I understand that you are specifying the type, but why? Under what conditions does it matter. For example, if I have the following method and I comment out the @Produces annotation, it still returns JSON.

@GET
@Path("/json")
//@Produces({MediaType.APPLICATION_JSON})
public String getJson(){
    return toJson(getResults());
}

      

The API doc says, "If not specified, the container will assume any type can be created." So why don't I want the container to assume this?

+3


source to share


2 answers


I think it depends on your JAX-RS implementation, but here Jersey explains their @Produces annotation: https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e1809

Basically, it is up to the client to determine what type of content the server should return. If the client supports multiple content types, it is sometimes possible to specify the priority of the returned content types for a given method:



@Produces({"application/xml; qs=0.9", "application/json"})

      

In the above example, if the client accepts both "application / xml" and "application / json" (the same), the server will always send "application / json" because "application / xml" has a lower quality factor.

+6


source


If the client requests your only JSON resource with a header Accept: application/xml;

, then strictly speaking the server should return a status code 406

(not acceptable), not a JSON string.



If you are using annotation @Provides

, the container should handle this case for you, which is why you should use it.

0


source







All Articles