4

I am using RESTEasy in my API development. My url is http://localhost:8080/project/player/M or http://localhost:8080/project/player

it means am pasing {gender} as path param.

my problem is how to mapp this url to REST method, i use below mapping

@GET
@Path("player/{gender}")
@Produces("application/json")

but if use it, it maps for http://localhost:8080/project/player/M but not for http://localhost:8080/project/player. i need a regular expression to map zero or more path parameters

Thanks.

Romi
  • 4,833
  • 28
  • 81
  • 113

4 Answers4

10

Is there any reason this must be a path parameter and not a query string ? If you change it to use the latter, then you can use a @DefaultValue annotation.

So your code would then look like the following:

@GET
@Path("player") //example: "/player?gender=F"
@Produces("application/json")
public Whatever myMethod(@QueryParam("gender") @DefaultValue("M") final String gender) {
  // your implementation here
}
mrjmh
  • 978
  • 10
  • 12
  • Even though this is not a direct answer to the question it is the right thing to do. REST paths shouldn't have optional parts. I was doing this wrong and this answer "woke me up". – Vinicius Jun 18 '21 at 12:47
6

Path parameters (@PathParam) aren't optional. If you want to map;

You will need two methods. You can use method overloading;

@GET
@Path("player/{gender}")
@Produces("application/json")
public Whatever myMethod(@PathParam("gender") final String gender) {
  // your implementation here
}

@GET
@Path("player")
@Produces("application/json")
public Whatever myMethod() {
  return myMethod(null);
}
Qwerky
  • 18,217
  • 6
  • 44
  • 80
  • 1
    I don't think this is correct. See: http://stackoverflow.com/questions/5421104/optional-pathparam-in-jax-rs – rtcarlson Apr 28 '14 at 18:14
1

See the below link which has a sample of optional path parameters via regular expressions

RestEasy @Path Question with regular expression

Community
  • 1
  • 1
fmucar
  • 14,361
  • 2
  • 45
  • 50
  • I would not recommend you to use regular expressions as path parameters. It just complicates a relatively simple problem... – eiden Jan 23 '12 at 15:20
0

You should use regex when you want have optional parameter in path.

So your code would then look like the following:

@GET
@Path("/player{gender : (/\\w+)?}")
@Produces("application/json;charset=UTF-8")
public Whatever myMethod(@QueryParam("gender") @DefaultValue("M") final String gender) {
  // your implementation here
}

For more information see https://docs.jboss.org/resteasy/docs/1.1.GA/userguide/html/Using__Path_and__GET___POST__etc..html

arVahedi
  • 107
  • 1
  • 3
  • 15