Required @QueryParam in JAX-RS (and what to do in their absence)

Marcus Junius Brutus picture Marcus Junius Brutus · Dec 20, 2012 · Viewed 91.7k times · Source

I deploy a web-services component to JBoss Application Server 7 using the RESTEasy JAX-RS implementation.

Is there an annotation available to declare required, mandatory @QueryParam parameters in JAX-RS ? And, if not, what is the 'standard' way to deal with situations where such parameters are missing?

My web service (resource) methods return JSON-stringified results when properly invoked with all the mandatory arguments, but I'm not sure what is the best way to indicate to the caller that a required parameter was missing.

Answer

yegor256 picture yegor256 · Dec 20, 2012

Good question. Unfortunately (or maybe fortunately) there is no mechanism in JAX-RS to make any params mandatory. If a parameter is not supplied it's value will be NULL and your resource should deal with it accordingly. I would recommend to use WebApplicationException to inform your users:

@GET
@Path("/some-path")
public String read(@QueryParam("name") String name) {
  if (name == null) {
    throw new WebApplicationException(
      Response.status(Response.Status.BAD_REQUEST)
        .entity("name parameter is mandatory")
        .build()
    );
  }
  // continue with a normal flow
}