Skip to content

Instantly share code, notes, and snippets.

@henriquecarv
Last active January 30, 2025 04:14
Show Gist options
  • Save henriquecarv/06d31d6039e2744450dcc110e203f65f to your computer and use it in GitHub Desktop.
Save henriquecarv/06d31d6039e2744450dcc110e203f65f to your computer and use it in GitHub Desktop.
FreecurrencyAPI - Get Exchange rate (Google Apps Script)
/**
*
* @param baseCurrency string - Ex. "USD"
* @param exchangeCurrency string - Ex. "EUR"
* @param refreshCache boolean - Default false
* @returns number - Ex. 0.95
*/
function GET_EXCHANGE_RATE(baseCurrency, exchangeCurrency, refreshCache = false) {
const exchangeRateCacheKey = 'exchange_rate' + '_' + baseCurrency + '_' + exchangeCurrency
const cache = CacheService.getScriptCache();
if(!refreshCache){
const cached = cache.get(exchangeRateCacheKey);
if (cached != null) {
return cached;
}
}
const scriptProperties = PropertiesService.getScriptProperties();
const api_key = scriptProperties.getProperty("api_key"); // Store it in the project's settings
const url = 'https://api.freecurrencyapi.com/v1/latest?'
+ 'apikey=' + api_key
+ '&base_currency=' + baseCurrency
+ '&currencies=' + exchangeCurrency;
const response = UrlFetchApp.fetch(url, {
method: "GET",
contentType: "application/json",
});
const { data } = JSON.parse(response.getContentText());
const exchangeRate = data[exchangeCurrency];
cache.put(exchangeRateCacheKey, exchangeRate, 86400); // 1 day
return exchangeRate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment