v5gfda
Last Updated: February 25, 2016
·
1.279K
· bendoerr

Groovy tricks for easy API calls

I often write quick one time scripts against all manner of remote API's over HTTP. One of the things that helps keep my code succinct is pimping String in various ways.

Almost always I add a method to skip the toURL().getContent().text chain.

// pimp String
String.metaClass.getRemoteContent = {
    delegate.toURL().getContent().text
}

Often I'll create a Category for the API.

class MediaWikiApi {

    String qPageAction = 'action=query&prop=revisions&rvprop=content'

    String wikiPage(String self) {
        "${baseUrl}?titles=${self}&${qPageAction}"
    }
}

Then putting it all together

use(MediaWikiApi) {
    println "Books".wikiPage().getRemoteContent()
}

2 Responses
Add your response

2946

Can't you just do delegate.toURL().text ?

over 1 year ago ·
2948

You totally can!

I 'personally' like the extra call to getContent() (standard JDK) and then getText() (Groovy JDK InputStream) since it makes reading the code a bit easier for those who haven't memorized a lot of the Groovy JDK yet. I think many developers, myself included, seeing Url.getText() would think that it returns the url itself as a string.

over 1 year ago ·