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
Method | Return type | Brief description |
---|---|---|
addOAuthService(serviceName) | OAuthConfig | Registers 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) | HTTPResponse | Makes a request to fetch a URL. |
fetch(url, params) | HTTPResponse | Makes a request to fetch a URL using optional advanced parameters. |
getRequest(url) | Object | Returns the request that would be made if the operation was invoked. |
getRequest(url, params) | Object | Returns the request that would be made if the operation were invoked. |
removeOAuthService(serviceName) | void | Removes 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("https://api.twitter.com/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oAuthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oAuthConfig.setConsumerKey(ScriptProperties.getProperty("twitterConsumerKey"));
oAuthConfig.setConsumerSecret(ScriptProperties.getProperty("twitterConsumerSecret"));
Parameters
Name | Type | Description |
---|---|---|
serviceName | String | identifier 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
Name | Type | Description |
---|---|---|
url | String | the 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("https://api.twitter.com/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oAuthConfig.setAuthorizationUrl("https://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("https://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
Name | Type | Description |
---|---|---|
url | String | the URL to fetch |
params | Object | optional JavaScript object specifying advanced parameters as defined below |
Advanced parameters
Name | Type | Description |
---|---|---|
contentType | String | the content type (defaults to 'application/x-www-form-urlencoded'). Another example of content type is 'application/xml; charset=utf-8'. |
headers | Object | a JavaScript key/value map of HTTP headers for the request |
method | String | the HTTP method for the request: 'post', 'get', 'put', 'delete', etc. The default is 'get'. |
payload | String | the 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. |
useIntranet | Boolean | this instructs fetch to resolve the specified URL within the intranet linked to your domain through SDC |
validateHttpsCertificates | Boolean | if this is set to false, the fetch will ignore any invalid certificates for HTTPS requests. The default is true. |
followRedirects | Boolean | if this is set to false, the fetch not automatically follow HTTP redirects; it will return the original HTTP response. The default is true. |
oAuthServiceName | String | the string identifier for an OAuth service. See example. |
oAuthUseToken | String | a string indicating OAuth token usage policy
("always", "if_available", "never", "require_present").
|
muteHttpExceptions | Boolean | if 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 ) |
escaping | Boolean | if 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
Name | Type | Description |
---|---|---|
url | String | the 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("https://api.twitter.com/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oAuthConfig.setAuthorizationUrl("https://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("https://api.twitter.com/1.1/statuses/user_timeline.json",
options);
for(i in result) {
Logger.log(i + ": " + result[i]);
}
}
Parameters
Name | Type | Description |
---|---|---|
url | String | the url to look up |
params | Object | optional JavaScript object specifying advanced parameters as defined below |
Advanced parameters
Name | Type | Description |
---|---|---|
contentType | String | the content type (defaults to 'application/x-www-form-urlencoded'). Another example of content type is 'application/xml; charset=utf-8'. |
headers | Object | a JavaScript key/value map of HTTP headers for the request |
method | String | the HTTP method for the request: 'post', 'get', 'put', 'delete', etc. The default is 'get'. |
payload | String | the 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. |
useIntranet | Boolean | this instructs fetch to resolve the specified URL within the intranet linked to your domain through SDC |
validateHttpsCertificates | Boolean | if this is set to false, the fetch will ignore any invalid certificates for HTTPS requests. The default is true. |
followRedirects | Boolean | if this is set to false, the fetch not automatically follow HTTP redirects; it will return the original HTTP response. The default is true. |
oAuthServiceName | String | the string identifier for an OAuth service. See example. |
oAuthUseToken | String | a string indicating OAuth token usage policy
("always", "if_available", "never", "require_present").
|
muteHttpExceptions | Boolean | if 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 ) |
escaping | Boolean | if 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
Name | Type | Description |
---|---|---|
serviceName | String | identifier for the service. |