Grails hip tip: optional URL parameters
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:
/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 URLMappings.groovy 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:
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?
| Related odds and ends | ||
|---|---|---|
1 comment Wednesday 08 Jul 2009 | Groovy
One Response to “Grails hip tip: optional URL parameters”
Thank you
Best Regards
Dean