grails Simple REST API with grails


Example

import grails.rest.*

@Resource(uri='/books')
class Book {

    String title

    static constraints = {
        title blank:false
    }
}

Simply by adding the Resource transformation and specifying a URI, your domain class will automatically be available as a REST resource in either XML or JSON formats. The transformation will automatically register the necessary RESTful URL mapping and create a controller called BookController.

You can try it out by adding some test data to BootStrap.groovy:

def init = { servletContext ->
    new Book(title:"The Stand").save()
    new Book(title:"The Shining").save()
}

And then hitting the URL http://localhost:8080/books/1, which will render the response like:

<?xml version="1.0" encoding="UTF-8"?>
<book id="1">
    <title>The Stand</title>
</book>

If you change the URL to http://localhost:8080/books/1.json you will get a JSON response such as:

{"id":1,"title":"The Stand"}

If you wish to change the default to return JSON instead of XML, you can do this by setting the formats attribute of the Resource transformation:

import grails.rest.*

@Resource(uri='/books', formats=['json', 'xml'])
class Book {
    ...
}