[{
"type": "thumb-down",
"id": "missingTheInformationINeed",
"label":"Missing the information I need"
},{
"type": "thumb-down",
"id": "tooComplicatedTooManySteps",
"label":"Too complicated / too many steps"
},{
"type": "thumb-down",
"id": "outOfDate",
"label":"Out of date"
},{
"type": "thumb-down",
"id": "samplesCodeIssue",
"label":"Samples/Code issue"
},{
"type": "thumb-down",
"id": "otherDown",
"label":"Other"
}]
[{
"type": "thumb-up",
"id": "easyToUnderstand",
"label":"Easy to understand"
},{
"type": "thumb-up",
"id": "solvedMyProblem",
"label":"Solved my problem"
},{
"type": "thumb-up",
"id": "otherUp",
"label":"Other"
}]
Node.js Quickstart
Complete the steps described in the rest of this page to create a simple Node.js
command-line application that makes requests to the Google Apps Script API.
Prerequisites
To run this quickstart, you need the following prerequisites:
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/script.projects'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Apps Script API.
authorize(JSON.parse(content), callAppsScript);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Creates a new script project, upload a file, and log the script's URL.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function callAppsScript(auth) {
const script = google.script({version: 'v1', auth});
script.projects.create({
resource: {
title: 'My Script',
},
}, (err, res) => {
if (err) return console.log(`The API create method returned an error: ${err}`);
script.projects.updateContent({
scriptId: res.data.scriptId,
auth,
resource: {
files: [{
name: 'hello',
type: 'SERVER_JS',
source: 'function helloWorld() {\n console.log("Hello, world!");\n}',
}, {
name: 'appsscript',
type: 'JSON',
source: '{\"timeZone\":\"America/New_York\",\"exceptionLogging\":' +
'\"CLOUD\"}',
}],
},
}, {}, (err, res) => {
if (err) return console.log(`The API updateContent method returned an error: ${err}`);
console.log(`https://script.google.com/d/${res.data.scriptId}/edit`);
});
});
}
Step 4: Run the sample
Run the sample using the following command:
node .
The first time you run the sample, it will prompt you to authorize access:
Browse to the provided URL in your web browser.
If you are not already logged into your Google account, you will be
prompted to log in. If you are logged into multiple Google accounts, you
will be asked to select one account to use for the authorization.
If you don't have a browser on the machine running the code, and you've
selected "Desktop app" when creating the OAuth client, you can browse to the
URL provided on another machine, and then copy the authorization code back to
the running sample.
Click the Accept button.
Copy the code you're given, paste it into the command-line prompt, and press
Enter.
Notes
Authorization information is stored on the file system, so subsequent
executions will not prompt for authorization.
The authorization flow in this example is designed for a command line
application. For information on how to perform authorization in other contexts,
see the
Authorizing and Authenticating.
section of the library's README.
This section describes some common issues that you may encounter while
attempting to run this quickstart and suggests possible solutions.
This app isn't verified.
The OAuth consent screen that is presented to the user may show the warning
"This app isn't verified" if it is requesting scopes that provide access to
sensitive user data. These applications must eventually go through the
verification process to
remove that warning and other limitations. During the development phase you can
continue past this warning by clicking
Advanced > Go to {Project Name} (unsafe).
[{
"type": "thumb-down",
"id": "missingTheInformationINeed",
"label":"Missing the information I need"
},{
"type": "thumb-down",
"id": "tooComplicatedTooManySteps",
"label":"Too complicated / too many steps"
},{
"type": "thumb-down",
"id": "outOfDate",
"label":"Out of date"
},{
"type": "thumb-down",
"id": "samplesCodeIssue",
"label":"Samples/Code issue"
},{
"type": "thumb-down",
"id": "otherDown",
"label":"Other"
}]
[{
"type": "thumb-up",
"id": "easyToUnderstand",
"label":"Easy to understand"
},{
"type": "thumb-up",
"id": "solvedMyProblem",
"label":"Solved my problem"
},{
"type": "thumb-up",
"id": "otherUp",
"label":"Other"
}]