Skip to main content.
July 15th, 2009

JAX-RS, @Path, @PathParam and Optional Parameters

In a recent Java project I needed to develop and provide to external clients a RESTful Web Services interface to an internal system. After some research I found that using JAX-RS and its open-source implementation Jersey with Spring and Hibernate as back-end will be great technologies stack for this project. Seems easy but unfortunately I found that JAX-RS does not support optional path parameters.

Customer requested each service to have an optional path parameter called “format” that specifies the output format. All services were required to support multiple output formats: XML, plain text, CSV, JSON, PDF, etc. For example if I request this URL: http://myserver.com/services/location/3/format/xml, the output should be XML, but if I request just http://myserver.com/services/location/3 without “format” parameter, the result should be plain text.

Mandatory Path Parameters

Using a path pattern like this:

makes the parameter “format” mandatory. If we skip it, the request will not match the path.

Optional @Path Parameters in JAX-RS

Using regular expressions and a simple hack can overcome this limitation in JAX-RS. The following example defines two optional path parameters “format” and “encoding”:

Requesting http://localhost:8080/services/user/3, will return “No format specified. No encoding specified”.
Requesting http://localhost:8080/services/user/3/format/pdf/encoding/utf8, will return “Format=pdf Encoding=utf8″.
Requesting http://localhost:8080/services/user/3/encoding/utf8, will return “No format specified. Encoding=utf8″.

Flexible @Path Parameters in JAX-RS

If we need more flexibility, we can match the entire path ending in the REST request and map it in key-value style (HashMap< String, String >):

Requesting http://localhost:8080/services/location/3, will return “Location: id=3″.
Requesting http://localhost:8080/services/location/3/format/json, will return “{ ‘location’ : { ‘id’ : ‘3′ } }”.

Enjoy!

Posted by nakov in java, blog

This entry was posted on Wednesday, July 15th, 2009 at 2:47 am and is filed under java, blog. You can follow any responses to this entry through the comments RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.