Giter Club home page Giter Club logo

node-samples's Introduction

Node.js samples for Google Workspace APIs docs

API Quickstart Snippets
Apps Script Link ---
Calendar Link Link
Classroom Link Link
Drive V3 Link Link
Gmail Link Link
Sheets Link Link
Slides Link Link
Tasks Link ---

Sample Types

Quickstarts

In about five minutes, you'll have a simple Node.js command-line application that makes requests to a Google Workspace API.

Guides

Learn how to use functions within an API, such as creating a new Google Slide to adding values to a Google Spreadsheet.

Other APIs

Admin SDK

Setup

  1. Install Node.js v6.4.0 or greater.
  2. Clone this repository.
  3. Follow the folder README instructions to run and test samples.

Run Snippet Tests

Create a Service Account

Before running tests, create a service account and download application_credentials.json in this directory.

To create a service account, follow these steps:

  1. Navigate to the Google Cloud Console API Dashboard
  2. Enable APIs for products you'd like to test snippets for like Slides or Drive.
  3. Create a service account key under Credentials.
  4. After creating a new JSON Service account key without a role, rename the downloaded file to application_credentials.json and move the file to this directory.

Run tests

In any snippet directory, npm run test.

Lint

Install and run ESLint. Example:

npm run lint apps-script/**/*.js

Some IDEs (like VS Code) will detect these lint errors within the editor.

Node.js Client Library

Google Workspace APIs use the Google API Node.js client library.

Contributing

Contributions welcome! See the Contributing Guide.

node-samples's People

Contributors

anuraggoogler avatar asrivas avatar assafshemesh avatar cdgugler avatar cschalk-goog avatar dependabot[bot] avatar evil-shrike avatar exter-dg avatar googleworkspace-bot avatar grant avatar ishaanrawat avatar iwin2471 avatar jamesor avatar jmdobry avatar jpoehnelt avatar jsmeredith avatar max-mathieu avatar maxim-mazurok avatar partman7 avatar rajeshgogo avatar randombrainstormer avatar renovate[bot] avatar sofisl avatar soheilv avatar sqrrrl avatar vinay-google avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-samples's Issues

[nit] The quickstarts often refer to `quickstart.js`, but actual samples are called `index.js`

When viewing a quickstart (for example: https://developers.google.com/calendar/quickstart/nodejs) the dynamically included code snippet shows the filename (index.js). I did a double-take initially when going through the quickstart because I copied the code and called my local file index.js, then saw the final command in the quickstart as

node quickstart.js

I quickly realized my error, but did feel a little led astray.

It's a nit, but I recommend we call the sample file quickstart.js rather than index.js so it shows up in the docs consistently.

Provide examples that not use env variables

In order to make examples robust and more useful please consider adding examples that shows how to use library without providing magic env variables, but using options to provide credentials, for example, and so on.

Generated URL from quickstart guide throws a 404 error

Expected Behavior

That the page would load and provide me with the code to input back into the js sample script

Actual Behavior

The requested URL was not found on this server. That’s all we know.

Steps to Reproduce the Problem

I simply followed the quickstart guide. I've also attempted deleting my OAuth credentials and starting again.

Specifications

  • Node version (node -v)
  • OS (Mac/Linux/Windows)

rgb is taking too much time

Is there a way to use hex notation or even decimal rgb notation instead of rgb arithmetic notation with conditional formatting?
None of the online converters have RGB arithmetic notation, Google sheets only shows the hex value if you select custom. It would be a lot easier to just have it in hex so I can just copy the colors from google sheets and not do lookups or conversions.

So far I tried hex and decimal rgb and neither worked.
Invalid value at 'requests[3].add_conditional_format_rule.rule.boolean_rule.format.background_color' (type.googleapis.com/google.type.Color), "#ffff00"

Thanks for any help

The API returned an error: Not Authorized to access this resource/api

Expected Behavior

Lists the first 10 users in the domain.

Actual Behavior

Outputs

Authorize this app by visiting this url: https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fadmin.directory.user&response_type=code&client_id=1025492374039-7btb479dh06fcqgh5ckuge56av0rfin5.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob
Enter the code from that page here: 4/QQC1oHz9949l53WSHoXEUGtgqEfXYw0Bu-TM-9s 41EnUdX0EZq6FH8
Token stored to token.json
The API returned an error: Not Authorized to access this resource/api

Steps to Reproduce the Problem

Specifications

  • Node version (node -v) v8.11.4
  • OS (Mac/Linux/Windows) Windows 10

Homebridge

Expected Behavior

Actual Behavior

events.js:167
throw er; // Unhandled 'error' event
^

Error: listen EADDRINUSE :::51826
at Server.setupListenHandle [as _listen2] (net.js:1286:14)
at listenInCluster (net.js:1334:12)
at Server.listen (net.js:1421:7)
at EventedHTTPServer.listen (/usr/local/lib/node_modules/homebridge/node_modules/hap-nodejs/lib/util/eventedhttp.js:60:19)
at HAPServer.listen (/usr/local/lib/node_modules/homebridge/node_modules/hap-nodejs/lib/HAPServer.js:158:20)
at Bridge.Accessory.publish (/usr/local/lib/node_modules/homebridge/node_modules/hap-nodejs/lib/Accessory.js:607:16)
at Server._publish (/usr/local/lib/node_modules/homebridge/lib/server.js:128:16)
at Server.run (/usr/local/lib/node_modules/homebridge/lib/server.js:97:10)
at module.exports (/usr/local/lib/node_modules/homebridge/lib/cli.js:45:10)
at Object. (/usr/local/lib/node_modules/homebridge/bin/homebridge:17:22)
Emitted 'error' event at:
at emitErrorNT (net.js:1313:8)
at process._tickCallback (internal/process/next_tick.js:63:19)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:11)
at startup (internal/bootstrap/node.js:285:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)

Steps to Reproduce the Problem

Specifications

  • Node version (node -v)
  • OS (Mac/Linux/Windows)

Google Sheets API v4 not generating authorization code

Firebase Callable Function with googleapis and JWT: google.options({ auth: jwt });

My question

Expected Behavior

sheets.spreadsheets.values.get(request, (err, response) => {
var rows = response.values;
//Expected: rows.length > 0

Actual Behavior

TypeError: Cannot read property 'length' of undefined
at sheets.spreadsheets.values.get.err (/user_code/index.js:71:17)
at createAPIRequestAsync.then.r (/user_code/node_modules/googleapis/node_modules/googleapis-common/build/src/apirequest.js:49:53)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

Steps to Reproduce the Problem

  1. Generate Admin Service Account Key .json file
  2. Make a clone (save on My Drive) of the Example Spreadsheet:
    https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
  3. Obtain "client_email" from Admin Service Account Key .json file and share a new spreadsheet with this specific user.
  4. Use code from index.js: Firebase Callable Function with JWT Authentication and Google Sheets v4 API

Specifications

  • Node version (node -v) v8.9.4
  • OS (Mac/Linux/Windows) MacOS High Sierra 10.13.4 (17E199)

Not able to create new spreadsheets from Node.JS using Google Sheets API v4

Expected Behavior

Spreadsheet should get created

Actual Behavior

No spreadsheet is getting created

Steps to Reproduce the Problem

Execute the below code and refer to create new spreadsheet function

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/spreadsheets.readonly'];
// 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 Sheets API.
  authorize(JSON.parse(content), listMajors);
});

/**
 * 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 getNewToken(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 getNewToken(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 while trying to retrieve 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) console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Prints the names and majors of students in a sample spreadsheet:
 * @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 * @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
 */
function listMajors(auth) {
  const sheets = google.sheets({version: 'v4', auth});
  sheets.spreadsheets.values.get({
    spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
    range: 'Class Data!A2:E',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const rows = res.data.values;
    if (rows.length) {
      console.log('Name, Major:');
      // Print columns A and E, which correspond to indices 0 and 4.
      rows.map((row) => {
        console.log(`${row[0]}, ${row[4]}`);
      });
    } else {
      console.log('No data found.');
    }
  });
}


function createNewSpreadSheet(auth) {
	  const sheets = google.sheets({version: 'v4', auth});
  const resource = {
  properties: {
    title:'SampleSheet'
  },
};
sheets.sheetsService.spreadsheets.create({
  resource,
  fields: 'spreadsheetId',
}, (err, spreadsheet) =>{
  if (err) {
    // Handle error.
    console.log(err);
  } else {
    console.log(`Spreadsheet ID: ${spreadsheet.spreadsheetId}`);
  }
});
}
createNewSpreadSheet();

Specifications

  • Node version (node -v)
  • OS (Mac/Linux/Windows)

Cannot destructure property `client_secret` of 'undefined' or 'null'.

Expected Behavior

expected the script to work.

Actual Behavior

I got an error.
const {client_secret, client_id, redirect_uris} = credentials.installed;
^

TypeError: Cannot destructure property client_secret of 'undefined' or 'null'.
at authorize (C:\Users\Mustafa Aygün\Desktop\code\emailer_test\quickstart.js:26:65)
at fs.readFile (C:\Users\Mustafa Aygün\Desktop\code\emailer_test\quickstart.js:16:3)
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)

Steps to Reproduce the Problem

Specifications

  • Node version (node -v)
  • OS (Mac/Linux/Windows)

Fail to get Oauth2.0 using gmail quick start

Expected Behavior

Generate Code

Actual Behavior

#Relplaced Path with XXXXX
var auth = new googleAuth();
^

TypeError: googleAuth is not a constructor
at authorize (C:\XXXXXXXi\quickstart.js:52:14)
at processClientSecrets (C:\XXXXX\quickstart.js:38:3)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:528:3)

Steps to Reproduce the Problem

Step followed described here:
https://developers.google.com/gmail/api/quickstart/nodejs

Specifications

Node v9.5.0
OS Windows 10 pro

  • Node version (node -v)
  • OS (Mac/Linux/Windows)

Entering code

Expected Behavior

what to put on cmd ->"Enter the code from that page here"

Actual Behavior

what to give code

Steps to Reproduce the Problem

Specifications

  • Node version (node -v)
  • OS (Mac/Linux/Windows)

Quickstart: ENABLE THE GOOGLE SLIDES API, not working

Expected Behavior

in https://developers.google.com/slides/quickstart/nodejs

  • Clicking "ENABLE THE GOOGLE SLIDES API" gives me credentials.json or guides me how to get them

Actual Behavior

  • Clicking "ENABLE THE GOOGLE SLIDES API" gives error:

image

From the console
image
(I couldn't copy all of the message, as there is a key in the URL that I don't know if is sensitive)

Steps to Reproduce the Problem

  1. Go to: https://developers.google.com/slides/quickstart/nodejs in
  2. Click "ENABLE THE GOOGLE SLIDES API"

Specifications

  • Chrome Version 70.0.3538.110 (Official Build) (64-bit) on OSX Mojave V10.14.1

Cannot read property 'OAuth2' of undefined

In the Google sheets api sample code:
https://github.com/gsuitedevs/node-samples/blob/e426bd6af84904ea49ebd043787659936264727a/sheets/quickstart/index.js#L20

Expected Behavior

The following should be working properly.
const google = require('googleapis');
const OAuth2Client = google.auth.OAuth2;

Actual Behavior

Instead, it is showing
Cannot read property 'OAuth2' of undefined

Steps to Reproduce the Problem

  1. Just create a quickstart.js with the code linked above.
  2. Install required packages.
  3. Run node quickstart.js.

Solution

After debugging the code, I found out that it is using the google property in the google variable that we required from googleapis. This bug was resulting in the undefined behavior as google.auth is not defined. What actually defined is google.google.auth.
So what I did was extract the google property directly be using ES6 destructuring which fixed this issue and all the further issues which were created by it.
const {google} = require('googleapis');

Specifications

  • Node version - v8.10.0
  • OS - Linux(Ubuntu v16.04)

Can't run the example code.

Expected Behavior

run the example code succeed.

Actual Behavior

I got an error:
TypeError: Cannot destructure property client_secret of 'undefined' or 'null'.

Steps to Reproduce the Problem

  1. download credentials.json file
  2. run example code
  3. got error

Specifications

no

Did the credential.json change format ? Or just cause I didn't setting some field for the account?

9.3 - Node version (node -v)
Mac - OS (Mac/Linux/Windows)

Bootstrap throws error?

Expected Behavior

It to prompt me to authorize access to google API.

Actual Behavior

Error code:
internal/modules/cjs/loader.js:573
throw err;
^

Error: Cannot find module 'C:\DP\delivery_group_webpage'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:571:15)
at Function.Module._load (internal/modules/cjs/loader.js:497:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:719:10)
at startup (internal/bootstrap/node.js:228:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:575:3)

Steps to Reproduce the Problem

I followed the steps on this tutorial. https://developers.google.com/calendar/quickstart/nodejs
But my directory is quite big and I didn't quite know where to put the index.js and credentials.json file. Tired them in both the maps "app" and "src" but it didn't change the outcome when running node . in terminal.

Specifications

  • Angular v6.0
  • Node version v10.0.0
  • OS (Windows)

Thanks for helping me!

UnhandledPromiseRejectionWarning on Sheets API quickstart

Expected Behavior

No error.

Actual Behavior

Error :

(node:17243) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:17243) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Steps to Reproduce the Problem

Following those steps : https://developers.google.com/sheets/api/quickstart/nodejs
The error appears at the very end of the tutorial.

Specifications

  • Node version : v8.10.0
  • OS : Linux ubuntu 13.04 LTS
  • using a company proxy

UnhandledPromiseRejectionWarning: TypeError: authClient.request is not a function

Expected Behaviov - no error

Actual Behavior

(node:4104) UnhandledPromiseRejectionWarning: TypeError: authClient.request is not a function
at Object.createAPIRequest (C:\Users\atifs\WebstormProjects\eventScheduler\node_modules\googleapis\build\src\lib\apirequest.js:193:20)
at Object.list (C:\Users\atifs\WebstormProjects\eventScheduler\node_modules\googleapis\build\src\apis\calendar\v3.js:684:33)
at listEvents (C:\Users\atifs\WebstormProjects\eventScheduler\index.js:72:21)
at oAuth2Client.getToken (C:\Users\atifs\WebstormProjects\eventScheduler\index.js:54:29)
at C:\Users\atifs\WebstormProjects\eventScheduler\node_modules\google-auth-library\build\src\auth\oauth2client.js:158:46
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:4104) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:4104) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Steps to Reproduce the Problem

Specifications

  • Node version (node -v)
  • OS (Mac/Linux/Windows)

Uncaught TypeError: Expected `input` to be a `Function` or `Object`, got `undefined`

Hi,
I have got the issue while accessing the google sheet API. I tried to Google Sheets API (https://developers.google.com/sheets/api/quickstart/nodejs). And made it as npm package while tried to include the package in new project. i got an issue

Uncaught TypeError: Expected input to be a Function or Object, got undefined at module.exports (index.js?2556:45) at eval (index.js?f447:22) at Object../node_modules/gtoken/build/src/index.js (app.js:5720) at __webpack_require__ (app.js:724) at fn (app.js:101) at eval (jwtclient.js?d465:63) at Object../node_modules/google-auth-library/build/src/auth/jwtclient.js (app.js:3154) at __webpack_require__ (app.js:724) at fn (app.js:101) at Object.eval (googleauth.js?0a40:73)

Please fix the issue
Ref: https://stackoverflow.com/questions/54468809/what-is-causing-typeerror-expected-input-to-be-a-function-or-object-issue/54920596#54920596

Shorthand prop name makes quickstart fail

Expected Behavior

see https://developers.google.com/drive/api/v3/quickstart/nodejs#step_4_run_the_sample

Actual Behavior

(node:36003) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property data of 'undefined' or 'null'. in quickstart.js line 75.

Steps to Reproduce the Problem

  1. follow https://developers.google.com/drive/api/v3/quickstart/nodejs => failure
  2. change line 75 from }, (err, {data}) => { to: }, (err, response) => { and line 77 from const files = data.files; to const files = response.data.files; => success

Specifications

  • Node version (node -v) v8.11.3 (LTS)
  • OS (Mac)

Error: unauthorized_client on trying to list files from Google Drive

Expected Behavior

List the files on google drive

Actual Behavior

Getting error :: The API returned an error: Error: unauthorized_client

Steps to Reproduce the Problem

Execute the below code

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/drive.metadata.readonly'];
// 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('credentialsDrive.json', (err, content) => {
	if (err) return console.log('Error loading client secret file:', err);
	// Authorize a client with credentials, then call the Google Drive API.
	authorize(JSON.parse(content), listFiles);
});

/**
 * 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) console.error(err);
				console.log('Token stored to', TOKEN_PATH);
			});
			callback(oAuth2Client);
		});
	});
}

/**
 * Lists the names and IDs of up to 10 files.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listFiles(auth) {
	const drive = google.drive({
		version: 'v3',
		auth
	});
	drive.files.list({
		pageSize: 10,
		fields: 'nextPageToken, files(id, name)',
	}, (err, res) => {
		if (err) return console.log('The API returned an error: ' + a);
		const files = res.data.files;
		if (files.length) {
			console.log('Files:');
			files.map((file) => {
				console.log(`${file.name} (${file.id})`);
			});
		} else {
			console.log('No files found.');
		}
	});
} 

Specifications

  • Node version (node -v)
  • OS (Mac/Linux/Windows)

Added a function for run the code

Hi All,
please let me know is there any error, its showing error while running the code such as:
There is a function added by me to run the code.

{ message: 'Request had insufficient authentication scopes.',
domain: 'global',
reason: 'forbidden' }

`const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
console.log("its start working...");
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/script.projects'];
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);
console.log("content::::",JSON.parse(content));
// 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) => {
console.log("Token path:::",TOKEN_PATH);
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) 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 myApp(){\n var form = FormApp.create('New Form'); \n var item = form.addCheckboxItem(); \n item.setTitle('What condiments would you like on your hot dog?');\n item.setChoices([item.createChoice('Ketchup'),\n item.createChoice('Mustard'),\n item.createChoice('Relish')]);\n}',
    }, {
    name: 'appsscript',
    type: 'JSON',
    source: '{"timeZone":"America/New_York","exceptionLogging":' +'"CLOUD", "oauthScopes":["https://www.googleapis.com/auth/forms","https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/forms.currentonly","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/analytics.readonly","https://www.googleapis.com/auth/spreadsheets.readonly"]}',
    }],
    },
    }, {}, (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);
    if(res.data.scriptId){
    script.scripts.run({
    scriptId:res.data.scriptId,
    auth,
    resource: {
    "function": 'myApp',
    "parameters": [res.data.scriptId],
    "sessionState": '',
    "devMode":true
    },
    })
    }
    });
    });
    }`
  • Node version (v8.11.2)
  • OS (Linux)

Sheets Quick Start Not Working

Expected Behavior

Run script and be brought to oauth screen that has code you enter on the command line.

Actual Behavior

Run script and get Error: "Missing required parameter: redirect_uri"

Steps to Reproduce the Problem

  1. Download file sheets/quickstart/index.js
  2. Create project and download credentials.json and put it in the same directory as index.js
  3. run node index.js and click click

Specifications

  • Node version (9.3.0)
  • OS (Mac)

error_description: 'Malformed auth code.'

Expected Behavior

Authorize gmail api

Actual Behavior

error_description: 'Malformed auth code.'

Steps to Reproduce the Problem

  1. Download the config file in root directory
  2. node .
  3. paste the secret key

Specifications

  • Node version (node -v) 10.14.2
  • OS (Mac/Linux/Windows)
    Windows

issue while running function.

Hi I am trying to run my code using
where myFunction is function Name

clasp run myFunction

but I am getting Error like this

Requested entity was not found

can anyone know why its happening ??

TypeError: Cannot read property 'auth' of undefined

I am using this quickstart to setup Google Sheets API.
link: https://developers.google.com/sheets/api/quickstart/nodejs

Expected Behavior

Actual Behavior

I am getting this error when I run index.js.

  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);
TypeError: Cannot read property 'auth' of undefined

Steps to Reproduce the Problem

  1. simply follow the tutorial.
  2. when I run index.js file using node ., I get the error mentioned above.

Specifications

  • Node version : 8.11.3
  • OS :Windows

Token Error: The request is missing a valid API key

Expected Behavior

To return the requested data

Actual Behavior

Returns an error saying a valid API key is required, even though a OAuth2 token has already been attached

Steps to Reproduce the Problem

  1. Create OAuth Credentials, get code after user authorization, get token using code
  2. Use oAuth2Client.setCredentials(JSON.parse(token)) to set credentials
  3. Make a request using google.sheets({version: 'v4', oAuth2Client}).values.get({spreadsheetId: '...', range: '...',})

Specifications

  • Node version (node -v) 10.14.0
  • OS (Mac/Linux/Windows) Windows 10

I've followed the example on the Google Sheets API for using OAuth2 for authentication of requests. However, instead of a plain Node app, I want to use it as an Express app. I managed to set up my own credentials, get the code for the user, get the token for a user from the code, and write the token to a 'token.json' file.

However, whenever I make the call to get spreadsheet data, like so:

app.get('/home', async (req, res) => {
	let oAuth2Client = () => {
        let credentials;

	try{
		let content = await readFile('credentials.json');
		console.log(content);
		credentials = JSON.parse(content);
	} catch(err){
		let errMsg = 'Error loading client secret file: ' + err;
		console.log(errMsg);
		res.send({"actionSuccess": false, "error:" : errMsg});
	}

	let {client_secret, client_id, redirect_uris} = credentials.web;
	let oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
	    
	return oAuth2Client;
};
	let token;

	try{
		token = await readFile('token.json');
	} catch (err){
		let errMsg = "Error while trying to retrieve access token: " + err;
		console.log(errMsg);
		res.send({"actionSuccess": false, "error:" : errMsg});
	}

	//console.log(token, 'is token', oAuth2Client, 'is oauth');
	//console.log('before', oAuth2Client);
	await oAuth2Client.setCredentials(JSON.parse(token));
	//console.log('after', oAuth2Client);

	const sheets = google.sheets({version: 'v4', oAuth2Client});
	console.log(sheets);
	sheets.spreadsheets.values.get({
	    spreadsheetId: '...',
	    range: '...',
	}, (err, response) => {
	    if (err){
	    	let errMsg = 'The API returned an error: ' + err;
	    	console.log(errMsg);
	    	res.send({"actionSuccess": false, "error:" : errMsg})
	    }
	    console.log(response);

	    const rows = response.data.values;
	    if (rows.length) {
	    	res.send({"actionSuccess": true, "data": rows});
	    }
	    else {
	    	res.send({"actionSuccess": false, "error": "No data found"});
	    }
	  })
})

I always get the error:

The API returned an error: Error: The request is missing a valid API key.

I check and my OAuth2 is CLEARLY there, so now I'm pulling my hair out wondering why I need this API key, and WHERE I'm supposed to suddenly get this API key? I thought, at first, maybe my credentials and tokens were wrong, but I tried the sample index.js file for the Google Sheets quickstart, and it works fine. So how come when I use it in an Express server it pops up with this error?

Update sheets snippets to use the latest Node client library version

  • Node version (node -v)8
  • OS (Mac/Linux/Windows)heroku

In this part

console.log(`${result.updates.updatedCells} cells appended.`);

There is a mistake
He gives Jason a circular
I opened it by

     var CircularJSON = require('circular-json');
     console.log(CircularJSON.stringify(result));

That's the only way it works for me now

     console.log(JSON.stringify(result.data.updates));

Add Travis

Expected Behavior

Travis CI should continually test these samples.

Actual Behavior

No Travis right now.

Error retrieving access token

Expected Behavior

get token and write to token.json

Actual Behavior

Error retrieving access token { Error: write EPROTO 4508878272:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:252

Specifications

  • Node version (10.14.2)
  • OS (Mac)

Unable to paste the token in the cmd

Expected Behavior

Paste the token in the cmd after authorizing

Actual Behavior

I got the token, copied it, but unable to paste it in the cmd when this message appears
"Enter the code from that page here:". I'm using firebase hosting also.

Specifications

  • Node version (10.12.0)

what about using latest async style

Expected Behavior
It will made easier to read

Actual Behavior
It look very pretty

Steps to Reproduce the Problem

  1. make code non-async style to latest aync style
  2. use try-catch statement to catch error
  3. see code and Be satisfied with shortened codes

Specifications

Node version (node -v): v9.5.0

Version (npm list | grep clasp): no diffence

OS (Mac/Linux/Windows): Linus (ubuntu) but it work all OS

Refactored the Quickstart example with async/await, use it if you'd like.

The Node.js Quickstart example (https://developers.google.com/sheets/api/quickstart/nodejs) contains a "callback hell" that might be difficult to understand for beginners. Also, the example code contains two parts that are coupled: 1. the auth functionality, 2. the example Sheets access code.

I've refactored the code so that it's async/await-based, and the auth part is decoupled from Sheets usage.

I've posted the code on StackOverflow: https://stackoverflow.com/questions/54882145/is-there-an-async-await-node-js-google-auth-module/54882146
Then someone suggested that I also post it here so that you guys can update the example if you agree that this is a more modern solution.

I've tested the code, it worked for me just the way your code did, both in the case of having a saved token and not.

I understand you already have a version as Issue **#28 (I didn't know it before, sorry). I've checked it but I think this solution is slightly better documented. If you find it useful, consider incorporating my code in 2 months when you switch to the newer Node version.

authorizer.js:

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const OAuth2Client = require('google-auth-library').OAuth2Client;

/**
 * Create an OAuth2 client with the given credentials.
 * Tries to use a saved auth token.
 * If no token is found at the given path, gets a token with user interaction, then stores the auth token for later use.
 *
 * @param {string} clientId
 * @param {string} clientSecret
 * @param {string} redirectUrl
 * @param {string[]} scopes Scopes to get authorization for.
 *        If the scopes are changed, a re-authentication is automatically started.
 * @param {string} tokenPath Path to a json file where the auth tokens are stored.
 */
async function authorize(clientId, clientSecret, redirectUrl, scopes, tokenPath) {
    const oAuth2Client = new google.auth.OAuth2(clientId, clientSecret, redirectUrl);
    const auth2Tokens = await readAuth2TokensFromFile(tokenPath);

    if (auth2Tokens && (auth2Tokens.scope === scopes[0])) {
        oAuth2Client.setCredentials(auth2Tokens);
    } else {
        await getNewTokensFromGoogleCli(oAuth2Client, scopes, tokenPath);
    }
    return oAuth2Client;
}

async function readAuth2TokensFromFile(path) {
    try {
        return JSON.parse(fs.readFileSync(path).toString());
    } catch (error) {
        return undefined;
    }
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {OAuth2Client} oAuth2Client The OAuth2 client to get token for.
 * @param {string[]} scopes Scopes to get authorization for.
 * @param {string} tokenFilePath Path to a JSON file to store the tokens in.
 * @returns {Promise<boolean>}
 */
async function getNewTokensFromGoogleCli(oAuth2Client, scopes, tokenFilePath) {
    const authUrl = oAuth2Client.generateAuthUrl({access_type: 'offline', scope: scopes});
    console.log('Authorize this app by visiting this url (mind the line break!):', authUrl);
    const code = await readlineAndReturnPromise('Enter the long code from that page here: ');
    try {
        const {tokens} = await oAuth2Client.getToken(code);
        oAuth2Client.setCredentials(tokens);
        try {
            // Store the token to disk for later program executions
            fs.writeFileSync(tokenFilePath, JSON.stringify(tokens));
            console.log('Token stored to', tokenFilePath);
        } catch(error) {
            console.error(error);
        }
        return true;
    } catch(error) {
        console.error('Error while trying to retrieve access token', error);
        return false;
    }
}

/**
 * @param {string} query The question to ask.
 */
async function readlineAndReturnPromise(query) {
    return new Promise((resolve) => {
        const readlineInterface = readline.createInterface({input: process.stdin, output: process.stdout});
        readlineInterface.question(query, (result) => {
            readlineInterface.close();
            resolve(result);
        });
    })
}

module.exports = {
    authorize,
};

example file for usage:

const authorizer = require('./authorizer');
const {google} = require('googleapis');

authorizer.authorize(
    {YOUR_CLIENT_ID},
    {YOUR_CLIENT_SECRET},
    {YOUR_REDIRECT_URL},
    ['https://www.googleapis.com/auth/spreadsheets.readonly'],
    {YOUR_TOKEN_FILENAME},
).then((oAuthClient) => { listMajors(oAuthClient); });

/**
 * Prints the names and majors of students in a sample spreadsheet:
 * @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 * @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
 */
function listMajors(auth) {
    const sheets = google.sheets({version: 'v4', auth});
    sheets.spreadsheets.values.get({
        spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
        range: 'Class Data!A2:E',
    }, (err, res) => {
        if (err) {
            return console.log('The API returned an error: ' + err);
        }
        const rows = res.data.values;
        if (rows.length) {
            console.log('Name, Major:');
            // Print columns A and E, which correspond to indices 0 and 4.
            rows.map((row) => {
                console.log(`${row[0]}, ${row[4]}`);
            });
        } else {
            console.log('No data found.');
        }
    });
}

Thanks for your work!

I found some error with my async code

Expected Behavior

I thought the file read was in the variable.

Actual Behavior

because of const it did not work as well

Steps to Reproduce the Problem

  1. write var instead of const at line 42
  2. and it will work as well

Specifications

  • Node version (node -v)
  • OS (Mac/Linux/Windows)

Cannot run Gmail API quickstart for nodejs

Expected Behavior

Send email successful

Actual Behavior

Error retrieving access token { Error: connect ETIMEDOUT 172.217.2.170:443
at Object._errnoException (util.js:1024:11)
at _exceptionWithHostPort (util.js:1046:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)

Steps to Reproduce the Problem

  1. Follow instructions on page https://developers.google.com/gmail/api/quickstart/nodejs?hl=zh-CN
  2. node .
  3. paste code and enter

Specifications

  • Node version (node -v) v8.9.1
  • OS (Mac/Linux/Windows) Windows 7

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.