Last Updated: February 25, 2016
· 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 = {

Often I'll create a Category for the API.

class MediaWikiApi {

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

    String wikiPage(String self) {

Then putting it all together

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

2 Responses
Add your response

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

over 1 year ago ·

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 ·