ブラウザクイックスタート

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


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

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

前提条件

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

  • Python 2.4以上(ウェブサーバを提供するため)
  • Google Driveが有効である Googleアカウント

Step 1: Drive APIをオンにする

  1. Google Developers Consoleにてプロジェクトを作成し、あるいは選択するためにこのウィザードを使用し、API自動的にオンにします。 Continue、それから、Go to credentialsをクリックします。
  2. Add credentials to your projectページ上で、Cancelボタンをクリックします。
  3. ページ上部の OAuth consent screenタブを選択します。 Email addressを選択し、まだセットされていない場合には Product nameを入力し、Saveボタンをクリックします。
  4. Credentialsタブを選択し、Create credentialsボタンをクリックし、OAuth client IDを選択します。
  5. アプリケーションタイプ Web applicationを選択します。
  6. Authorized JavaScript originsフィールドに URL http://localhost:8000を入力します。 Authorized redirect URIsフィールドを空白のままにすることができます。
  7. Createボタンをクリックします。
  8. 表示されたダイアログ内のクライアント IDをメモします。 後のステップにてそれを必要とします。
  9. 表示されたダイアログを閉じるために OKをクリックします。
  10. Create credentialsボタンをクリックし、API keyを選択します。
  11. 表示されたダイアログ内の APIキーをメモします。 後のステップにてそれを必要とします。
  12. 無制限のキーを作成するために Closeボタンをクリックします。 本番アプリケーションでは、APIキーへのアクセスを特定のウェブサイト、IPアドレス、あるいはモバイルアプリに制限することができます。

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

index.htmlと名付けられたファイルを作成し、次のコードをコピーします:

drive/quickstart/index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Drive API Quickstart</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <p>Drive API Quickstart</p>

    <!--Add buttons to initiate auth sequence and sign out-->
    <button id="authorize_button" style="display: none;">Authorize</button>
    <button id="signout_button" style="display: none;">Sign Out</button>

    <pre id="content" style="white-space: pre-wrap;"></pre>

    <script type="text/javascript">
      // Client ID and API key from the Developer Console
      var CLIENT_ID = '<YOUR_CLIENT_ID>';
      var API_KEY = '<YOUR_API_KEY>';

      // Array of API discovery doc URLs for APIs used by the quickstart
      var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];

      // Authorization scopes required by the API; multiple scopes can be
      // included, separated by spaces.
      var SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';

      var authorizeButton = document.getElementById('authorize_button');
      var signoutButton = document.getElementById('signout_button');

      /**
       *  On load, called to load the auth2 library and API client library.
       */
      function handleClientLoad() {
        gapi.load('client:auth2', initClient);
      }

      /**
       *  Initializes the API client library and sets up sign-in state
       *  listeners.
       */
      function initClient() {
        gapi.client.init({
          apiKey: API_KEY,
          clientId: CLIENT_ID,
          discoveryDocs: DISCOVERY_DOCS,
          scope: SCOPES
        }).then(function () {
          // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
        }, function(error) {
          appendPre(JSON.stringify(error, null, 2));
        });
      }

      /**
       *  Called when the signed in status changes, to update the UI
       *  appropriately. After a sign-in, the API is called.
       */
      function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          listFiles();
        } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }

      /**
       *  Sign in the user upon button click.
       */
      function handleAuthClick(event) {
        gapi.auth2.getAuthInstance().signIn();
      }

      /**
       *  Sign out the user upon button click.
       */
      function handleSignoutClick(event) {
        gapi.auth2.getAuthInstance().signOut();
      }

      /**
       * Append a pre element to the body containing the given message
       * as its text node. Used to display the results of the API call.
       *
       * @param {string} message Text to be placed in pre element.
       */
      function appendPre(message) {
        var pre = document.getElementById('content');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }

      /**
       * Print files.
       */
      function listFiles() {
        gapi.client.drive.files.list({
          'pageSize': 10,
          'fields': "nextPageToken, files(id, name)"
        }).then(function(response) {
          appendPre('Files:');
          var files = response.result.files;
          if (files && files.length > 0) {
            for (var i = 0; i < files.length; i++) {
              var file = files[i];
              appendPre(file.name + ' (' + file.id + ')');
            }
          } else {
            appendPre('No files found.');
          }
        });
      }

    </script>

    <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>
  </body>
</html>

コピーされたコード内のプレースホルダ <YOUR_CLIENT_ID>を、Step 1にて作成したクライアント IDに置換します。 同様に、プレースホルダ <YOUR_API_KEY>を作成した APIキーに置換します。

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

  1. あなたの作業ディレクトリから次のコマンドを使用してウェブサーバを起動します:

Python 2.x

python -m SimpleHTTPServer 8000

Python 3.x

python -m http.server 8000
  1. あなたのブラウザに URL http://localhost:8000をロードします。

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

  1. 承認ウインドウを開くために Authorizeボタンをクリックします。

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

  2. Acceptボタンをクリックします。

ノート

  • 最初のユーザの承認のあと、ユーザとの対話なしに認証トークンを取得するには、immediate:trueモードを使用する gapi.auth.authorizeを呼び出します。

参考文献

トラブルシューティング

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

Error: origin_mismatch

このエラーは、ウェブページをサービスするために使用されているホストおよびポートが、あなたの Google Developers Console project上の許可された JavaScriptオリジンと一致しない場合に、承認フローの最中に発生します。 承認された JavaScriptオリジンをセットし、あなたのブラウザにて URLがオリジンの URLと一致していることを確認してください。

idpiframe_initialization_failed: Failed to read the 'localStorage' property from 'Window'

Google Sign-inライブラリは、サードパーティーのクッキーおよびデータストレージがウェブブラウザにて有効とされていることを必要とします。 このエラーが発生したユーザの場合、彼らに機能を有効にするか、accounts.google.comに例外を追加するよう促してください。

idpiframe_initialization_failed: Not a valid origin for the client

Google Sign-inライブラリは、Google Developers Consoleにて登録されたドメインがウェブページをホストするために使用されているドメインと一致することを必要とします。 登録したオリジンがブラウザ内の URLと一致していることを確認してください。

This app isn't verified.

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