Panduan memulai Node.js

Panduan memulai menjelaskan cara menyiapkan dan menjalankan aplikasi yang memanggil Google Workspace API.

Panduan memulai Google Workspace menggunakan library klien API untuk menangani beberapa detail alur autentikasi dan otorisasi. Sebaiknya gunakan library klien untuk aplikasi Anda sendiri. Panduan memulai ini menggunakan pendekatan autentikasi sederhana yang sesuai untuk lingkungan pengujian. Untuk lingkungan produksi, sebaiknya pelajari autentikasi dan otorisasi sebelum memilih kredensial akses yang sesuai untuk aplikasi Anda.

Membuat aplikasi command line Node.js yang membuat permintaan ke Drive Labels API.

Tujuan

  • Menyiapkan lingkungan Anda.
  • Instal library klien
  • Siapkan contoh.
  • Jalankan contoh.

Prasyarat

  • Akun Google.

Menyiapkan lingkungan Anda

Untuk menyelesaikan panduan memulai ini, siapkan lingkungan Anda.

Mengaktifkan API

Sebelum menggunakan Google API, Anda harus mengaktifkannya di project Google Cloud. Anda dapat mengaktifkan satu atau beberapa API dalam satu project Google Cloud.

Mengizinkan kredensial untuk aplikasi desktop

Untuk mengautentikasi pengguna akhir dan mengakses data pengguna di aplikasi, Anda perlu membuat satu atau beberapa Client ID OAuth 2.0. Client ID digunakan untuk mengidentifikasi satu aplikasi ke server OAuth Google. Jika aplikasi Anda berjalan di beberapa platform, Anda harus membuat client ID terpisah untuk setiap platform.
  1. Di konsol Google Cloud, buka Menu > APIs & Services > Credentials.

    Buka Kredensial

  2. Klik Buat Kredensial > Client ID OAuth.
  3. Klik Jenis aplikasi > Aplikasi desktop.
  4. Di kolom Name, ketik nama untuk kredensial tersebut. Nama ini hanya ditampilkan di Konsol Google Cloud.
  5. Klik Create. Layar yang dibuat klien OAuth akan muncul, yang menampilkan Client ID dan Rahasia klien Anda yang baru.
  6. Klik OK. Kredensial yang baru dibuat akan muncul di Client ID OAuth 2.0.
  7. Simpan file JSON yang didownload sebagai credentials.json, lalu pindahkan file tersebut ke direktori kerja Anda.

Menginstal library klien

  • Instal library menggunakan npm:

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

Menyiapkan contoh

  1. Di direktori kerja Anda, buat file bernama index.js.

  2. Dalam file tersebut, tempel kode berikut:

        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');
            }
          });
        }
    

Menjalankan contoh

  1. Di direktori kerja Anda, jalankan contoh:

    node .
    
  2. Saat pertama kali menjalankan contoh, Anda akan diminta untuk memberikan otorisasi akses:

    1. Jika belum login ke Akun Google, Anda akan diminta untuk login. Jika Anda masuk ke beberapa akun, pilih satu akun yang akan digunakan untuk otorisasi.
    2. Klik Accept.

    Informasi otorisasi disimpan di sistem file, sehingga saat berikutnya Anda menjalankan kode contoh, Anda tidak akan dimintai otorisasi.

Anda telah berhasil membuat aplikasi Nodejs pertama yang membuat permintaan ke Drive Labels API.

Langkah berikutnya