Skip to content

Instantly share code, notes, and snippets.

@mstraughan86
Last active November 3, 2017 07:57
Show Gist options
  • Save mstraughan86/337bd8615d60fdd48b6e0e058c5acfac to your computer and use it in GitHub Desktop.
Save mstraughan86/337bd8615d60fdd48b6e0e058c5acfac to your computer and use it in GitHub Desktop.
How to make Google API calls from inside Google Apps Scripts

How to make Google API calls from inside Google Apps Scripts: https://developers.google.com/sheets/api/quickstart/apps-script

Step 1: Create the script

  1. Open Google Drive in your web browser.
  2. Click New > More > Google Apps Script.
  3. If Google Apps Script isn't listed, you can install it by clicking the Connect more apps option instead. Search for "Google Apps Script" and click the +CONNECT button. Click the OK button in the popup, click the X icon to close the dialog, and repeat the step above.
  4. If you are presented with a welcome screen, click Blank Project.
  5. Replace the contents of the script editor with the code at the end of this gist.
  6. Click File > Save, name your project "Quickstart", and click OK.

Step 2: Turn on the Google Sheets API

  1. In the Apps Script editor, click Resources > Advanced Google Services.
  2. Locate Sheets API in the dialog and click the corresponding toggle, setting it to on.
  3. Click the Google API Console link.
  4. Enter "Sheets API" into the search box and click on the corresponding entry in the results.
  5. Click the Enable API button.
  6. Return to the Apps Script editor and click the OK button on the Advanced Google Services dialog.

Step 3: Run the sample

In the Apps Script editor, click Run > logNamesAndMajors. The first time you run the sample, it will prompt you to authorize access. Continue through the prompt windows and authorize access to the app. It will be unauthorized, which is OK. To view the script's output, click View > Logs.

Appendix: Google Apps Script:

/**
 * Creates a Sheets API service object and prints the names and majors of
 * students in a sample spreadsheet:
 *  https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 */
function logNamesAndMajors() {
  var spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
  var rangeName = 'Class Data!A2:E';
  var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;

  if (!values) {
    Logger.log('No data found.');
  } else {
    Logger.log('Name, Major:');
    for (var row = 0; row < values.length; row++) {
      // Print columns A and E, which correspond to indices 0 and 4.
      Logger.log(' - %s, %s', values[row][0], values[row][4]);
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment