Google Apps Script can interact with APIs from all over the web. This guide shows how to work with different types of APIs in your scripts.
Connect to public APIs
You can use the UrlFetch
service to make
API requests directly.
The following example uses the GitHub API to search for repositories with 100 or more stars that mention "Apps Script". This API request does not require authorization or an API key.
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);
Make requests to services with OAuth
APIs that act on behalf of a user usually require authorization, often using the OAuth protocol. Apps Script doesn't provide built-in support for the protocol, but there are open source libraries you can use to perform the OAuth flow and send the credentials with your requests:
- OAuth1 for Apps Script: Compatible with OAuth 1.0 and 1.0a.
- OAuth2 for Apps Script: Compatible with OAuth2.
Work with JSON
Working with JSON objects is similar to working with XML, except that parsing or encoding a JSON object is much easier.
If the API being requested returns a raw JSON response for a request, the JSON
string response can be accessed using the method
HTTPResponse.getContentText()
.
Once this string is retrieved, simply call JSON.parse()
on the string to get a
native object representation.
// Make request to API and get response before this point.
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data.title);
Likewise, to make a string representation of a JavaScript object in order to
make a request, use 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.
Parse XML
If an external API returns a raw XML response for a request, you can access the
XML response using the method
HTTPResponse.getContentText()
.
// Make request to API and get response before this point.
var xml = response.getContentText();
var doc = XmlService.parse(xml);
When making XML requests to an API, construct the XML to send by using
the XmlService
methods.
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.