Google Apps Script 可與網路上各處的 API 互動。請參閱本指南,瞭解如何在指令碼中使用不同類型的 API。
連線至公開 API
使用 UrlFetch 服務直接發出 API 要求。
下列範例使用 GitHub API 搜尋提及「Apps Script」且有 100 顆以上星號的存放區。這項 API 要求不需要授權或 API 金鑰。
var query = '"Apps Script" stars:">=100"';
var url = 'https://api.github.com/search/repositories'
+ '?sort=stars'
+ '&q=' + encodeURIComponent(query);
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
Logger.log(response);
使用 OAuth 向服務提出要求
代表使用者執行的 API 通常需要授權,通常會使用 OAuth 通訊協定。Apps Script 不提供通訊協定的內建支援功能,但您可以透過開放原始碼程式庫執行 OAuth 流程,並在要求中傳送憑證:
- Apps Script 適用的 OAuth1: 與 OAuth 1.0 和 1.0a 相容。
- Apps Script 的 OAuth2: 與 OAuth2 相容。
使用服務帳戶進行驗證
如要從 Apps Script 呼叫 API,您可能會基於下列任何原因選擇使用服務帳戶驗證:
- 使用 Google Cloud API 提升成效
- 自動化和長時間執行的工作
- 提升安全性 (最低權限)
- 集中管理存取權
如要在 Apps Script 中使用服務帳戶,請參閱「使用服務帳戶以 Apps Script 專案身分進行驗證」。
連線至 Google Cloud 服務
您可以使用 ScriptApp.getIdentityToken() 方法,為有效使用者取得 OpenID Connect 身分識別權杖 (JSON Web Token 或 JWT)。您可以使用這個權杖向 Google Cloud 服務 (例如 Cloud Run) 進行驗證,前提是這些服務已設定為接受權杖。
詳情請參閱「連線至 Google Cloud 服務」。
使用 JSON
使用 JSON 物件與使用 XML 類似,但剖析或編碼 JSON 物件容易得多。
當 API 傳回原始 JSON 回應時,請使用 HTTPResponse.getContentText 方法存取 JSON 字串回應。擷取字串後,請使用 JSON.parse() 將其剖析為 JavaScript 物件。
// Make request to API and get response before this point.
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data.title);
同樣地,如要將 JavaScript 物件轉換為要求酬載的 JSON 字串,請使用 JSON.stringify()。
var data = {
'entry': {
'group': {
'title': 'Dog Skateboarding',
'description': 'My dog gets some serious air'
},
'keywords': 'dog, skateboard'
}
}
var payload = JSON.stringify(data);
// Make request to API with payload after this point.
剖析 XML
如果外部 API 針對要求傳回原始 XML 回應,請使用 HTTPResponse.getContentText() 方法存取 XML 回應。
// Make request to API and get response before this point.
var xml = response.getContentText();
var doc = XmlService.parse(xml);
向 API 提出 XML 要求時,請使用 XmlService 方法建構要傳送的 XML。
var root = XmlService.createElement('entry')
.setAttribute('keywords', 'dog, skateboard');
var group = XmlService.createElement('group')
.setAttribute('title', 'Dog Skateboarding')
.setAttribute('description', 'My dog gets some serious air');
root.addContent(group);
var document = XmlService.createDocument(root);
var payload = XmlService.getPrettyFormat().format(document);
// Make request to API with payload after this point.