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.
The @QueryParam annotation allows you to map a URI query string parameter or url form encoded parameter to your method invocation.
PathParam could be used to drill down to entity class hierarchy. Whereas, QueryParam could be reserved for specifying attributes to locate the instance of a class. For example, /Vehicle/Car?
Query parameters allow you to pass optional parameters like page number to the component. In this tutorial, we look at how to pass the query parameters using the queryParams directive.
Basically, @QueryParam denotes that the value of the Query Parameter with the corresponding name will be parsed, and if parsed correctly it will be available on the method argument denoted with @QueryParam . There are baically two ways to pass parameters in a GET request in REST services.
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 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With