10.5.2 Implementing REST Controllers Step by Step

If you don’t want to take advantage of the features provided by the RestfulController super class, then you can implement each HTTP verb yourself manually. The first step is to create a controller:

  1. $ grails create-controller book

Then add some useful imports and enable readOnly by default:

  1. import grails.gorm.transactions.*
  2. import static org.springframework.http.HttpStatus.*
  3. import static org.springframework.http.HttpMethod.*
  4. @Transactional(readOnly = true)
  5. class BookController {
  6. ...
  7. }

Recall that each HTTP verb matches a particular Grails action according to the following conventions:

HTTP MethodURIController Action
GET/booksindex
GET/books/${id}show
GET/books/createcreate
GET/books/${id}/editedit
POST/bookssave
PUT/books/${id}update
DELETE/books/${id}delete
The create and edit actions are already required if you plan to implement an HTML interface for the REST resource. They are there in order to render appropriate HTML forms to create and edit a resource. They can be discarded if that is not a requirement.

The key to implementing REST actions is the respond method introduced in Grails 2.3. The respond method tries to produce the most appropriate response for the requested content type (JSON, XML, HTML etc.)

Implementing the 'index' action

For example, to implement the index action, simply call the respond method passing the list of objects to respond with:

  1. def index(Integer max) {
  2. params.max = Math.min(max ?: 10, 100)
  3. respond Book.list(params), model:[bookCount: Book.count()]
  4. }

Note that in the above example we also use the model argument of the respond method to supply the total count. This is only required if you plan to support pagination via some user interface.

The respond method will, using Content Negotiation, attempt to reply with the most appropriate response given the content type requested by the client (via the ACCEPT header or file extension).

If the content type is established to be HTML then a model will be produced such that the action above would be the equivalent of writing:

  1. def index(Integer max) {
  2. params.max = Math.min(max ?: 10, 100)
  3. [bookList: Book.list(params), bookCount: Book.count()]
  4. }

By providing an index.gsp file you can render an appropriate view for the given model. If the content type is something other than HTML then the respond method will attempt to lookup an appropriate grails.rest.render.Renderer instance that is capable of rendering the passed object. This is done by inspecting the grails.rest.render.RendererRegistry.

By default there are already renderers configured for JSON and XML, to find out how to register a custom renderer see the section on "Customizing Response Rendering".

Implementing the 'show' action

The show action, which is used to display and individual resource by id, can be implemented in one line of Groovy code (excluding the method signature):

  1. def show(Book book) {
  2. respond book
  3. }

By specifying the domain instance as a parameter to the action Grails will automatically attempt to lookup the domain instance using the id parameter of the request. If the domain instance doesn’t exist, then null will be passed into the action. The respond method will return a 404 error if null is passed otherwise once again it will attempt to render an appropriate response. If the format is HTML then an appropriate model will produced. The following action is functionally equivalent to the above action:

  1. def show(Book book) {
  2. if(book == null) {
  3. render status:404
  4. }
  5. else {
  6. return [book: book]
  7. }
  8. }

Implementing the 'save' action

The save action creates new resource representations. To start off, simply define an action that accepts a resource as the first argument and mark it as Transactional with the grails.gorm.transactions.Transactional transform:

  1. @Transactional
  2. def save(Book book) {
  3. ...
  4. }

Then the first thing to do is check whether the resource has any validation errors and if so respond with the errors:

  1. if(book.hasErrors()) {
  2. respond book.errors, view:'create'
  3. }
  4. else {
  5. ...
  6. }

In the case of HTML the 'create' view will be rendered again so the user can correct the invalid input. In the case of other formats (JSON, XML etc.), the errors object itself will be rendered in the appropriate format and a status code of 422 (UNPROCESSABLE_ENTITY) returned.

If there are no errors then the resource can be saved and an appropriate response sent:

  1. book.save flush:true
  2. withFormat {
  3. html {
  4. flash.message = message(code: 'default.created.message', args: [message(code: 'book.label', default: 'Book'), book.id])
  5. redirect book
  6. }
  7. '*' { render status: CREATED }
  8. }

In the case of HTML a redirect is issued to the originating resource and for other formats a status code of 201 (CREATED) is returned.

Implementing the 'update' action

The update action updates an existing resource representation and is largely similar to the save action. First define the method signature:

  1. @Transactional
  2. def update(Book book) {
  3. ...
  4. }

If the resource exists then Grails will load the resource, otherwise null is passed. In the case of null, you should return a 404:

  1. if(book == null) {
  2. render status: NOT_FOUND
  3. }
  4. else {
  5. ...
  6. }

Then once again check for errors validation errors and if so respond with the errors:

  1. if(book.hasErrors()) {
  2. respond book.errors, view:'edit'
  3. }
  4. else {
  5. ...
  6. }

In the case of HTML the 'edit' view will be rendered again so the user can correct the invalid input. In the case of other formats (JSON, XML etc.) the errors object itself will be rendered in the appropriate format and a status code of 422 (UNPROCESSABLE_ENTITY) returned.

If there are no errors then the resource can be saved and an appropriate response sent:

  1. book.save flush:true
  2. withFormat {
  3. html {
  4. flash.message = message(code: 'default.updated.message', args: [message(code: 'book.label', default: 'Book'), book.id])
  5. redirect book
  6. }
  7. '*' { render status: OK }
  8. }

In the case of HTML a redirect is issued to the originating resource and for other formats a status code of 200 (OK) is returned.

Implementing the 'delete' action

The delete action deletes an existing resource. The implementation is largely similar to the update action, except the delete() method is called instead:

  1. book.delete flush:true
  2. withFormat {
  3. html {
  4. flash.message = message(code: 'default.deleted.message', args: [message(code: 'Book.label', default: 'Book'), book.id])
  5. redirect action:"index", method:"GET"
  6. }
  7. '*'{ render status: NO_CONTENT }
  8. }

Notice that for an HTML response a redirect is issued back to the index action, whilst for other content types a response code 204 (NO_CONTENT) is returned.