Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better: returning a Response object or an Object representing the rest resource?

Tags:

java

rest

In some books, the rest APIs generally return a Response object which wraps some other objects representing payload, status, etc.

On the other hand many of the APIs that I have seen and written return a POJO (or call it a DTO) as JSON which is the consumed by the client.

This may be opinion based, but I would like to know which is better of the two to use on high scalability environment where some request result in success and others in failure/data not returned.

I would like to know if there is an accepted better practice. This will help me designing some APIs and put things in perspective before my team. But I am ok with this question being closed if 'better of the two' is too much opinion based.

Thanks.

Update: The two rest APIs would look like this. Avoiding code like @Path, @Get, @PathParam, @Produces etc

public Response myCustomerObject(int id){...} 

This returns a Customer object wrapped inside the Response object. Response could be error as well.

And the approach below will return the Customer entity directly:

public Customer myCustomerObject(int id){...} 
like image 503
Atul Avatar asked Jul 08 '15 13:07

Atul


1 Answers

I would vote for an API which gives you a Response object. This allows you to control the response completely within your code and it is clear what is going into response. And in cases where you want to write a Response which cannot easily be represented by a POJO you are not forced to use unintuitive workarounds.

Returning a Object from a rest handler method which is then transformed into a response is too much framework magic for my taste.

Worst - imho - is the practice to return a String from the rest handler method which is then interpreted as a template reference (e.g. the path to a JSP resource) which is then written to the response. Again way too much magic.

like image 95
wero Avatar answered Sep 29 '22 19:09

wero