I am working on building a REST api. My question is, when using Jersey, what are the differences between my services building and returning a Response object or returning the the bean or collection. I am only concerned with successful calls, I am throwing appropriate exceptions for errors and exceptional situations.
Here is a example:
@Produces(MediaType.APPLICATION_JSON)
public Response search(FooBean foo){
List<FooBean> results = bar.search(foo);
return Response.ok(results).build();
}
vs.
@Produces(MediaType.APPLICATION_JSON)
public List<FooBean> search(FooBean foo){
List<FooBean> results = bar.search(foo);
return results;
}
I've seen both examples used, and I'd prefer the second scenario, just to make it easier to recognize the service method. I've examined the responses to both of these methods and they appear to be identical.
Thoughts?
The differences are explained in the JAX-RS specification:
3.3.3 Return Type
Resource methods MAY return void, Response, GenericEntity, or another Java type, these return types are mapped to a response entity body as follows:
void
Results in an empty entity body with a 204 status code.
Response
Results in an entity body mapped from the entity property of the Response with the status code specified by the status property of the Response. A null return value results in a 204 status code. If the status property of the Response is not set: a 200 status code is used for a non-null entity property and a 204 status code is used if the entity property is null.
GenericEntity
Results in an entity body mapped from the Entity property of the GenericEntity. If the return value is not null a 200 status code is used, a null return value results in a 204 status code.
Other
Results in an entity body mapped from the class of the returned instance. If the return value is not null a 200 status code is used, a null return value results in a 204 status code.Methods that need to provide additional metadata with a response should return an instance of Response