Can I overload the REST url resource with different arguments?

Using the same resource URL, is it possible to call different methods depending on 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); 
+5
source share
2 answers

To answer the question

No, this is not possible because the container does not have information on how to redirect the request.

What could you do

As pointed out in the comments of @Jim Garrison, you can get around this by differentiating the path. However, I find this somewhat controversial. As far as I understand, this is not a completely different resource. You just want to use a different view.

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

Your API clients should be aware of this design decision. If you don’t know if introducing custom media types is a good idea, look at the answers to these questions, which may make this a bit clearer:

If you do not want the views to be different, then I do not quite understand the meaning of these two classes. Perhaps this separation should not extend to your RESTful API, and you should use these views internally. In this case, you can implement an adapter, decorator, or possibly factory, to be able to switch between the two implementations. It is difficult to recommend a specific template without knowing how these classes should be used and what they represent.

+4
source

No, It is Immpossible. From your example, I could see what you are trying to add. If these are two different classes, I assume its two different things.

For example: Contacts, Items like this.

Usually in these cases we would have two api.

One for adding Contacts (Class1) and one for adding elements (Class2). To understand the understanding for the client side.

0
source

Source: https://habr.com/ru/post/1200697/


All Articles