外部 API
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
Google Apps 脚本可以与整个网络中的 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 脚本不提供对该协议的内置支持,但您可以使用一些开源库来执行 OAuth 流程并随请求发送凭据:
使用 JSON
处理 JSON 对象与处理 XML 类似,只不过解析或编码 JSON 对象要容易得多。
如果所请求的 API 针对请求返回原始 JSON 响应,则可以使用 HTTPResponse.getContentText()
方法访问 JSON 字符串响应。检索到此字符串后,只需对该字符串调用 JSON.parse()
即可获得原生对象表示形式。
// 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.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.
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-31。
[null,null,["最后更新时间 (UTC):2025-08-31。"],[[["\u003cp\u003eGoogle Apps Script enables interaction with various web APIs using the \u003ccode\u003eUrlFetch\u003c/code\u003e service for direct API requests.\u003c/p\u003e\n"],["\u003cp\u003eFor user-centric APIs requiring authorization, utilize open-source libraries like OAuth1 or OAuth2 for Apps Script to manage the OAuth flow.\u003c/p\u003e\n"],["\u003cp\u003eApps Script simplifies working with JSON responses through \u003ccode\u003eJSON.parse()\u003c/code\u003e for converting raw JSON into native objects and \u003ccode\u003eJSON.stringify()\u003c/code\u003e for the reverse.\u003c/p\u003e\n"],["\u003cp\u003eHandle XML responses from APIs using \u003ccode\u003eHTTPResponse.getContentText()\u003c/code\u003e and the \u003ccode\u003eXmlService\u003c/code\u003e for parsing and constructing XML data.\u003c/p\u003e\n"]]],[],null,["# External APIs\n\nGoogle Apps Script can interact with APIs from all over the web. This guide\nshows how to work with different types of APIs in your scripts.\n\nConnect to public APIs\n----------------------\n\nYou can use the [`UrlFetch`](/apps-script/reference/url-fetch) service to make\nAPI requests directly.\n\nThe following example uses the\n[GitHub API](https://developer.github.com/v3/search/#search-repositories) to\nsearch for repositories with 100 or more stars that mention \"Apps Script\".\nThis API request does not require authorization or an API key. \n\n var query = '\"Apps Script\" stars:\"\u003e=100\"';\n var url = 'https://api.github.com/search/repositories'\n + '?sort=stars'\n + '&q=' + encodeURIComponent(query);\n\n var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});\n Logger.log(response);\n\nMake requests to services with OAuth\n------------------------------------\n\nAPIs that act on behalf of a user usually require authorization, often using the\n[OAuth protocol](http://oauth.net/). Apps Script doesn't provide built-in\nsupport for the protocol, but there are open source libraries you can use to\nperform the OAuth flow and send the credentials with your requests:\n\n- [OAuth1 for Apps Script](https://github.com/googlesamples/apps-script-oauth1): Compatible with OAuth 1.0 and 1.0a.\n- [OAuth2 for Apps Script](https://github.com/googlesamples/apps-script-oauth2): Compatible with OAuth2.\n\nWork with JSON\n--------------\n\nWorking with JSON objects is similar to working with XML, except that parsing or\nencoding a JSON object is much easier.\n\nIf the API being requested returns a raw JSON response for a request, the JSON\nstring response can be accessed using the method\n[`HTTPResponse.getContentText()`](/apps-script/reference/url-fetch/http-response#getContentText()).\nOnce this string is retrieved, simply call `JSON.parse()` on the string to get a\nnative object representation. \n\n // Make request to API and get response before this point.\n var json = response.getContentText();\n var data = JSON.parse(json);\n Logger.log(data.title);\n\nLikewise, to make a string representation of a JavaScript object in order to\nmake a request, use `JSON.stringify()`. \n\n var data = {\n 'entry': {\n 'group': {\n 'title': 'Dog Skateboarding',\n 'description': 'My dog gets some serious air'\n },\n 'keywords': 'dog, skateboard'\n }\n }\n var payload = JSON.stringify(data);\n // Make request to API with payload after this point.\n\nParse XML\n---------\n\nIf an external API returns a raw XML response for a request, you can access the\nXML response using the method\n[`HTTPResponse.getContentText()`](/apps-script/reference/url-fetch/http-response#getContentText()). \n\n // Make request to API and get response before this point.\n var xml = response.getContentText();\n var doc = XmlService.parse(xml);\n\nWhen making XML requests to an API, construct the XML to send by using\nthe [`XmlService`](/apps-script/reference/xml-service/xml-service) methods. \n\n var root = XmlService.createElement('entry')\n .setAttribute('keywords', 'dog, skateboard');\n var group = XmlService.createElement('group')\n .setAttribute('title', 'Dog Skateboarding');\n .setAttribute('description', 'My dog gets some serious air');\n root.addContent(group);\n var document = XmlService.createDocument(root);\n var payload = XmlService.getPrettyFormat().format(document);\n // Make request to API with payload after this point."]]