Grails hip tip: optional URL parameters

how-to
Jul 8, 20092 mins

Often times with RESTful services, a particular URI might need a further level of detail than simply /widget/id — that is, a particular resource might be further segregated by date (i.e. give me the representation of a widget with an id of 29 on the date 04-09-2009). Thus, the URI pattern one would like to support in Grails is more like:

<pre class="prettyprint"><code>/widget/id
/widget/id/date

Obviously, the pattern could go on — one could further segregate a widget by date and batch, for example (in fact, one could make the date aspect more detailed by making the day-month-year pattern separate variables).

As I’ve written about before, enabling RESTful services in Grails is a snap and one of the first things you must do is alter the <a href="<a href="https://grails.org/doc/1.1/ref/Plug-ins/URL%20mappings.html">https://grails.org/doc/1.1/ref/Plug-ins/URL%20mappings.html</a>">URLMappings.groovy</a> file found in your grails-app/conf directory.

If you look closely at this particular mapping, you’ll notice Groovy’s null safety operator in action:

<pre class="prettyprint"><code>class UrlMappings {
 static mappings = {
   "/$controller/$id?"{
    constraints {
     action = [GET:"show", POST:"save", PUT:"update", DELETE:"remove"]
      }
  }
  "/"(view:"/index")
  "500"(view:'/error')
 }
}

As you can see with the id variable in the mapping String — it ends with a ?, which designates it as optional. Thus, the /widget URI returns a list of widgets in which ever response format requested, for example (assuming you’ve coded that logic in your controller). If you want additional variables, such as a date and batch like I’ve outlined above, all you need to do is add additional optional variables like so:

"/$controller/$id?/$var1?/$var2?"

Thus, in a particular controller, you can grab those additional parameters by checking to see if they exist within the param map (i.e. param.var1). Don’t worry if a particular optional parameter isn’t there either — a call to the map will simply return null.

Building RESTful services in Grails is as easy as cake, don’t you think, man?

You can now follow The Disco Blog on Twitter, baby!
andrew_glover

When Andrew Glover isn't listening to “Funkytown” or “Le Freak” he enjoys speaking on the No Fluff Just Stuff Tour. He also writes articles for multiple online publications including IBM's developerWorks and O'Reilly’s ONJava and ONLamp portals. Andrew is also the co-author of Java Testing Patterns, which was published by Wiley in September 2004; Addison-Wesley’s Continuous Integration; and Manning’s Groovy in Action.

More from this author