Grails REST: Generate RestfulController
Since version 2.3 Grails has excellent support for creating REST APIs. This new support comes with some new console commands. Besides the well known generate-controller
command, Grails now comes with a new command which let you generate restful controllers for a given domain class. In the following example, we will create a restful controller using the new generate-restful-controller command.
First we create a domain object
$ grails create-domain-class grails.data.Movie
Second we will generate the REST controller using the new command:
$ grails generate-restful-controller grails.data.Movie
This command will generate a restful controller with the name MovieController
with a default REST implementation. Notable is that this generated controller does not extend RestfulController<T>
but gives you a full implementation of the REST functionality inside the actions. Below you can see for example the default implementation of the index
method of the generated restful controller.
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
respond Movie.list(params), [status: OK]
}
Furthermore this command will generate the REST responseType settings so both JSON and XML formats are supported.
static responseFormats = ['json', 'xml']
Code written in Grails 2.4.1