Jersey REST query parameter combinations validation

I have a RESTful resource implemented using Java and Jersey.

It is allowed to have any one of the below query parameter combinations

  • queryParam1 OR
  • queryParam2 OR
  • queryParam3 & queryParam4

I currently implemented this like below:

@GET
@Path("/my-resource")
public MyResource findMyResource(
      @QueryParam("param1") String param1,
      @QueryParam("param2") String param2,
      @QueryParam("param3") String param3,
      @QueryParam("param4") String param4) {

    if (param1 != null && (param2 == null && param3 == null && param4 == null)) {
        ...
    } else if (param2 != null && (param1 == null && param3 == null && param4 == null)) {
      ...
    } else if (param3 != null && param4 != null && (param1 == null && param1 == null)) {
      ...
    } else {
      // return 400 BAD REQUEST
    }
    ...
}

This looks really ugly. Is there a way to achieve this in a cleaner way?

1 answer

  • answered 2019-12-15 04:28 hoodakaushal

    If I were you, I'd just have three different APIs instead. One that only takes param1 - call if findMyResourceByParam1 (maybe not even as a query parameter but as a path parameter since it is required), one that only takes param2, and so on.

    This also makes it less likely that whoever is using the API will mess up exactly which parameters need to be specified.

    Also, this is rather subjective, but IMO query parameters should be optional, if your API requires one or more parameters then they should be path params not query params.