Marcus Junius Brutus Marcus Junius Brutus - 4 months ago 33
Java Question

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

I deploy a web-services component to JBoss 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

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(HttpURLConnection.HTTP_BAD_REQUEST)
        .entity("name parameter is mandatory")
        .build()
    );
  }
  // continue with a normal flow
}