Skip to content
Advertisement

How to create REST API with optional parameters?

I need to implement an API with these path params.

@Path("/job/{param1}/{optional1}/{optional2}/{param2}")

Can the second and third params by optional? So the client need not pass these, but have to pass the first and last.

If this is not possible, then is it recommended to rearrange the params in this way?

@Path("/job/{param1}/{param2}/{optional1}/{optional2}")

How to provide the optional params?

Advertisement

Answer

You can match the entire path ending in the REST request

@Path("/location/{locationId}{path:.*}")
public Response getLocation(
    @PathParam("locationId") int locationId,
    @PathParam("path") String path) {
    //your code
}

Now the path variable contain entire path after location/{locationId}

You can also use a regular expressions to make the path optional.

@Path("/user/{id}{format:(/format/[^/]+?)?}{encoding:(/encoding/[^/]+?)?}")
public Response getUser(
    @PathParam("id") int id,
    @PathParam("format") String format,
    @PathParam("encoding") String encoding) {
    //your code
}

Now if you format and encoding will be optional. You do not give any value they will be empty.

Advertisement