Node.js クイックスタート

みるくあいらんどっ! > 和訳 > google関係 > Drive API > api > v3 > クイックスタート


  • この記事は、Google Drive™ APIに関する記事を和訳したものです。
  • 原文: Node.js Quickstart
  • 元記事のライセンスは CC-BYで、この和訳記事のライセンスは CC-BYです。
  • 自己責任でご利用ください。
  • 和訳した時期は 2019年6月ころです。

Drive APIにリクエストを行う単純な Node.jsコマンドラインアプリケーションを作成するには、このページの残りの部分で説明されている手順を完了します。

前提条件

このクイックスタートを実行するには、以下の前提条件を必要とします:

  • Node.js & npmがインストールされている。
  • Google Driveが有効である Googleアカウント

Step 1: Drive APIをオンにする

新しい Cloud Platform projectを作成するためにこのボタンをクリックし、Drive APIを自動的に有効にします:

Drive APIを有効にする

ダイアログが表示されたら、DOWNLOAD CLIENT CONFIGURATIONをクリックし、あなたの作業ディレクトリにファイル credentials.json を保存します。

Step 2: クライアントライブラリをインストールする

npmを使用してライブラリをインストールするするには、以下のコマンドを実行します:

npm install googleapis@39 --save

Step 3: サンプルをセットアップする

あなたの作業ディレクトリに、index.jsと名付けられたファイルを作成し、次のコードをコピーします:

drive/quickstart/index.js
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('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 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) return 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: ' + err);
    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.');
    }
  });
}

Step 4: サンプルを実行する

次のコマンドを使用してサンプルを実行します:

node .

初めてサンプルを実行するとき、アクセスを承認するよう求められるでしょう:

  1. あなたのブラウザにて、提供された URLを閲覧します。

    もし、まだあなたの Googleアカウントにログインしていなければ、ログインを求められるでしょう。 もし、複数の Googleアカウントにログインしているならば、認証のために使用する 1つのアカウントを選択するよう求められるでしょう。

  2. Acceptボタンをクリックします。
  3. 与えられたコードをコピーし、それをコマンドラインプロンプトにペーストし、Enterを押します。

ノート

  • 認証情報は、ファイルシステム上に格納されるので、以降の実行では認証を求められないでしょう。
  • この例の認証フローは、コマンドラインアプリケーションのためにデザインされています。 他のコンテキストにて承認を実行する方法については、ライブラリの READMEの Authorizing and Authenticatingセクションを参照してください。

参考文献

トラブルシューティング

このセクションでは、このクイックスタートを実行しようとしたときに遭遇するかもしれない、幾つかの一般的な問題について説明し、可能な解決策を提案します。

This app isn't verified.

機密性の高いユーザデータへのアクセスを提供するスコープをリクエストしている場合、ユーザに表示される OAuth同意画面に、警告 "This app isn't verified" が表示されるかもしれません。 これらのアプリケーションは、その警告および他の制限を取り除くための検証プロセスを、最終的には通過しなければなりません。 開発段階では、Advanced > Go to {Project Name} (unsafe) をクリックすることによって、この警告を追加し続けることができます。