মঙ্গলবার, ১৯ জুলাই, ২০১১

Restfull in grails

Restfull for Grails :

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 ->
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
Final project structure will be:




















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 {

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")
}

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:
  • GET -> show
  • PUT -> update
  • POST -> save (used when you know ID of item you create - not our case;)
  • DELETE -> delete
Implementation of our controller will use GORM for data storage and will communicate with client application using JSON format. Edit /grails-app/controllers/BookController.groovy:

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"}

1 টি মন্তব্য: