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()
}
Written by Ben Doerr
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Groovy
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#