Grails’s RESTClient

Grails, groovy, programming

The groovy.net.http.RESTClient class is a subclass of a more general groovyx.net.http.HttpBuilder class and comes with the “rest” plugin (http://grails.org/plugin/rest).

GET

A simple GET request with query parameters:

def rest = new RESTClient('http://www.my.com')
try {
// equivalent to: http://www.my.com/abc/123?param1=p1&param2=p2&param3=p3a&param3=p3b
def response = rest.get([
path:'/abc/123',
contentType:'application/json',
query:[param1:'p1', param2:'p2', param3:['p3a','p3b']])

// Assuming the server respects Content-Type and returns a JSON,
// the follow will provide the JSONObject or JSONArray
// for the returned results
def json = response.data
...
} catch (HttpResponseException ex) {
// errors and response status codes >= 400 end up here
}

POST

A sample for POSTing data w/ JSON

def rest = new RESTClient('http://www.my.com')
try {
// equivalent to: POST http://www.my.com/abc/123 with body of '{"param1": 1, "param2": "2"}'
def response = rest.post(path:'/abc/123',
contentType:'application/json',
body: [param1: 1, param2: "2"])
json = response.data
} catch (HttpResponseException ex) {
...
}

groovy.net.http.HttpBuilder uses the RequestConfigDelegate class to parse the map provided to get() and post(). The map supports these keys:

  • uri — used to specify the complete URL for the request, excluding the query component.  If used with path, then this should be the base URL. This value overrides the value passed to the ctor of RESTClient
  • query — used to specify a map of values representing the query parameters.  Lists are supported (see the GET example above).
  • path — used in conjunction with uri if you want to separate the path and base components of a URL.
  • contentType — the Content-Type to use and accept (either a String literal such as ‘application/json’ or a groovyx.net.http.ContentType constant).
  • requestContentType — if the request body type is different than the response (Accepts) body type, then this value is used to specify the request’s content type.
  • body — the body of the request
  • headers — used to specify a map of headers for the request

No support for URL fragments (as of rest-0.8)

You will need to create a java.net.URI instance with the entire URL w/ query and fragment and pass it to the ctor of RESTClient.

Response

By default, get() and post() will return an instance of groovyx.net.http.HttpResponseDecorator.  Commonly used methods are isSuccess() and getData().

  • isSuccess() returns true if the HTTP status code is < 400.
  • getData() will return the parsed body, and the type depends on the contentType used for the get() or post() method.