Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails 2.4.3: Consume a REST Service

How do I consume a RESTful web service in Grails 2.4.3. I also need to use Basic Authentication.

You would think there would be an good answer to this question already, but I have really struggled to find one. Many answers point me in the direction of the Grails rest plugin, which I have tried but could not get to work for me. I think I am probably just struggling with the docs and using it wrong.

like image 214
SGT Grumpy Pants Avatar asked Aug 24 '14 10:08

SGT Grumpy Pants


2 Answers

I found the REST Client Builder Plugin, which was better documented and worked much better for me. Thanks to Graeme Rocher for that! Here's a simple example that will hopefully be helpful to others.

import grails.plugins.rest.client.RestBuilder
import grails.transaction.Transactional

@Transactional
class BatchInstanceService {

    def getBatch(String id) {
        String url = "https://foo.com/batch/$id"

        def resp = new RestBuilder().get(url) {
            header 'Authorization', 'Basic base64EncodedUsername&Password'
        }
    }
}

And here's the test class.

import grails.test.mixin.*

import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*
import org.springframework.http.HttpStatus

import spock.lang.Specification

@TestFor(BatchInstanceService)
class BatchInstanceServiceSpec extends Specification {

    void "test get batch" () {
        when:
        def resp = service.restart('BI1234')

        then:
        resp.status == HttpStatus.OK.value
    }
}

The object returned, resp, is an instance of the ResponseEntity class.

I really hope this helps. If there are better examples please post links to them. Thanks!

like image 59
SGT Grumpy Pants Avatar answered Oct 21 '22 21:10

SGT Grumpy Pants


Yes, you can pass a UrlTemplate-style string and the map of name/value pair url parameters to be substituted. In addition, there is another shortcut to Auth headers that will auto-encode... so

    def urlTemplate = "https://foo.com/batch/{id}"
    def params = [id: $id]

    def resp = new RestBuilder().get(urlTemplate, params) {
       auth username, password
    }
like image 36
durp Avatar answered Oct 21 '22 20:10

durp