Google Apps Script

Class UrlFetchApp

Fetch resources and communicate with other hosts over the Internet. This service allows scripts to communicate with other applications or access other resources on the web by fetching URLs. A script can use the URL Fetch service to issue HTTP and HTTPS requests and receive responses. The URL Fetch service uses Google's network infrastructure for efficiency and scaling purposes.

See also

Methods

MethodReturn typeBrief description
addOAuthService(serviceName)OAuthConfigRegisters the given service name with the OAuth configuration and returns the newly created OAuthConfig object for an OAuth service with the given name.
fetch(url)HTTPResponseMakes a request to fetch a URL.
fetch(url, params)HTTPResponseMakes a request to fetch a URL using optional advanced parameters.
getRequest(url)ObjectReturns the request that would be made if the operation was invoked.
getRequest(url, params)ObjectReturns the request that would be made if the operation were invoked.
removeOAuthService(serviceName)voidRemoves the OAuthConfig for the given service name.

Detailed documentation

addOAuthService(serviceName)

Registers the given service name with the OAuth configuration and returns the newly created OAuthConfig object for an OAuth service with the given name.

 
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(ScriptProperties.getProperty("twitterConsumerKey"));
 oAuthConfig.setConsumerSecret(ScriptProperties.getProperty("twitterConsumerSecret"));
 

Parameters

NameTypeDescription
serviceNameStringidentifier for the service; used for the oAuthServiceName field in calls to fetch(url, params)

Return

OAuthConfig — a configuration object


fetch(url)

Makes a request to fetch a URL. This works over HTTP as well as HTTPS.

 
// The code below logs the HTML code of the Google home page.
 var response = UrlFetchApp.fetch("http://www.google.com/");
 Logger.log(response.getContentText());
 

Parameters

NameTypeDescription
urlStringthe URL to fetch

Return

HTTPResponse — the HTTP response data


fetch(url, params)

Makes a request to fetch a URL using optional advanced parameters. This works over HTTP as well as HTTPS.

 
// The code below logs the HTML code of the Google home page.
 var response = UrlFetchApp.fetch("http://www.google.com/");
 Logger.log(response.getContentText());
 
 
// This sample pulls in your tweets from Twitter and puts them in a spreadsheet.
 //
 //  First: set up Script Properties "twitterConsumerKey" and
 // "twitterConsumerSecret" with values provided to you by Twitter.

 var fields = {'in_reply_to_screen_name':true,'created_at':true,'text':true};

 function tweet() {
   // Setup OAuthServiceConfig
   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(ScriptProperties.getProperty("twitterConsumerKey"));
   oAuthConfig.setConsumerSecret(ScriptProperties.getProperty("twitterConsumerSecret"));

   // Setup optional parameters to point request at OAuthConfigService.  The "twitter"
   // value matches the argument to "addOAuthService" above.
   var options =
     {
       "oAuthServiceName" : "twitter",
       "oAuthUseToken" : "always"
     };

   var result = UrlFetchApp.fetch("http://api.twitter.com/1.1/statuses/user_timeline.json",
       options);
   var o  = Utilities.jsonParse(result.getContentText());
   var doc = SpreadsheetApp.getActiveSpreadsheet();
   var cell = doc.getRange('a1');
   var index = 0;
   for (var i in o) {
     var row = o[i];
     var col = 0;
     for (var j in row) {
       if (fields[j]) {
         cell.offset(index, col).setValue(row[j]);
         col++;
       }
     }
     index++;
   }
 }
 
 
// This sample sends POST payload data in the style of an HTML form, including
 // a file.

 function sendHttpPost() {

   // Download a file now (GET), so we can upload it in the HTTP POST below.
   var response = UrlFetchApp.fetch("http://example.com/image_to_download.jpg");
   var fileBlob = response.getBlob();

   var payload =
   {
     "fieldOne" : "value for field one",
     "fieldTwo" : "value for field two",
     "fileAttachment": fileBlob
   };

   // Because payload is a JavaScript object, it will be interpreted as
   // an HTML form. (We do not need to specify contentType; it will
   // automatically default to either 'application/x-www-form-urlencoded'
   // or 'multipart/form-data')

   var options =
   {
     "method" : "post",
     "payload" : payload
   };

   UrlFetchApp.fetch("http://example.com/upload_form.cgi", options);
 }
 

Parameters

NameTypeDescription
urlStringthe URL to fetch
paramsObjectoptional JavaScript object specifying advanced parameters as defined below

Advanced parameters

NameTypeDescription
contentTypeStringthe content type (defaults to 'application/x-www-form-urlencoded'). Another example of content type is 'application/xml; charset=utf-8'.
headersObjecta JavaScript key/value map of HTTP headers for the request
methodStringthe HTTP method for the request: 'post', 'get', 'put', 'delete', etc. The default is 'get'.
payloadStringthe payload (e.g. POST body) for the request. Certain HTTP methods (e.g. GET) do not have any payload. It can be a String, a byte array, or a JavaScript key/value map. See the examples for more detail.
useIntranetBooleanthis instructs fetch to resolve the specified URL within the intranet linked to your domain through SDC
validateHttpsCertificatesBooleanif this is set to false, the fetch will ignore any invalid certificates for HTTPS requests. The default is true.
followRedirectsBooleanif this is set to false, the fetch not automatically follow HTTP redirects; it will return the original HTTP response. The default is true.
oAuthServiceNameStringthe string identifier for an OAuth service. See example.
oAuthUseTokenStringa string indicating OAuth token usage policy ("always", "if_available", "never", "require_present").
  • always: always send the OAuth Authorization header, with every request
  • if_available: send the OAuth Authorization header if an OAuth token has been set
  • never: never send the OAuth Authorization header, regardless of an OAuth token having been set or not
  • require_present: send an OAuth Authorization header only if the service at the URL you're requesting requires one
See example.
muteHttpExceptionsBooleanif this is set to true, the fetch will not throw an exception if the response code indicates failure, and will instead return the HTTPResponse (default: false)
escapingBooleanif this is set to false, reserved characters in the URL will not be escaped (default: true)

Return

HTTPResponse — the http response data


getRequest(url)

Returns the request that would be made if the operation was invoked. This method does not actually issue the request.

 
// The code below logs the value for every key of the returned map.
 var response = UrlFetchApp.getRequest("http://www.google.com/");
 for(i in response) {
   Logger.log(i + ": " + response[i]);
 }
 

Parameters

NameTypeDescription
urlStringthe URL to look up

Return

Object — a map of Field Name to Value. The map has at least the following keys: url, method, contentType, useIntranet, payload, headers, oAuthServiceName, oAuthUseToken.


getRequest(url, params)

Returns the request that would be made if the operation were invoked. This method does not actually issue the request.

 
// The code below logs the value for every key of the returned map.
 var fields = {'in_reply_to_screen_name': true, 'created_at': true, 'text': true};

 function tweet() {
   // Setup OAuthServiceConfig
   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(ScriptProperties.getProperty("twitterConsumerKey"));
   oAuthConfig.setConsumerSecret(ScriptProperties.getProperty("twitterConsumerSecret"));

   // Setup optional parameters to point request at OAuthConfigService.  The "twitter"
   // value matches the argument to "addOAuthService" above.
   var options =
     {
       "oAuthServiceName" : "twitter",
       "oAuthUseToken" : "always"
     };

   var result = UrlFetchApp.getRequest("http://api.twitter.com/1.1/statuses/user_timeline.json",
       options);
   for(i in result) {
     Logger.log(i + ": " + result[i]);
   }
 }
 

Parameters

NameTypeDescription
urlStringthe url to look up
paramsObjectoptional JavaScript object specifying advanced parameters as defined below

Advanced parameters

NameTypeDescription
contentTypeStringthe content type (defaults to 'application/x-www-form-urlencoded'). Another example of content type is 'application/xml; charset=utf-8'.
headersObjecta JavaScript key/value map of HTTP headers for the request
methodStringthe HTTP method for the request: 'post', 'get', 'put', 'delete', etc. The default is 'get'.
payloadStringthe payload (e.g. POST body) for the request. Certain HTTP methods (e.g. GET) do not have any payload. It can be a String, a byte array, or a JavaScript key/value map.
useIntranetBooleanthis instructs fetch to resolve the specified URL within the intranet linked to your domain through SDC
validateHttpsCertificatesBooleanif this is set to false, the fetch will ignore any invalid certificates for HTTPS requests. The default is true.
followRedirectsBooleanif this is set to false, the fetch not automatically follow HTTP redirects; it will return the original HTTP response. The default is true.
oAuthServiceNameStringthe string identifier for an OAuth service. See example.
oAuthUseTokenStringa string indicating OAuth token usage policy ("always", "if_available", "never", "require_present").
  • always: always send the OAuth Authorization header, with every request
  • if_available: send the OAuth Authorization header if an OAuth token has been set
  • never: never send the OAuth Authorization header, regardless of an OAuth token having been set or not
  • require_present: send an OAuth Authorization header only if the service at the URL you're requesting requires one
See example.
muteHttpExceptionsBooleanif this is set to true, the fetch will not throw an exception if the response code indicates failure, and will instead return the HTTPResponse (default: false)
escapingBooleanif this is set to false, reserved characters in the URL will not be escaped (default: true)

Return

Object — a map of Field Name to Value. The map has at least the following keys: url, method, contentType, useIntranet, payload, headers, oAuthServiceName, oAuthUseToken.


removeOAuthService(serviceName)

Removes the OAuthConfig for the given service name.

 
var oAuthConfig = UrlFetchApp.addOAuthService("twitter");
 // some useful code here...
 UrlFetchApp.removeOAuthService(oAuthConfig.getServiceName());
 

Parameters

NameTypeDescription
serviceNameStringidentifier for the service.

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.