Last active
May 16, 2023 05:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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