Node.js quickstart

Stay organized with collections Save and categorize content based on your preferences.

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 Tasks API.

Prerequisites

To run this quickstart, you need the following prerequisites:

  • Authorization credentials for a desktop application. To learn how to create credentials for a desktop application, refer to Create credentials.

  • A Google account with Google Tasks enabled.

Step 1: Install the client library

Run the following commands to install the libraries using npm:

npm install googleapis@105 @google-cloud/local-auth@2.1.0 --save

Step 2: Set up the sample

Create a file named index.js in your working directory and copy in the following code:

tasks/quickstart/index.js
const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/tasks.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 = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

/**
 * Reads previously authorized credentials from the save file.
 *
 * @return {Promise<OAuth2Client|null>}
 */
async function loadSavedCredentialsIfExist() {
  try {
    const content = await fs.readFile(TOKEN_PATH);
    const credentials = JSON.parse(content);
    return google.auth.fromJSON(credentials);
  } catch (err) {
    return null;
  }
}

/**
 * Serializes credentials to a file comptible with GoogleAUth.fromJSON.
 *
 * @param {OAuth2Client} client
 * @return {Promise<void>}
 */
async function saveCredentials(client) {
  const content = await fs.readFile(CREDENTIALS_PATH);
  const keys = JSON.parse(content);
  const key = keys.installed || keys.web;
  const payload = JSON.stringify({
    type: 'authorized_user',
    client_id: key.client_id,
    client_secret: key.client_secret,
    refresh_token: client.credentials.refresh_token,
  });
  await fs.writeFile(TOKEN_PATH, payload);
}

/**
 * Load or request or authorization to call APIs.
 *
 */
async function authorize() {
  let client = await loadSavedCredentialsIfExist();
  if (client) {
    return client;
  }
  client = await authenticate({
    scopes: SCOPES,
    keyfilePath: CREDENTIALS_PATH,
  });
  if (client.credentials) {
    await saveCredentials(client);
  }
  return client;
}

/**
 * Lists the user's first 10 task lists.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
async function listTaskLists(auth) {
  const service = google.tasks({version: 'v1', auth});
  const res = await service.tasklists.list({
    maxResults: 10,
  });
  const taskLists = res.data.items;
  if (taskLists || taskLists.length === 0) {
    console.log('No task lists found.');
    return;
  }
  console.log('Task lists:');
  taskLists.forEach((taskList) => {
    console.log(`${taskList.title} (${taskList.id})`);
  });
}

authorize().then(listTaskLists).catch(console.error);

Step 3: Run the sample

  1. Run the sample using the following command:

    node .
    
  2. If this is your first time running the sample, authorize the app to access your data:

    1. In the window that appears, sign in to the Google account that you wish to use for authorization.

    2. Click Accept.

The sample executes.

If you have problems, refer to the Troubleshoot the sample section.

Troubleshooting

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

If the OAuth consent screen displays the warning "This app isn't verified," your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your app must go through the verification process to remove that warning and other limitations. During the development phase, you can continue past this warning by selecting Advanced > Go to {Project Name} (unsafe).

File not found error for credentials.json

When running the sample, you might receive a file not found or no such file error regarding credentials.json.

This error occurs when you have not authorized the desktop application credentials as detailed in the Prerequisites section above. To learn how to create credentials for a desktop application, go to Create credentials.

Once you create the credentials, make sure the downloaded JSON file is saved as credentials.json. Then move the file to your working directory with the rest of the sample quickstart code.

Further reading

For further information on the APIs used in this quickstart, refer to the Google APIs Node.js Client section on GitHub.