Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional params in REST API request using Jersey 2.21

I'm playing around with Jersey 2.21 and I'd like to know if it's possible to have an "optional" param which can, or not, be present in the request made to the server.

I want to successfully access this two methods:

http://localhost:8080/my_domain/rest/api/myMethod/1
http://localhost:8080/my_domain/rest/api/myMethod

As you can see, I'm trying to make the integer (id) param an optional one.

I've declared myMethod as follows:

@GET
@Path("myMethod/{id}")
@Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public String myMethod(@PathParam("id") Integer id, @Context HttpHeaders hh)

This works:

http://localhost:8080/my_domain/rest/api/myMethod/1

and this works too:

http://localhost:8080/my_domain/rest/api/myMethod/

but this won't work and I don't understand why. It throws a 404 Not Found error:

http://localhost:8080/my_domain/rest/api/myMethod

Can you point me in the right direction to work this out? I don't like the slash being mandatory on all my REST method calls and would like to suppress it if possible.

like image 585
JorgeGRC Avatar asked Sep 24 '15 15:09

JorgeGRC


1 Answers

There is a way easier way to do this:

@GET
@Path("myMethod/{id}")
public String myMethod(@PathParam("id") Integer id) {
}

@GET
@Path("myMethod")
public String myMethod() {
  return myMethod(null);
}

No tricky regex required.

like image 138
ccleve Avatar answered Nov 15 '22 20:11

ccleve