12.8. Using REST in Groovy

Groovy, a dynamic language for the JVM, has built-in support for REST. The RESTClient class is an extension of HTTPBuilder, designed specifically for making REST calls easier (for example, by having convenience methods for GET, POST, etc.).

Issuing GET Requests
Given RESTClient, it's pretty easy:

import groovyx.net.http.RESTClient
 
def client = new RESTClient( 'http://www.acme.com/' )
def resp = client.get( path : 'products/3322' ) // ACME boomerang

assert resp.status == 200  // HTTP response code; 404 means not found, etc.
println resp.getData()

The response field data is the parsed response content, always buffered in-memory.

Issuing POST Requests
Equally simple, using the same class:

import groovyx.net.http.RESTClient
 
def client = new RESTClient( 'http://www.acme.com/' )
def resp = client.post( path : '/user/details',
                        body : [ firstName:'John', lastName:'Doe' ] )

assert resp.status == 200

Here, too, the response is available in resp.getData().

3 comments:

Unknown said...

Thanks for an excellent tutorial, very well written.

Unknown said...

Could you please include example with headers?

Sarala said...

A sample with extracting cookies from login response and using it for further queries would be of great help