Node.js 빠른 시작

빠른 시작에서는 Google Workspace API를 호출하는 앱을 설정하고 실행하는 방법을 설명합니다.

Google Workspace 빠른 시작은 API 클라이언트 라이브러리를 사용하여 인증 및 승인 흐름의 일부 세부정보를 처리합니다. 자체 앱에는 클라이언트 라이브러리를 사용하는 것이 좋습니다. 이 빠른 시작에서는 테스트 환경에 적합한 간소화된 인증 방식을 사용합니다. 프로덕션 환경의 경우 앱에 적합한 액세스 사용자 인증 정보를 선택하기 전에 인증 및 승인에 대해 알아보는 것이 좋습니다.

Drive Labels API에 요청을 수행하는 Node.js 명령줄 애플리케이션을 만듭니다.

목표

  • 환경을 설정합니다.
  • 클라이언트 라이브러리를 설치합니다.
  • 샘플을 설정합니다.
  • 샘플을 실행합니다.

기본 요건

  • Google 계정

환경 설정하기

이 빠른 시작을 완료하려면 환경을 설정하세요.

API 사용 설정

Google API를 사용하려면 먼저 Google Cloud 프로젝트에서 사용 설정해야 합니다. 단일 Google Cloud 프로젝트에서 하나 이상의 API를 사용 설정할 수 있습니다.
  • Google Cloud 콘솔에서 Drive Labels API를 사용 설정합니다.

    API 사용 설정

데스크톱 애플리케이션에 대한 사용자 인증 정보 승인

앱에서 최종 사용자를 인증하고 사용자 데이터에 액세스하려면 OAuth 2.0 클라이언트 ID를 하나 이상 만들어야 합니다. 클라이언트 ID는 Google OAuth 서버에서 단일 앱을 식별하는 데 사용됩니다. 앱이 여러 플랫폼에서 실행되는 경우 플랫폼마다 별도의 클라이언트 ID를 만들어야 합니다.
  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > 사용자 인증 정보로 이동합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭합니다.
  3. 애플리케이션 유형 > 데스크톱 앱을 클릭합니다.
  4. 이름 입력란에 사용자 인증 정보의 이름을 입력합니다. 이 이름은 Google Cloud 콘솔에만 표시됩니다.
  5. 만들기를 클릭합니다. OAuth 클라이언트 생성 완료 화면이 나타나 새 클라이언트 ID와 클라이언트 비밀번호를 표시합니다.
  6. OK(확인)를 클릭합니다. 새로 만든 사용자 인증 정보가 OAuth 2.0 클라이언트 ID 아래에 표시됩니다.
  7. 다운로드한 JSON 파일을 credentials.json로 저장하고 작업 디렉터리로 파일을 이동합니다.

클라이언트 라이브러리 설치

  • npm을 사용하여 라이브러리를 설치합니다.

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

샘플 설정

  1. 작업 디렉터리에서 index.js라는 파일을 만듭니다.

  2. 파일에 다음 코드를 붙여넣습니다.

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

샘플 실행

  1. 작업 디렉터리에서 샘플을 실행합니다.

    node .
    
  2. 샘플을 처음 실행하면 액세스를 승인하라는 메시지가 표시됩니다.

    1. 아직 Google 계정에 로그인하지 않았다면 로그인하라는 메시지가 표시됩니다. 여러 계정에 로그인되어 있는 경우 승인에 사용할 계정 하나를 선택합니다.
    2. 동의를 클릭합니다.

    승인 정보는 파일 시스템에 저장되므로 다음에 샘플 코드를 실행할 때는 승인하라는 메시지가 표시되지 않습니다.

Drive Labels API에 요청하는 첫 번째 Nodejs 애플리케이션을 성공적으로 만들었습니다.

다음 단계