User27854
User27854

Reputation: 884

Java JAX-RS How to implement a GET API with query and normal request

I am learning JAX-RS, as an activity, I have created an endpoint which will list out all the TODO within by DB.

@Path("list")
@GET
public List<Todo> getTodos(){
    return todoService.getTodos();
}

The end point URL is

http://localhost:9090/hello-todo/api/v1/todo/list

Currently it lists all the TODO items, Since, I am learning query params I have decided to add add a condition to and list out only completed TODO items.

The end point URL is

http://localhost:9090/hello-todo/api/v1/todo/list?taskstatus=completed

The implementation method which I have written is @Path("list") @GET public List getFilteredTodos(@QueryParam("taskstatus") String taskstatus_){ return todoService.getFilteredTodos(); }

The build is fine, but while deploying it throws the below error:

The application resource model has failed during application initialization.

[[FATAL] A resource model has ambiguous (sub-)resource method for HTTP method GET and input mime-types as defined by"@Consumes" and "@Produces" annotations at Java methods public java.util.List academy.learnprogramming.rest.TodoRest.getTodos() and public java.util.List academy.learnprogramming.rest.TodoRest.getFilteredTodos(java.lang.String) at matching regular expression /list. These two methods produces and consumes exactly the same mime-types and therefore their invocation as a resource methods will always fail.; source='org.glassfish.jersey.server.model.RuntimeResource@8bd9d08']

I get that the deployement has failed as the both are having the same URI but how do I handle such a scenario?

Possible Solution:

@Path("list")
@GET
public List<Todo> getFilteredTodos(@QueryParam("taskstatus") String taskstatus_){
    if (taskstatus_!=null && !taskstatus_.isEmpty()) {
        return todoService.getFilteredTodos(taskstatus_);
    }else{
        return todoService.getTodos();
    }

}

Upvotes: 2

Views: 588

Answers (2)

alexandrum
alexandrum

Reputation: 429

You can create something like:

 @GET
   @Path("list/{taskStatus}")
   public List getFilteredTodos(@PathParm("taskStatus") String taskStatus) {
      // do the filtering
   }

So you will have a different path that will not be conflicted with the main one.
More details here and here.

Upvotes: 1

skydriver
skydriver

Reputation: 11

Possible solution: Implement one method with @Path("list") and handle the case with an empty taskstatus parameter value inside

Upvotes: 1

Related Questions