UrlFetchApp 與外部 API
Apps Script 沒有瀏覽器的 fetch。對外 HTTP 一律走 UrlFetchApp。把 JSON 寫進試算表、呼叫 Gemini/Vertex AI、接公司內部 API,都是這條路。
讀 JSON
function fetchRates() {
const url = "https://api.example.com/rates";
const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
if (res.getResponseCode() !== 200) {
throw new Error("API " + res.getResponseCode() + ": " + res.getContentText());
}
const data = JSON.parse(res.getContentText());
const rows = data.items.map((item) => [item.name, item.price]);
SpreadsheetApp.getActiveSheet().getRange(2, 1, rows.length, 2).setValues(rows);
}
muteHttpExceptions: true 才讀得到 4xx/5xx 的本文,否則一非 2xx 就丟例外、看不到伺服器說什麼。
POST、帶標頭:
const res = UrlFetchApp.fetch(url, {
method: "post",
contentType: "application/json",
headers: { Authorization: "Bearer " + token },
payload: JSON.stringify({ prompt: "摘要這段文字" }),
muteHttpExceptions: true,
});
金鑰與配額
API 金鑰放 PropertiesService.getScriptProperties(),不要寫進 Code.gs。UrlFetchApp 每天有呼叫次數上限,迴圈裡對每一列打一次 API 很容易用完;能批次就批次,或先寫進快取 CacheService。
進階 Google 服務
YouTube、Sheets API v4、Drive API v3 等,可在編輯器左側 服務 → 新增,用較完整的 REST 資源,而不只靠內建 DriveApp。OAuth 範圍會變多,發佈外掛前要在 appsscript.json 對過。
官方用 UrlFetchApp 打 Vertex AI/Gemini 的示範,見 官方影音 的「AI 外掛程式碼講解」。跟做外部 API 的社群片見 YouTube 優質教學。