Guia de início rápido do Node.js

Os guias de início rápido explicam como configurar e executar um app que chama uma API do Google Workspace. Este guia de início rápido usa uma abordagem de autenticação simplificada adequada para um ambiente de teste. Para um ambiente de produção, recomendamos aprender sobre autenticação e autorização antes de escolher as credenciais de acesso adequadas para seu app.

Crie um aplicativo de linha de comando do Node.js que faça solicitações à API Drive Labels.

Objetivos

  • Prepare o ambiente.
  • Instale a biblioteca de cliente.
  • Configure a amostra.
  • Execute a amostra.

Pré-requisitos

  • Uma Conta do Google

Configurar o ambiente

Para concluir este guia de início rápido, configure seu ambiente.

Ativar a API

Antes de usar as APIs do Google, é necessário ativá-las em um projeto do Google Cloud. É possível ativar uma ou mais APIs em um único projeto do Google Cloud.
  • No console do Google Cloud, ative a API Drive Labels.

    Ativar a API

Autorizar credenciais para um aplicativo de computador

Para autenticar usuários finais e acessar dados de usuários no app, crie um ou mais IDs do cliente OAuth 2.0. Um ID do cliente é usado para identificar um único app nos servidores OAuth do Google. Se o app for executado em várias plataformas, crie um ID do cliente separado para cada uma delas.
  1. No console do Google Cloud, acesse Menu > Google Auth platform > Clientes.

    Acesse "Clientes"

  2. Clique em Criar cliente.
  3. Clique em Tipo de aplicativo > App para computador.
  4. No campo Nome, digite um nome para a credencial. Esse nome é mostrado apenas no console do Google Cloud.
  5. Clique em Criar.

    A credencial recém-criada aparece em "IDs de cliente OAuth 2.0".

  6. Salve o arquivo JSON baixado como credentials.json e mova-o para o diretório de trabalho.

Instale a biblioteca de cliente

  • Instale as bibliotecas usando o npm:

    npm install googleapis@113 @google-cloud/local-auth@2.1.1 --save
    

Configure a amostra

  1. No diretório de trabalho, crie um arquivo chamado index.js.

  2. No arquivo, cole o seguinte código:

        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.labels.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 Drive Labels
          // API.
          authorize(JSON.parse(content), listDriveLabels);
        });
    
        /**
        * 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 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);
            });
          });
        }
    
        function listDriveLabels(auth) {
          const service = google.drivelabels({version: 'v2', auth});
          const params = {
            'view': 'LABEL_VIEW_FULL'
          };
          service.labels.list(params, (err, res) => {
            if (err) return console.error('The API returned an error: ' + err);
            const labels = res.data.labels;
            if (labels) {
              labels.forEach((label) => {
                const name = label.name;
                const title = label.properties.title;
                console.log(`${name}\t${title}`);
              });
            } else {
              console.log('No Labels');
            }
          });
        }
    

Executar a amostra

  1. No diretório de trabalho, execute a amostra:

    node .
    
  2. Na primeira vez que você executar a amostra, será necessário autorizar o acesso:

    1. Se você ainda não estiver conectado à sua Conta do Google, será solicitado a fazer login. Se você tiver feito login em várias contas, selecione uma para usar na autorização.
    2. Clique em Aceitar.

    As informações de autorização são armazenadas no sistema de arquivos. Assim, na próxima vez que você executar o código de exemplo, não será necessário fazer a autorização.

Você criou seu primeiro aplicativo Node.js que faz solicitações para a API Drive Labels.

Próximas etapas