mbgsuirp
mbgsuirp

Reputation: 628

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?

Upvotes: 15

Views: 82186

Answers (4)

Sahil Patel
Sahil Patel

Reputation: 234

to make request parameter optional set @RequestParam to false in controller class

@GetMapping("/get")
public get(@RequestParam(value = "name", required = false) String name){
 
/* code of controller......*/

}

Upvotes: 0

Emdadul Sawon
Emdadul Sawon

Reputation: 6077

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.

Upvotes: 6

user8681
user8681

Reputation:

It might be easier to turn the optional path parameters into query parameters. You can then use @DefaultValue if you need it:

@GET @Path("/job/{param1}/{param2}")
public Response method(@PathParam("param1") String param1,
    @PathParam("param2") String param2,
    @QueryParam("optional1") String optional1,
    @QueryParam("optional2") @DefaultValue("default") String optional2) {
  ...
}

You can then call it using /job/one/two?optional1=test passing only the optional parameters you need.

Upvotes: 24

cassiomolin
cassiomolin

Reputation: 130877

Rearrange the params and try the following:

@Path("/job/{param1}/{param2}{optional1 : (/optional1)?}{optional2 : (/optional2)?}")
public Response myMethod(@PathParam("param1") String param1,
                         @PathParam("param2") String param2,
                         @PathParam("optional1") String optional1,
                         @PathParam("optional2") String optional2) {
    ...
}

Upvotes: 1

Related Questions