Two GET methods with different query parameters

ritesh picture ritesh · Jun 24, 2013 · Viewed 36.2k times · Source

Could we create the same GET URI but with different query parameters?

For example, I have two REST GET URIs:

/questions/ask/?type=rest
/questions/ask/?byUser=john

Now the REST service is not recognizing two GET methods as separate and considering it only 1 GET method which is declared as first.

  1. Why is it behaving this way?
  2. Is there any way that I could make two GET methods having different Query Parameters?

It would be highly appreciated if you could quote any resource.

Answer

darijan picture darijan · Jun 24, 2013

Because a resource is uniquely identified by its PATH (and not by its params). Two resources you define have the same PATH.

@Path("/questions/ask")

According to JSR-311 spec:

Such methods, known as sub-resource methods, are treated like a normal resource method (see section 3.3) except the method is only invoked for request URIs that match a URI template created by concatenating the URI template of the resource class with the URI template of the method.

Since your data model includes two distinct resources I suggest making two rest methods with different paths:

@Path("/questions/ask/type")
@Path("/questions/ask/user")

This is the RESTful way, since one URI represents one and only one resource and there should be no overloading. If one URI represents more than one resource that means you got it wrong somewhere.