Skip to content

Instantly share code, notes, and snippets.

@tgherzog
Last active May 16, 2023 05:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgherzog/8a9c53ef0bb27290c968a67f2e5ba8f7 to your computer and use it in GitHub Desktop.
Save tgherzog/8a9c53ef0bb27290c968a67f2e5ba8f7 to your computer and use it in GitHub Desktop.
Google sheets interface to the World Bank API. Paste this code into the Google Sheets script editor to add a custom function.
/**
* Fetches data from the World Bank API
*
* @param {string} indicator The indicator code
* @param {string} country The 2- or 3-character ISO country code
* @param {number} year The optional year. If omitted, fetch most recent available
* @return The data value.
* @customfunction
*/
function WBAPI(indicator, country, year) {
var url = 'http://api.worldbank.org/v2/en/country/' + country + '/indicator/' + indicator + '?'
if( year == undefined ) {
url += 'MRV=1'
}
else {
url += 'date=' + year
}
url += '&format=json'
var response = UrlFetchApp.fetch(url);
var json = response.getContentText()
var data = JSON.parse(json)
if( data.length < 2 ) {
// whoops, there's an error. Likely an invalid function parameter
return data[0].message[0].key
}
return data[1][0].value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment