Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 453
MattC Avatar asked Oct 10 '14 01:10

MattC


People also ask

What is the use of @consumes annotation of Jax RS?

The @Consumes annotation is used to specify which MIME media types of representations a resource can accept, or consume, from the client. If @Consumes is applied at the class level, all the response methods accept the specified MIME types by default.

Which annotation is used for RESTful Web services?

The @Path annotation is used to specify the URI through which a resource and an API can be accessed. Resource in this case is the REST Web service itself. Thus this annotation is present at the class level as well as the method level. It is mandatory to annotate a REST Web resource class with the @Path annotation.

What is @path annotation in Java?

The @Path annotation identifies the URI path template to which the resource responds and is specified at the class or method level of a resource.

What if @consumes is applied both on method as well as resource class?

@Consumes annotation is used to specify the MIME media types that a resource can consume. @Consumes can be applied at both class level and method level, If applied on class level all the methods can produce the specified MIME types by default.


1 Answers

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.

like image 161
logicalicy Avatar answered Sep 27 '22 20:09

logicalicy