Google Apps Script

External APIs

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.

Connecting to public APIs

Dozens of Google APIs are available in Apps Script, either as built-in services or advanced services. If you want to use a Google (or non-Google) API that isn't available as an Apps Script service, you can connect to the API's public HTTP interface through the URL Fetch service.

The following example makes a request to the YouTube API and returns a feed of videos that match the query skateboarding dog.

var url = 'https://gdata.youtube.com/feeds/api/videos?'
    + 'q=skateboarding+dog'
    + '&start-index=21'
    + '&max-results=10'
    + '&v=2';
var response = UrlFetchApp.fetch(url);
Logger.log(response);

Similarly, the following example uploads a video to YouTube.

var payload = 'XXXXX'; // Replace with raw video data.
var headers = {
    'GData-Version': '2',
    'Slug': 'dog-skateboarding.mpeg'
    // Add any other required parameters for the YouTube API.
};
var url = 'https://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
var options = {
    'method': 'post',
    'headers': headers,
    'payload': payload
};
var response = UrlFetchApp.fetch(url, options);

Information on how to handle the response variables from above is given later in this guide.

Interacting with SOAP services

A complete guide to working with SOAP services is provided in the guide for the SOAP service. The following is a brief example from the SOAP tutorial that demonstrates how to interact with a GeoIP SOAP service.

function determineCountryFromIP(ipAddress) {
  var wsdl = SoapService.wsdl(
      'http://www.webservicex.net/geoipservice.asmx?wsdl');
  var geoService = wsdl.getGeoIPService();
  var param = Xml.element('GetGeoIP', [
      Xml.attribute('xmlns', 'http://www.webservicex.net/''),
      Xml.element('IPAddress', [
          ipAddress
      ])
  ]);
  var result = geoService.GetGeoIP(param);
  return result.Envelope.Body.GetGeoIPResponse
      .GetGeoIPResult.CountryCode.Text;
}

Parsing XML

A complete guide to parsing XML is provided in the Parsing XML tutorial. Beginners getting started with parsing XML should read the tutorial first, as parsing XML can be difficult initially.

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 = Xml.parse(xml, true);
// Continue with the rest of the tutorial after this point.

When making XML requests to an API, construct the XML to send either by joining strings together, or by using the method Xml.parseJS(). This method takes a JavaScript object and returns an XML representation, which can make it easier to get an XML string.

var entry = {
    'entry': {
        'group': {
            'title': 'Dog Skateboarding',
            'description': 'My dog gets some serious air'
        },
        'keywords': 'dog, skateboard'
    }
}
var payload = Xml.parseJS(entry).toXmlString();
// Make request to API with payload after this point.

Working 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);
Browser.msgBox(data.title);

Likewise, to make a string representation of a JavaScript object in order to make a request, use JSON.stringify().

var data = {
    "title": "Dog Skateboarding",
    "description": "My dog gets some serious air"
}
var payload = JSON.stringify(data);
// Make request to API with payload after this point.

Making requests to services with OAuth

APIs that act on behalf of a user usually require authorization, often using the OAuth protocol. Beginners starting out with OAuth in Apps Script should first read the Twitter Approval Manager tutorial, which gives a complete introduction to making authorized requests to the Twitter API. Advanced users may find it faster to start with the following example, which makes an authorized request to fetch a user's tweets.

var consumerKey = 'XXXXX'; // Register your app with Twitter.
var consumerSecret = 'XXXXX'; // Register your app with Twitter.

var oauthConfig = UrlFetchApp.addOAuthService('twitter');
oauthConfig.setAccessTokenUrl(
    'http://api.twitter.com/oauth/access_token');
oauthConfig.setRequestTokenUrl(
    'http://api.twitter.com/oauth/request_token');
oauthConfig.setAuthorizationUrl(
    'http://api.twitter.com/oauth/authorize');
oauthConfig.setConsumerKey(consumerKey);
oauthConfig.setConsumerSecret(consumerSecret);

// "twitter" value must match the argument to "addOAuthService" above.
var options = {
    'oAuthServiceName' : 'twitter',
    'oAuthUseToken' : 'always'
};

var url = 'http://api.twitter.com/1.1/statuses/user_timeline.json';
var response = UrlFetchApp.fetch(url, options);
var tweets = JSON.parse(response.getContentText());

// Handle tweets after this point.

The OAuthConfig object and the options variable are where the bulk of the OAuth configuration happen. A script must configure an OAuth service, then instruct UrlFetchApp.fetch() to use that OAuth service.

Once set up, making requests via OAuth is almost completely transparent to a script, so long as the oAuthServiceName and oAuthUseToken parameters are provided in the options argument of UrlFetchApp.fetch().

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.