Last active
January 30, 2025 04:14
-
-
Save henriquecarv/06d31d6039e2744450dcc110e203f65f to your computer and use it in GitHub Desktop.
FreecurrencyAPI - Get Exchange rate (Google Apps Script)
This file contains hidden or 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
/** | |
* | |
* @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 | |
+ '¤cies=' + 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