Introduction to RESTful APIs and Web Services in Google Apps Script

Google Apps Script allows you to interact with external web services and APIs, enabling you to integrate your scripts with a wide range of online platforms and services. This chapter introduces RESTful APIs and demonstrates how to consume and interact with them using Google Apps Script.

What Are RESTful APIs?

  • REST (Representational State Transfer): An architectural style for designing networked applications.
  • API (Application Programming Interface): A set of rules and protocols for building and interacting with software applications.
  • RESTful API: An API that adheres to the REST principles, enabling communication between client and server over HTTP/HTTPS.

Key Concepts

  • Resources: Objects or representations of information that can be accessed via URLs.
  • HTTP Methods:
    • GET: Retrieve data from a resource.
    • POST: Create a new resource.
    • PUT: Update an existing resource.
    • DELETE: Delete a resource.
  • Status Codes: HTTP responses indicating the result of a request (e.g., 200 OK, 404 Not Found).

Making HTTP Requests in Google Apps Script

Google Apps Script provides the UrlFetchApp service to make HTTP requests to external APIs.

Basic GET Request

function getExample() {
var response = UrlFetchApp.fetch('https://api.example.com/data');
var content = response.getContentText();
var jsonData = JSON.parse(content);
Logger.log(jsonData);
}

Handling HTTP Methods

  • GET Request: Fetch data.
  • POST Request: Send data to the server.

Making a POST Request

function postExample() {
var url = 'https://api.example.com/data';
var payload = {
'name': 'John Doe',
'email': 'john.doe@example.com'
};

var options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload)
};

var response = UrlFetchApp.fetch(url, options);
var content = response.getContentText();
Logger.log(content);
}

Setting Request Headers

function requestWithHeaders() {
var url = 'https://api.example.com/data';

var options = {
'headers': {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Custom-Header': 'CustomValue'
}
};

var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}

Parsing API Responses

API responses are often in JSON format. You can parse JSON strings into JavaScript objects.

Parsing JSON

var jsonString = '{"name": "John", "age": 30}';
var jsonObject = JSON.parse(jsonString);
Logger.log(jsonObject.name); // Output: John

Handling Errors

function fetchData() {
try {
var response = UrlFetchApp.fetch('https://api.example.com/data');
if (response.getResponseCode() === 200) {
var data = JSON.parse(response.getContentText());
// Process data
} else {
Logger.log('Error: ' + response.getResponseCode());
}
} catch (e) {
Logger.log('Exception: ' + e.message);
}
}

Authenticating API Requests

Many APIs require authentication. Common methods include API keys, OAuth tokens, or basic authentication.

Using API Keys

function apiKeyExample() {
var url = 'https://api.example.com/data?api_key=YOUR_API_KEY';
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}

OAuth 2.0 Authentication

  • Use OAuth services provided by Google Apps Script or external libraries.
  • For built-in services, you may need to enable them in your script’s settings.

Example with OAuth

function oauthExample() {
var service = getOAuthService();
if (service.hasAccess()) {
var url = 'https://api.example.com/data';
var options = {
'headers': {
'Authorization': 'Bearer ' + service.getAccessToken()
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
} else {
Logger.log('Authorization required.');
}
}

function getOAuthService() {
return OAuth2.createService('exampleService')
.setAuthorizationBaseUrl('https://accounts.example.com/o/oauth2/auth')
.setTokenUrl('https://accounts.example.com/o/oauth2/token')
.setClientId('YOUR_CLIENT_ID')
.setClientSecret('YOUR_CLIENT_SECRET')
.setCallbackFunction('authCallback')
.setScope('https://www.example.com/auth/scope');
}

function authCallback(request) {
var service = getOAuthService();
var isAuthorized = service.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success!');
} else {
return HtmlService.createHtmlOutput('Denied.');
}
}

Consuming RESTful APIs: Practical Examples

Example 1: Fetching Weather Data

function getWeather() {
var apiKey = 'YOUR_API_KEY';
var city = 'London';
var url = 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=' + apiKey;

var response = UrlFetchApp.fetch(url);
var data = JSON.parse(response.getContentText());

Logger.log('Temperature: ' + data.main.temp);
}

Example 2: Creating a New Issue on GitHub

function createGitHubIssue() {
var url = 'https://api.github.com/repos/owner/repo/issues';
var payload = {
'title': 'Issue Title',
'body': 'Issue description.'
};

var options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload),
'headers': {
'Authorization': 'token YOUR_GITHUB_TOKEN',
'User-Agent': 'Google Apps Script'
}
};

var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}

Best Practices for Working with APIs

  • Read API Documentation: Understand the API’s endpoints, parameters, authentication, and rate limits.
  • Handle Rate Limits: Implement delays or check headers for rate limit information.
  • Secure API Keys: Do not hardcode API keys; store them securely using PropertiesService.
  • Error Handling: Anticipate and handle different types of errors gracefully.
  • Testing: Test API calls with tools like Postman before integrating them into your script.

Exercises

Exercise 1

Write a function that retrieves a list of public repositories for a given GitHub username using the GitHub API. Log the names of the repositories.

Exercise 2

Explain how you can securely store and retrieve API keys in Google Apps Script.

Exercise 3

Create a function that sends a POST request to a mock API endpoint https://jsonplaceholder.typicode.com/posts with a JSON payload containing a title and body. Log the response from the server.


Multiple Choice Questions

Question 1: Which service in Google Apps Script is used to make HTTP requests to external APIs?

A) HTTPService

B) UrlFetchApp

C) ExternalRequestApp

D) WebServiceApp

Answer: B) UrlFetchApp


Question 2: What HTTP method is typically used to retrieve data from a RESTful API?

A) POST

B) PUT

C) GET

D) DELETE

Answer: C) GET


Question 3: How do you parse a JSON string into a JavaScript object in Google Apps Script?

A) JSON.parseString()

B) Utilities.jsonParse()

C) JSON.parse()

D) String.toJSON()

Answer: C) JSON.parse()


Question 4: Which of the following is a best practice when working with API keys in your script?

A) Hardcode them directly into your code.

B) Store them in a publicly shared Google Sheet.

C) Store them using PropertiesService.

D) Email them to yourself for safekeeping.

Answer: C) Store them using PropertiesService.


Question 5: What HTTP status code indicates a successful GET request?

A) 200

B) 404

C) 500

D) 301

Answer: A) 200


Short Answers to Exercises

Exercise 1 Solution

function listGitHubRepos() {
var username = 'GITHUB_USERNAME';
var url = 'https://api.github.com/users/' + username + '/repos';
var options = {
'headers': {
'User-Agent': 'Google Apps Script'
}
};

var response = UrlFetchApp.fetch(url, options);
var repos = JSON.parse(response.getContentText());

repos.forEach(function(repo) {
Logger.log(repo.name);
});
}

Exercise 2 Solution

Explanation:

  • Use PropertiesService to store API keys securely.
  • Store the API key:javascriptCopy codefunction setApiKey() { var properties = PropertiesService.getScriptProperties(); properties.setProperty('API_KEY', 'YOUR_API_KEY'); }
  • Retrieve the API key:javascriptCopy codefunction getApiKey() { var properties = PropertiesService.getScriptProperties(); return properties.getProperty('API_KEY'); }
  • This approach prevents exposing the API key in your codebase.

Exercise 3 Solution

function postToJsonPlaceholder() {
var url = 'https://jsonplaceholder.typicode.com/posts';
var payload = {
'title': 'foo',
'body': 'bar',
'userId': 1
};

var options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload)
};

var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}

By understanding RESTful APIs and how to interact with them using Google Apps Script, you can greatly expand the capabilities of your scripts. Whether you’re integrating with third-party services, fetching data, or automating workflows, mastering API interactions is a valuable skill in your Google Apps Script toolkit.