user3913652
user3913652

Reputation: 27

Grails: RESTful web services data processing in different format

Currently I'm working on grails 2.4.3 with GGTS 3.6.0

Requirement - How a grails web service work.

Existing - Currently my closure is working for me as a web service but output is format specific(JSON or XML at a time).

Problem - In closure(web service), how I would be able to return JSON/XML and other format.

Closure code -

def able_Webservice = {

   ableService.populateAbleBean(ableBean);
   ableService.settingWhereClause(ableBean);
   ableService.getDBData(ableBean);
   def jsonData = ableService.webservice_Data(ableBean);
   render jsonData as JSON

}   

Upvotes: 0

Views: 121

Answers (2)

Gregor Petrin
Gregor Petrin

Reputation: 2931

You can use the controller's respond method to render your data in format most appropriate for the request. If the HTML response is chosen as the most appropriate, it will render a template determined by the /views/controllerName/actionName convention.

def able_Webservice = {

    ableService.populateAbleBean(ableBean);
    ableService.settingWhereClause(ableBean);
    ableService.getDBData(ableBean);
    def data = ableService.webservice_Data(ableBean);
    respond data
}   

Upvotes: 0

Andriy Budzinskyy
Andriy Budzinskyy

Reputation: 2001

Grails has withFormat feature. You can render different responses based on the incoming request Accept header, format parameter or URI extension.

Your code would like:

def able_Webservice = {
   ableService.populateAbleBean(ableBean);
   ableService.settingWhereClause(ableBean);
   ableService.getDBData(ableBean);
   def data = ableService.webservice_Data(ableBean);
   withFormat {
      xml { render data as XML }
      json { render data as JSON }
   }
}

This uses built-in content negotiation.

Upvotes: 2

Related Questions