10.1.1 Domain classes as REST resources - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.1.9
10.1.1 Domain classes as REST resources
The easiest way to create a RESTful API in Grails is to expose a domain class as a REST resource. This can be done by adding thegrails.rest.Resource transformation to any domain class:import grails.rest.*@Resource(uri='/books') class Book { String title static constraints = { title blank:false } }
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()
}<?xml version="1.0" encoding="UTF-8"?> <book id="1"> <title>The Stand</title> </book>
http://localhost:8080/books/1.json you will get a JSON response such as:
{"id":1,"title":"The Stand"}formats attribute of the Resource transformation: import grails.rest.*@Resource(uri='/books', formats=['json', 'xml']) class Book { … }
grails.mime.types setting of application.groovy:grails.mime.types = [
…
json: ['application/json', 'text/json'],
…
xml: ['text/xml', 'application/xml']
]curl tool:$ curl -i -H "Accept: application/json" localhost:8080/books/1 {"id":1,"title":"The Stand"}
POST request:$ curl -i -X POST -H "Content-Type: application/json" -d '{"title":"Along Came A Spider"}' localhost:8080/books HTTP/1.1 201 Created Server: Apache-Coyote/1.1 ...
PUT request:$ curl -i -X PUT -H "Content-Type: application/json" -d '{"title":"Along Came A Spider"}' localhost:8080/books/1 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 ...
DELETE request:$ curl -i -X DELETE localhost:8080/books/1 HTTP/1.1 204 No Content Server: Apache-Coyote/1.1 ...
Resource transformation enables all of the HTTP method verbs on the resource. You can enable only read-only capabilities by setting the readOnly attribute to true:import grails.rest.*@Resource(uri='/books', readOnly=true) class Book { … }
