Cache API Responses in Apps Script with CacheService
Every call to an external API or SpreadsheetApp takes time and counts against your quotas. CacheService lets you store results temporarily and reuse them across executions — making your scripts faster and more quota-efficient.
What is CacheService?
CacheService provides an in-memory key-value store that persists for up to 6 hours (21,600 seconds). It has three scopes:
// Shared across all users and executions of this scriptconst cache =CacheService.getScriptCache();// Per-user, shared across executionsconst cache =CacheService.getUserCache();// Per-user, per-documentconst cache =CacheService.getDocumentCache();
For caching API responses shared by all users, use getScriptCache().
Cache a simple API response
functiongetExchangeRates(){const cache =CacheService.getScriptCache();const cacheKey ='exchange_rates_USD';// Check cache firstconst cached = cache.get(cacheKey);if(cached){Logger.log('Cache hit!');returnJSON.parse(cached);}// Cache miss — fetch from APILogger.log('Cache miss — fetching from API...');const response =UrlFetchApp.fetch('https://api.exchangerate-api.com/v4/latest/USD');const data =JSON.parse(response.getContentText());// Store in cache for 1 hour (3600 seconds) cache.put(cacheKey,JSON.stringify(data),3600);return data;}
Cache pattern: read-through helper
A clean wrapper that handles cache check, fetch, and store:
functioncachedFetch(url, ttlSeconds =3600){const cache =CacheService.getScriptCache();const key ='fetch_'+Utilities.base64Encode(url);const hit = cache.get(key);if(hit)returnJSON.parse(hit);const response =UrlFetchApp.fetch(url,{muteHttpExceptions:true});if(response.getResponseCode()!==200){thrownewError(`HTTP ${response.getResponseCode()} from ${url}`);}const data =JSON.parse(response.getContentText()); cache.put(key,JSON.stringify(data), ttlSeconds);return data;}// Usage:functiongetWeather(){const apiKey =PropertiesService.getScriptProperties().getProperty('WEATHER_API_KEY');const data =cachedFetch(`https://api.openweathermap.org/data/2.5/weather?q=London&appid=${apiKey}`,900// Cache for 15 minutes);Logger.log(data.main.temp);}
Cache Sheet data for a custom function
Custom functions in Sheets run frequently. Caching avoids repeated API calls: