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

In some books, other APIs usually return a Response object that wraps some other objects representing payload, status, etc.

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

It might be an opinion based opinion, but I would like to know which one is best to use in a highly scalable environment where some queries lead to success and others fail / data that is not returned.

I would like to know if there is an accepted best practice. This will help me develop some APIs and put things in perspective in front of my team. But I'm fine with closing this question if "better of two" has too many opinions.

Thank.

Update: Both break APIs will look like this. Avoid code like @Path, @Get, @PathParam, @Produces, etc.

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

      

Returns a Customer object wrapped inside a Response object. The answer could also be a mistake.

And the below approach will return the Customer object directly:

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

      

+3


source to share


3 answers


I would vote for the API that gives you the Response object. This allows complete control over the response in your code, and it is clear what happens in the response. And in cases where you want to write an answer that cannot be easily represented by a POJO, you won't be forced to use non-intuitive workarounds.

Returning an object from a dormancy handler method, which is then converted to a response, is too small for my style.



Worst - imho is the practice of returning a String from a remainder handler method, which is then interpreted as a template reference (like a JSP resource path), which is then written into the response. Too much magic again.

+3


source


I prefer to return custom data objects rather than response objects. The whole point of annotation-based frameworks is to abstract the http aspects out of the application logic. Instead of managing response codes and entities, application developers return model objects and throw custom exceptions that can be mapped to http codes in the mapper. It's less control, but IMHO, it's much easier to develop api quickly.



+4


source


One response object returned contains your data, which gets legacy of request / response like SOAP and HTTP, but REST services are based on the concept of request / response resources so I prefer to use objects representing your actual resources without a wrapper, as a rest service can represent yours resources directly to the response object for ex. if you call the resource as a car:

http: // localhost / car GET for the list of cars

http: // localhost / car / 1 GET to get car with id 1

how to represent this in the response object?

0


source







All Articles