Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Leonardo da Vinci once mused:
simplicity is the ultimate sophistication
REST embodies this thought and thus yields highly scalable, loosely coupled systems that, as it turns out, are simple to build, baby! There are a few mechanisms for implementing RESTful applications– Restlets and JSR 311 are two in a handful of options available in Java; however, they address one aspect of RESTful applications and ignore other aspects like an ORM and testing. Groovy’s Grails gives you the ability to apply RESTful techniques with a full fleged web application framework that supports an ORM and testing to boot! As you’ll see, using Groovy’s Grails framework makes building RESTful Web services a snap — in 3 steps, in fact.
Briefly, the three steps are:
Say for instance, you’d like to create a RESTful web service that enables runners to sign up for races. In this context, imagine a company (foo) that provides the management platform that facilitates putting on races and other organizations (bar, etc) then create races (for which the first organization, foo, puts on). The management company will accordingly construct a web service that enables organizations to:
Accordingly, the first step is to create two domain objects — a Race and a Runner.
Hip domain objects in Grails are indubitably easy to create as there is little to no boiler plate code. For instance, my Race object, minimally speaking, has three properties — a name, a distance, and a collection of associated runners.
class Race {
String name
double distance
static hasMany = [runners:Runner]
}As you can see, properties inherent to a domain object are simply declared as normal properties (i.e. String name) and relationships are handled by GORM’s hasMany syntax, which states there is a runners property (a collection) that contains instances of Runner.
Next, my Runner domain object is similarly coded; however, in this case, I’ve stipulated that runner’s must be at least 13 in order to be eligible.
class Runner {
static constraints = {
age(min:13)
}
String firstName
String lastName
int age
static belongsTo = Race
}Note too how in GORM, I can make a relationship bi-directional by specifying a Runner instance belongs to a related Race via the belongsTo syntax.
The second step involves manipulating Grail’s URL mappings so as to expose my desired behavior in a more RESTful manner. Because REST relies on named resources rather than messages, it easily facilitates loose coupling when designing applications. As everything on the web, in essence, is a resource (think web pages, images, etc), REST’s reliance on resources limits the exposure of the underlying technology involved.
For instance, the following URL exposes a resource without implying anything about the underlying technology involved
http://thediscoblog.com/2008/03/20/unambiguously-analyzing-metrics/
As you can see, baby, there is a resource represented here– in this case an article called “Unambiguously analyzing metrics.” Notice how the URL is also noun based rather than verb based (which would look something like getArticle?name=blahblah). What’s more, requesting this resource leverages the HTTP GET command– one could also imagine posting a new resource (i.e. article) via HTTP’s POST command (such as http://thediscoblog.com/2008/03/22/rest-is-good-for-you/). Yet, using the same getArticle contrary example from earlier, you can imagine other API’s associated such as createArticle?name=blahblha and deleteArticle?name=blahblah– but in this case these calls are hijacking the HTTP GET command and for the most part, ignoring the already built (and did I say successful?) HTTP infrastructure available!
Thus, making Grail’s URLs more RESTful is done via the UrlMappings class, found in conf directory of a Grails application. In the case of the RESTful races and runners application, the class can be coded like so:
class UrlMappings {
static mappings = {
"/$controller/$id?"{
action = [GET:"show", POST:"save", PUT:"update", DELETE:"remove"]
}
"500"(view:'/error')
}
}In the code above, I’ve indicated that for any controller in my application, if the HTTP request, for example, is a GET, then Grails should invoke the show closure on that particular controller. Same for POST, PUT, and DELETE.
For instance, because it’s Grail’s bag, if Grails receives an HTTP GET request like www.acmeracing.com/race/165 — Grails will invoke the show closure on the RaceController.
Consequently, the final step in creating a RESTful web service in Grails is to code your controllers — in my case, I’d need two — one for handling races and another for handling runners — conceivably, these could be combined into one logical model as well. For example, my RunnerController is as follows:
import grails.converters.XML
class RunnerController {
def show = {
if(params.id && Runner.exists(params.id)){
render Runner.findById(params.id) as XML
}else{
render Runner.list() as XML
}
}
def save = {
def runner = new Runner(params['runner'])
if(runner.save()){
render runner as XML
}else{
//handle errors...
}
}
}The show closure is simple (as is the entire class, right, man?) — the id parameter is obtained and consequently a related runner is found; otherwise, all runners are displayed. Note, I’m using Grail’s XML render type, which renders objects in XML logically like so:
<?xml version="1.0" encoding="UTF-8"?>
<runner>
<age>20</age>
<firstName>Mary</firstName>
<lastName>Smith</lastName>
</runner>Note how easy it is to leverage Grail’s XML render — I just have to type render x as XML. I could just as easily, by the way, use Grail’s JSON render as well.
Creating a hip runner is just as easy — in this case, my application is expecting that a posted XML document follow the same structure as I’ve outlined above; thus, I can easily create a new runner instance with one line of code:
def runner = new Runner(params['runner'])
As coded, ‘runner’ is the root element — Grails auto-magically maps everything else for me!
That’s it — 3 steps in short order! First, create your domain objects. Second, create your mapping via the UrlMappings class; finally, code your controller(s) — they can either use XML or JSON — the choice is yours, baby!
Indeed, Grails makes RESTful web service creation a breeze. For as English Poet Alexander Pope once suggested:
There is a certain majesty in simplicity which is far above all the quaintness of wit.
Can you dig, man?
Want to learn more about Groovy and Grails? Then sign up for ThirstyHead's Jump into Groovy and Grails course!
Think easyb is the coolest thing since sliced bread? Then come to my BDD with easyb course too!