REST in Grails
Learn about using REST services with Grails.
We'll cover the following
How it works
Groovy includes some built-in support for XML, such as the XMLSlurper. Grails also includes converters for simply converting objects to XML or JSON or vice versa.
import grails.converters.JSON
import grails.converters.XML
class BookController {
def getBooks = {
render Book.list() as JSON
}
def getBooksXML = {
render Book.list() as XML
}
}
For REST services that service multiple formats, you can use the built-in withFormat
in Grails. So the above would become the following:
def getBooks = {
withFormat {
json { render list as JSON }
xml { render list as XML }
}
}
Then Grails would decide which format to use based on numerous inputs; the simplest being the extension of the URL, such as .json
or the request’s Accept
header.
For using web-services in Grails, there’s a rest plugin available.
Get hands-on with 1400+ tech skills courses.