I am new to grails and I am learning. I want to consume a webservice API(Rest). I searched for the example but didn't get a good one. My requirement is: The address to consume is eg:localhost:8080/order/createOrder; which will provide the JSON. My JSON format will be :
//and from JSON is:
username: 'abc',
password: 'xyz',
order: {
orderDate
orderNumber
subTotal
shipping
discount
netTotalPaid
creditApplied
transactionId
specialInstruction
}
I have to get the username,password and Order from JSON. Order is a Domain class where I will set the data from JSON.
Please suggest me with a detail explanation.
And if the JSON is not REST service,i.e.The application itself provides JSON as a service ? , if we don't need to consume a REST service ?
Getting the JSON
Again, a few options. I like to use the REST Client Builder Plugin for this sort of thing. It comes with lots of utility methods to make your life easier.
For example, to get the JSON from your end point, it would be something like:
Using the JSON
There's a few options.
If
Orderis a domain class that maps to these values exactly, then you can use theGSONplugin. This enables the serialization and de serialization of POJOs (or grails Domain objects). An example of the usage is:Or if you want to keep things Grails, you can use the converters..
Personally, I prefer the former.
Design Tips
Don't put all this stuff in a controller. Abstract it out to a service, so that your controller simply passes it off to the service layer and doesn't care what happens to it.
Put your URLs to the RESTful service in some sort of object, or string. If you change API endpoints, you don't want to have to update it all over your application.
Extra Reading
The GSON plugin home is where you can find the dependency to add to your build config.
The Docs will show you how to use the GSON plugin.
And these Docs will show you how to use the REST Client Builder Plugin.