Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I overload REST url resource having different arguments?

Tags:

java

rest

jax-rs

Using the same url of the resource, is it possible to call different methods underneath depending the arguments?

@POST
@Path("/resource/add")
@Consumes(MediaType.APPLICATION_JSON)
public Response add(Class1 arg1);

@POST
@Path("/resource/add")
@Consumes(MediaType.APPLICATION_JSON)
public Response add(Class2 arg2);
like image 983
vezzmax Avatar asked Aug 19 '14 19:08

vezzmax


1 Answers

To answer the question

No, it is not possible because the container has no information on how to route the request.

What you could possibly do

As pointed out by @Jim Garrison in the comments, you could work around this by differentiating the path. However, I find this somewhat counter-intuitive. As far as I understand, it's not a different resource at all. You just want to use a different representation.

If you really want to introduce such logic, maybe you should introduce your own, custom media types for specific formats and use them instead of the generic application/json

The clients of your API would have to be conscious of this design decision, though. If you're unsure whether the introduction of custom media types is a good idea, take a look at the answers to these questions, which may make it a bit clearer:

  • How to create a custom media type (application/vnd) for a RESTful web service?
  • Is using custom json content-types a good idea

If you don't want to have the representations different, then I don't really understand the point of having those two classes. Perhaps this division should not reach your RESTful API and you should be using these representations internally. In this case, you might want to implement an adapter, a decorator or maybe a factory to be able to switch between the two implementations. It's difficult to recommend a specific pattern without knowing how these classes are supposed to be used and what they represent.

like image 174
toniedzwiedz Avatar answered Oct 07 '22 00:10

toniedzwiedz