Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

GoogleAPIその0001 JavaScriptでデータを取得するための認証とか基礎

参考にさせて頂いたページ

公式のGoogle People APIサンプル(認証して、Google People APIを使用するサンプル)

はじめてのアナリティクス API: ウェブ アプリケーション向け JavaScript クイックスタート

Google API Console のアカウント作成とログイン

まずは Google API Consoleのアカウントを作成してログインします。

APIに関する設定をする「API Manager」のページが表示されます。

色々と設定をする

プロジェクト作成

  • 「プロジェクト作成」ボタンをクリックします。

f:id:motomichi_works:20161022230437p:plain

  • モーダルが表示され、「My Project」とデフォルトで入力さていたので、そのまま作成しました。

f:id:motomichi_works:20161022230549p:plain

OAuth同意画面

  • 「OAuth同意画面」タブをクリック
  • 「認証情報を作成」ボタンをクリック

f:id:motomichi_works:20161022231516p:plain

  • メールアドレス欄は自身がログイン中のメールアドレスを選択します。
  • サービス名は適当に「サンプルサービス」と入力しました。
  • あとは省略可能とのことなので、何も入力せず「保存」をクリックしました。

f:id:motomichi_works:20161022232522p:plain

「承認URL」の設定と「OAuthクライアントID」の取得

  • 「認証情報」タブをクリックします。
  • 「認証情報を作成」ドロップダウンから「OAuthクライアントID」を選択します。

f:id:motomichi_works:20161022233103p:plain

f:id:motomichi_works:20161022235154p:plain

  • クライアントIDの横にあるアイコンをクリックして、テキストファイルにコピペしておきます。これは後でJSを書くときに使用します。
  • クライアントシークレットは今回は使用しません。
  • クライアントID、クライアントシークレットは後からでも確認できるので安心です。
  • 「OK」をクリックします。

f:id:motomichi_works:20161023001157p:plain

  • 登録が完了すると以下のような感じになります。

f:id:motomichi_works:20161023001208p:plain

APIキーの取得

  • 「認証情報」タブをクリックします。
  • 「認証情報を作成」ドロップダウンから「OAuthクライアントID」を選択します。

f:id:motomichi_works:20161023002514p:plain

  • APIキーの横にあるアイコンをクリックして、テキストファイルにコピペしておきます。これも後でJSを書くときに使用します。

f:id:motomichi_works:20161023002841p:plain

  • 名前は任意ですが初期値のまま「API キー 1」にしました。
  • ラジオボタン「HTTPリファラー(ウェブサイト)」を選択します。
  • "このHTTPリファラー(ウェブサイト)からのリクエストを受け入れる"の項目は例として「*example.com/*」ですが自身のドメインに合わせて設定してください。
  • 保存をクリックします。

f:id:motomichi_works:20161023004418p:plain

使いたいAPIを有効化する

  • 例として Google People API です。
  • 「ライブラリ」をクリックして、フォームに「people」と入力すると、候補が出てくるので「Google People API」をクリックします。

f:id:motomichi_works:20161023010425p:plain

  • 「有効にする」をクリックします。

f:id:motomichi_works:20161023010900p:plain

  • ここで有効化することで、JSから以下のような感じで Google People API の バージョン1 がJSONを返してくれるようになります。htmlソースの全容はのちほど紹介します。
        gapi.client.load('people', 'v1', function() {
          var request = gapi.client.people.people.get({
            resourceName: 'people/me'
          });
          request.execute(function(resp) {
            var p = document.createElement('p');
            var name = resp.names[0].givenName;
            p.appendChild(document.createTextNode('Hello, '+name+'!'));
            document.getElementById('content').appendChild(p);
          });
        });

index.htmlの作成とその記述内容

<!--
  Copyright (c) 2011 Google Inc.
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy of
  the License at
  http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  License for the specific language governing permissions and limitations under
  the License.
  To run this sample, set apiKey to your application's API key and clientId to
  your application's OAuth 2.0 client ID. They can be generated at:
    https://console.developers.google.com/apis/credentials?project=_
  Then, add a JavaScript origin to the client that corresponds to the domain
  where you will be running the script. Finally, activate the People API at:
    https://console.developers.google.com/apis/library?project=_
-->
<!DOCTYPE html>
<html>
  <head>
    <title>Say hello using the People API</title>
    <meta charset='utf-8' />
  </head>
  <body>
    <p>Say hello using the People API.</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>

    <div id="content"></div>

    <script type="text/javascript">
      // Enter an API key from the Google API Console:
      //   https://console.developers.google.com/apis/credentials?project=_
      var apiKey = 'YOUR_API_KEY';
      // Enter a client ID for a web application from the Google API Console:
      //   https://console.developers.google.com/apis/credentials?project=_
      // In your API Console project, add a JavaScript origin that corresponds
      //   to the domain where you will be running the script.
      var clientId = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com';
      // Enter one or more authorization scopes. Refer to the documentation for
      // the API or https://developers.google.com/identity/protocols/googlescopes
      // for details.
      var scopes = 'profile';
      var auth2; // The Sign-In object.
      var authorizeButton = document.getElementById('authorize-button');
      var signoutButton = document.getElementById('signout-button');
      function handleClientLoad() {
        // Load the API client and auth library
        gapi.load('client:auth2', initAuth);
      }
      function initAuth() {
        gapi.client.setApiKey(apiKey);
        gapi.auth2.init({
            client_id: clientId,
            scope: scopes
        }).then(function () {
          auth2 = gapi.auth2.getAuthInstance();
          // Listen for sign-in state changes.
          auth2.isSignedIn.listen(updateSigninStatus);
          // Handle the initial sign-in state.
          updateSigninStatus(auth2.isSignedIn.get());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
        });
      }
      function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          makeApiCall();
        } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }
      function handleAuthClick(event) {
        auth2.signIn();
      }
      function handleSignoutClick(event) {
        auth2.signOut();
      }
      // Load the API and make an API call.  Display the results on the screen.
      function makeApiCall() {
        gapi.client.load('people', 'v1', function() {
          var request = gapi.client.people.people.get({
            resourceName: 'people/me'
          });
          request.execute(function(resp) {
            var p = document.createElement('p');
            var name = resp.names[0].givenName;
            p.appendChild(document.createTextNode('Hello, '+name+'!'));
            document.getElementById('content').appendChild(p);
          });
        });
        // Note: In this example, we use the People API to get the current
        // user's name. In a real app, you would likely get basic profile info
        // from the GoogleUser object to avoid the extra network round trip.
        console.log(auth2.currentUser.get().getBasicProfile().getGivenName());
      }
    </script>
    <script src="https://apis.google.com/js/api.js?onload=handleClientLoad"></script>
  </body>
</html>

Google People API からデータを取得してみる

  • 「Authorize」ボタンをクリックすると、「クライアントID」「APIキー」をもとに認証が行われます。
  • サインイン状態であれば、makeApiCall()関数が実行されます。
  • gapi.client.load()メソッドの引数として、API名とそのバージョン、コールバック関数を渡します。

参考までにエラーが出ていたときの話

  • 400エラーが出ていたときは、認証の際に送信する「クライアントID」または「APIキー」の値が間違っていました。
  • 403エラーが出ていたときは、Google People API が有効化されていませんでした。

おまけ