Example of how to use Groovy HTTPBuilder library

Let us consider a short example of HTTPBuilder usage. HTTPBuilder is very handy HTTP client which is built on top of Apache's HttpClient. As a sample we will use REST API provided by Glosbe. In this example we will use Gradle and start with generating Gradle project:

 gradle init --type groovy-library

This command will generate for us project structure:


Now we need to add Gradle dependencies. HTTPBuilder itself and TestNG as a testing framework. After we are done, build.gradle file will look like below:


apply plugin: 'groovy'

repositories {
    jcenter()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.6'
    compile group: 'org.codehaus.groovy.modules.http-builder', name: 'http-builder', version: '0.6'
    testCompile group: 'org.testng', name: 'testng', version: '6.9.10'
}

In the example below we will translate the word "world" from English to French. To see what response looks like, you can use https://glosbe.com/gapi/translate?from=eng&dest=fr&format=json&phrase=world&pretty=true. After we receive response we will make sure that HTTP status of operation is 200,   response body contains "result" : "ok" and actual translation.


import groovyx.net.http.HTTPBuilder
import static org.testng.Assert.assertEquals
import static org.testng.Assert.assertTrue
import org.testng.annotations.Test

class AppTest {

    @Test
    void jsonTest() {

        def http = new HTTPBuilder('https://glosbe.com')

        http.get(path: '/gapi/translate',
                query: [
                        from  : 'eng',
                        dest  : 'fr',
                        format: 'json',
                        phrase: 'world']) { resp, json ->

            assertEquals(resp.status, 200, "HTTP status code of response")
            assertTrue("ok".equalsIgnoreCase(json.result), 
                        "Result in response body is different from expected")
            assertTrue("monde".equalsIgnoreCase(json.tuc[0].phrase.text), 
                        "Result in response body is different from expected")
        }
    }
}

That's it! Now you can see how simple it can be to work with API using HTTPBuilder and Groovy.

Comments