In JAX RS, differences between returning Response and Bean or Collection of Beans (DTO) - rest

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, the ResponseBuilder class provides a convenient way to create a Response instance using a builder pattern.
'Regular' beans are mapped over in pretty much the same way as Response is, with the exception that a Response allows you to set additional metadata (response headers, specialized status, specialized content type, etc). As far as which one to use, thats entirely up to you too decide - Response gives you more flexibility, but regular beans are more 'self-documenting'.

There is no diference if you want to return always the response 200 - OK , catching and manipulate all the exceptions that may occur before of after your method return the result, with interceptions or WebApplicationException. So, both of these methods will result the same responses.
The only diference is at specific scenarios, like returning null objects, or creating object, like this example:
#POST
#Consumes("application/json")
public Response post(String content) {
URI createdUri = ...
Object createdContent = create(content);
return Response.created(createdUri).entity(createdContent).build();
}
In this case the return will be 201 - CREATED (With the URI to access the created object)
So, the following method:
#POST
#Consumes("application/json")
public Object post(String content) {
URI createdUri = ...
Object createdContent = create(content);
return createdContent;
}
... will return a response 200 - OK
If you don't care about which response status your client will receive, you can use any of declarations without problem.
Source: Jersey.

My personal of view, if response contains DTO (Bean/Collection of beans), then rest service always must return DTO, but not Response object.
The motivation: early or late, you will be asked to make a usage of rest service easier for clients, by providing rest client api. Usually, you have to extract rest interfaces for it, and implement them with your rest services. These rest interfaces are used by clients of your rest client.
And from a client point of view there is a huge difference between processing DTO and plain Response. In case Response is used, your client is forced:
Check response code explicitely to process successfull response
Handle errors, by checking codes explicitly
Convert body of your response into DTO by himself.
Which means handling Response is very similar to returning error codes in methods, which is considered as a very bad practice. In order to handle errors in one place, exceptions are used (I'm not talking about FP ways of handle errors, which is the best).
So what may you do:
In case a request is processed successfully, convert in your rest service data into DTO/Bean and return it.
In case if validation failed, or something went wrong, throw an exception in your rest service. Perhaps a default exception mapper is not good for you, so, you'll have to implement your own exception mapper.
So if to think in advance, you should return DTO.
One use-case, when plain Response should be returned - when you export file, for instance. It seems JAX RS does not allow to return InputStream object. Not sure, it has to be checked.
The other use case, was pointed by #Perception, but it is more an exception, than a rule:
Methods that need to provide additional metadata with a response
should return an instance of Response, the ResponseBuilder class
provides a convenient way to create a Response instance using a
builder pattern.
Note: it is a general question for JAX RS, does not depend on exact implementation, like Resteasy or Jersey

Related

Multiple payloads in MVC core rest api

I am developing a rest api on .Net core 2.2 following MVC pattern.
I have a controller with a post method like this...
// POST: api/Todo
[HttpPost]
public async Task<ActionResult<TodoItem>> PostTodoItem(string param, [FromBody] TodoItem item)
{
// some work...
return CreatedAtAction(nameof(GetTodoItem), new { id = item.Id }, item);
}
And it works fine.
The customer asked to have an api on the same route, but the Json body could have 2 different structures, bearing the same data on different schemas.
I considered using
PostTodoItem(string param, [FromBody] Object item)
{
// TryCast item to one of the possible POCO classes then work with the correct one.
}
Do you know a better way, maybe with some advanced routing and filtering option?
This is not really possible nor desirable. Pretty much the core tenant of REST is a URI uniquely represents a particular resource. If you've got a URI like POST /todo, then the post body should be a "todo" and it should create a new "todo" based on that. Here, that is a TodoItem, so that is all that should ever be posted.
REST aside, this just won't work. When your action is activated, the modelbinder attempts to bind the post body to the param(s) that the action accepts. It basically just news up whatever type the param is, and then attempts to find something from the post body to bind to the various properties on that type. This is an intentionally simplistic description of what's happening; the important part is that the type of the param informs how the post body is bound. If you bind to an object (which has no members) or even a base type, then the only members of the post body that will be bound are those that are present on that type, not derived types thereof. Anything that cannot be bound is discarded.
Long and short, you need a unique route for each type of thing you're working with. Under the hood, you can share or otherwise reuse code by factoring out common functionality into private methods, employing inheritance, etc., but you need a distinct action and route to handle each case.

What is an entity in Akka-Http?

I am new to akka-http and building a basic server-client application in scala. The examples I looked at has the object "entity". Can someone please explain the concept underlying and why is it used and how is it useful?
post {
path("insert") {
entity(as[Student]) {
obj => complete {
insertingstudent(obj)
s"got obj with name ${obj.getName()}"
}
}
Thanks
Can someone please explain the concept underlying and why is it used
and how is it useful?
entity is of type HttpEntity. From the comments of the code:
Models the entity (aka "body" or "content") of an HTTP message.
It is an abstraction over the content of the HTTP request. Many times, when one sends an HTTP request, they provide a payload inside the body of the request. This body can be in many format, popular ones are JSON and XML.
When you write:
entity(as[Student])
You are attempting to unmarhsall, or deserialize, the body of the request into a data structure of your liking. That means that your obj field in the proceeding function will be of type Student.

Handle Links in Restful Webservice Client

I'm implementing a client to a restful webservice, that returns results in a linked-list kind of way, where each element, besides the actual contents has a URI pointing to the next part of the result.
#XmlRootElement()
public class PagedResult<T> {
private List<T> values;
private URI next;
}
Using jax-rs(jersey) with jax-b there is plenty of documentation on how to create these links on the server side, but I'm not sure whats the preferred way to handle this on the client. I could obviously parse the URI and do the request myself, but that seems wrong.
Is there a simple way to get a getNext() method (returning PagedResult, not URI)?

JAX-RS generic response and interface proxy

is there any way how to return generic describing entity type with the JAX-RS Response? Something like REST-Easy ClientReponse but JAX-RS standard and not implementation-specific class.
The thing is I want to call my REST service via its shared interface (created by some proxy provider) and returning only object does not allow add information I need. E.g. for creating resource via POST, I would like to return also URL to newly created resource and so on. Returing simple Response does not show what type of entity is stored within such response.
Response<MyObject> getMyObject(#PathParam("id" Integer id)
So far it seems that I will have to return simple Response and then create adapter which will simply call Response.getEntity(.class)
There is probably no such option...
GenericEntity allows you to return a generic. The actual type is held at runtime by GenericEntity, allowing the object to be serialized.
Here's a contrived example of how it can be used.
GenericEntity entity = new GenericEntity<Employee>(new Employee());
return Response.ok(entity).build();

asp.net MVC 2.0 REST service with FormCollection

Let's say the Action below is exposed via REST service and is called from a different appliation how would it handle the posted data/object?
Should I use Create(FormCollection collection) here?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Member member)
{
....
}
I'd suggest using a model, but one in which all of the parameters are nullable and use the RequiredAttribute for actual, required parameters. This would allow your method to accept invalid requests -- with missing or extra data -- yet have valid data bound to the model. For invalid data, you can supply error returns instead of presuming default values for non-nullable properties. Using the model binding validation architecture provides a convenient way to make sure that the request is legal. It would be up to you how you want to handle "extra" data supplied by the request -- I'd say ignore it.