Grails - Domain classes as REST resources



Description

You can create a RESTful API in Grails, the simple way to do this is by using a domain class as a REST resource. You should add grails.rest.Resource transformation to domain class as shown below snippet:

import grails.rest.*
@Resource(uri='/api/orders', formats=['json', 'xml'])
class Orderdemo {
	
	Long id
	String stock
	String side
	Double price
	Long size
	
	static mapping = {
		version false
		table 'orders'
		id column: 'id', generator:'native', params:[sequence:'order_seq']
	  }
	
    static constraints = {
			stock blank:false
			price blank:false
			quantity blank:false
	}
}

Your domain class will be available as a REST resource in either XML or JSON formats, by just adding the Resource transformation and specifying a URI. Registering the required RESTful URL mapping and creating a controller called OrderdemoController will be done with the help of transformation.

If you want to test, you can add sample data in BootStrap.groovy file as shown below:

import grails.rest.example.Orderdemo

class BootStrap {

    def init = { servletContext ->
        new Orderdemo(stock:"Nokia", price:20000, quantity:100).save()
        new Orderdemo(stock:"Samsung", price:30000, quantity:200).save()
	new Orderdemo(stock:"HTC", price:15000, quantity:300).save()
    }
    def destroy = {
    }
}

The JSON response can be obtained by using the ACCEPT header or by using the file extension in the URI. The table below shows to obtain JSON response using the Unix curl tool:

S.N.Method & DescriptionSyntax
1 GET
To display the record GET method is used.
curl -i -H "Accept: application/json" localhost:8080/api/orders
	
2 POST
To create a new resource, you can use POST request:
curl -i -X POST -H "Content-Type: application/json" -d 
'{"price": 200,"side": "S","size": 5000,"stock": "TWT"}' localhost:8080/api/orders
	
3 PUT
To update a record, PUT request is used.
curl -i -X PUT -H "Content-Type: application/json" -d
 '{"price": 210,"size": 500}' localhost:8080/api/orders/1
	
4 DELETE
To delete a resource, DELETE request is used:
curl -i -X DELETE localhost:8080/api/orders/1
	
Advertisements