How to create a REST API with additional parameters?

I need to implement an API with these path parameters.

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

Can the second and third parameters optional? Thus, the client should not transmit this data, but must pass the first and last.

If this is not possible, is it recommended to reorder the parameters in this way?

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

How to provide optional parameters?

+7
java rest jax-rs
source share
3 answers

You can match the whole path ending in a REST request

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

The path variable now contains the full path after location/{locationId}

You can also use regex 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 encode, this will be optional. You do not attach importance, they will be empty.

+3
source share

It may be easier to include optional path parameters in the query parameters. Then you can 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) { ... } 

Then you can call it using /job/one/two?optional1=test , passing only the parameters you need.

+7
source share

Change the settings 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) { ... } 
+1
source share

All Articles