MattC
MattC

Reputation: 6364

Why use REST @Produces annotation

So I understand that you are specifying the type, but why? Under what conditions would 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 then a container will assume that any type can be produced.' So why would I not want the container to assume that?

Upvotes: 7

Views: 17652

Answers (2)

tom
tom

Reputation: 2712

If a client requests your JSON only resource with an Accept: application/xml; header then strictly speaking the server should return a 406 (not acceptable) status code, not the JSON string.

If you use the @Provides annotation, the container should handle this case for you and that is why you should use it.

Upvotes: 1

logicalicy
logicalicy

Reputation: 917

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

Basically, it's up to the client to determine what content type the server should spit back. If the client supports more than one content type, you can sometimes specify the priority of content types to return, for a given method:

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

In the above sample, if client accepts both "application/xml" and "application/json" (equally), then a server always sends "application/json", since "application/xml" has a lower quality factor.

Upvotes: 7

Related Questions