RESTClient with Groovy WSLite

Groovy-WSLite is a library for Groovy that provides an easy way to consume SOAP and REST webservices. Let’s consider the following CURL command:

curl https://weblux.josdem.io/sanity/ping



So using Groovy-WSLite we can create an script like this:

#!/usr/bin/env groovy


import wslite.rest.RESTClient

def sanityStarter(){
  println 'Starting sanity check'
  def client = new RESTClient("https://webflux.josdem.io/")
  def response = client.get(path:'/sanity/ping')
  assert 200 == response.statusCode
  println 'Up and running!'


In order to execute previous script save it in a file named sanityCheck.groovy and provide the following privileges:

chmod 755 sanityCheck.groovy

Then you can execute this command:


Post with Headers

Let’s consider the following curl command:

curl -v -d 'username=myuser&password=mypassword' -X POST "http://myhost/oauth/token"

Here we are sending an username and password in a urlencoded format using POST method to the http://myhost/oauth/token url in a verbose mode.

Using groovyx.net.http.RESTClient could be this way:

  def rest = new RESTClient('http://myhost/')
  def response = rest.post(
    path: 'oauth/token',
    body: [username:'myuser',password:'mypassword'],
    requestContentType: URLENC )

} catch(Exception ex) {
  log.warn "Error: ${ex.message}"

If we need to send some headers in curl format:

curl -H "Content-Type: application/json" -H "Authorization: Bearer be41be7a-70ca-4988-89df-54beb212e6a9" -X POST -d '{"name":"josdem","email":"joseluis.delacruz@gmail.com"}' "http://myhost/services/user"

Here we are sending JSON data with Authorization: Bearer be41be7a-70ca-4988-89df-54beb212e6a9 as header.

RESTClient version:

  def rest = new RESTClient('http://myhost/')
  String token = 'mytoken'
  def response = rest.post(
    path: 'services/user',
    headers: [Authorization:"Bearer ${token}"],
    body: [name:"josdem",email:"joseluis.delacruz@gmail.com"],
    requestContentType: 'application/json' )
} catch(Exception ex) {
  log.warn "Error: ${ex.message}"

Return to the main article

comments powered by Disqus