5

I need to map path with multiple optional arguments to my endpoint

path will look like localhost/func1/1/2/3 or localhost/func1/1 or localhost/func1/1/2 and this path should be correctly matched with

public Double func1(int p1, int p2, int p3){ ... }

What should I use in my annotations?

It's test task to play with Jersey to find a way for using multiple optional params, not to learn REST design.

silent_coder
  • 6,222
  • 14
  • 47
  • 91
  • 1
    You probably need to have a quick review of you Rest api. The url should match resource not action. And most of the time resource should have only one way to be accessed directly (you may access it by relation to other resource). Tanking this into account, optional arguments really better fit as query parameters (it is then easy to set default value to them). – Kazaag Jan 27 '16 at 12:37
  • It's not about REST, it's about jersey. I just need to know how to use multiple optional params – silent_coder Jan 27 '16 at 12:46
  • Jersey has been build to make it easy to implement Rest idioms. If you don't use Rest idioms, it is probably not the best framework to be used. – Kazaag Jan 27 '16 at 12:49
  • I know superbly what is rest and how to use it. I just playing with framework and trying to learn how to use multiple optional parameters. – silent_coder Jan 27 '16 at 12:51

2 Answers2

9

To solve this you need to make your params optional, but also / sign optional

In the final result it will looks similar to this:

    @Path("func1/{first: ((\+|-)?\d+)?}{n:/?}{second:((\+|-)?\d+)?}{p:/?}{third:((\+|-)?\d+)?}")
    public String func1(@PathParam("first") int first, @PathParam("second") int second, @PathParam("third") int third) {
        ...
    }
Ph0en1x
  • 9,943
  • 8
  • 48
  • 97
6

You should give QueryParams a try:

@GET
@Path("/func1")
public Double func1(@QueryParam("p1") Integer p1, 
                    @QueryParam("p2") Integer p2, 
                    @QueryParam("p3") Integer p3) {
...
}

which would be requested like:

localhost/func1?p1=1&p2=2&p3=3

Here all parameters are optional. Within the path part this is not possible. The server could not distinguish between e.g.:

func1/p1/p3 and func1/p2/p3

Here are some examples of QueryParam usage: http://www.mkyong.com/webservices/jax-rs/jax-rs-queryparam-example/.

wumpz
  • 8,257
  • 3
  • 30
  • 25