grails create-app RestFullTest
cd RestFullTest
grails create-domain-class book
grails create-controller Book

You can add some code this /grails-app/conf/BootStrap.groovy file:
def init = { servletContext ->Final project structure will be:
new Book(author:"S.M. Mahmudul Hasan",title:"Grails").save()
new Book(author:"Shohan",title:"Restfull").save()
}
or U can insert value in db
or U can insert by programatically

RESTful server
We need to create controller that will be performing base CRUD operations and map its methods to REST style URLs.
Edit /grails-app/conf/UrlMappings.groovy:
class UrlMappings {Entry with /book maps GET and POST HTTP requests to this URL to list and create controller methods. Below we map URLs like /book/$id using default grails REST mapping:
static mappings = {
"/$controller/$action?/$id?" {
constraints {
// apply constraints here
}
}
"/"(view: "/index")
"500"(view: '/error')
"/book"(controller: "book") {
action = [GET: "list", POST: "create"]
}
"/book/$id"(resource: "book")
}
- GET -> show
- PUT -> update
- POST -> save (used when you know ID of item you create - not our case;)
- DELETE -> delete
import grails.converters.*
class BookController {
def list = {
response.setHeader("Cache-Control", "no-store")
render Book.list(params) as JSON
}
def show = {
Book b=Book.get(params.id)
render b as JSON
}
def create = {
def json = JSON.parse(request);
def b = new Book(json)
b.save()
response.status = 201
response.setHeader('Location', '/book/'+b.id)
render b as JSON
}
def delete = {
Book b=Book.get(params.id)
b.delete()
render(status: 200)
}
}
Run this code with grails run-app and point your browser to http://localhost:8080/GrailsRestTest/book. You should get following response:
[{"class":"Book","id":1,"author":"S.M. Mahmudul Hasan","title":"Grails"},{"class":"Book","id":2,"author":"Shohan","title":"Restfull"}]To get particular item try http://localhost:8080/GrailsRestTest/book/1 - response should be:
{"class":"Book","id":1,"author":"S.M. Mahmudul Hasan","title":"Grails"}
courtesy: http://maciekmoczkowski.blogspot.com/2010/01/almost-restfull-application-with-grails.html
উত্তরমুছুন