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

You can use javax.validation annotations to enforce that the parameters are mandatory by annotating them with @javax.validation.constraints.NotNull. See an example for Jersey and one for RESTeasy.

So your method would simply become:

@GET
@Path("/some-path")
public String read(@NotNull @QueryParam("name") String name) {
  String something = 
  // implementation
  return something;
}

Note that the exception gets then translated by the JAX-RS provider to some error code. It can usually be overridden by registering your own implementation of javax.ws.rs.ext.ExceptionMapper<javax.validation.ValidationException>.

This provides a centralized way to translate mandatory parameter to error responses and no code duplication is necessary.


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
}

Tags:

Java

Jax Rs