v5gfda
Last Updated: February 25, 2016
·
1.228K
· bendoerr
9114304b96acd7b2bd88275eaccdbdbf

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()
}
Say Thanks
Respond

2 Responses
Add your response

2946
De6eafe28472ceb9522fd3f609afed53

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

over 1 year ago ·
2948
9114304b96acd7b2bd88275eaccdbdbf

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 ·