参考にさせて頂いたページ
公式のGoogle People APIサンプル(認証して、Google People APIを使用するサンプル)
はじめてのアナリティクス API: ウェブ アプリケーション向け JavaScript クイックスタート
Google API Console のアカウント作成とログイン
まずは Google API Consoleのアカウントを作成してログインします。
APIに関する設定をする「API Manager」のページが表示されます。
色々と設定をする
プロジェクト作成
- 「プロジェクト作成」ボタンをクリックします。
- モーダルが表示され、「My Project」とデフォルトで入力さていたので、そのまま作成しました。
OAuth同意画面
- 「OAuth同意画面」タブをクリック
- 「認証情報を作成」ボタンをクリック
- メールアドレス欄は自身がログイン中のメールアドレスを選択します。
- サービス名は適当に「サンプルサービス」と入力しました。
- あとは省略可能とのことなので、何も入力せず「保存」をクリックしました。
「承認URL」の設定と「OAuthクライアントID」の取得
- 「認証情報」タブをクリックします。
- 「認証情報を作成」ドロップダウンから「OAuthクライアントID」を選択します。
- ラジオボタンの「ウェブアプリケーション」を選択します。
- 名前は任意ですが初期値のまま「ウェブ クライアント 1」にしました。
- 承認済みのJavaScript生成元は例として「http://example.com」としてありますが、自身の使用しているドメインにしてください。JSはこのあとhttp://example.com/index.htmlの中に書くことにします。
- クライアントIDの横にあるアイコンをクリックして、テキストファイルにコピペしておきます。これは後でJSを書くときに使用します。
- クライアントシークレットは今回は使用しません。
- クライアントID、クライアントシークレットは後からでも確認できるので安心です。
- 「OK」をクリックします。
- 登録が完了すると以下のような感じになります。
APIキーの取得
- 「認証情報」タブをクリックします。
- 「認証情報を作成」ドロップダウンから「OAuthクライアントID」を選択します。
- APIキーの横にあるアイコンをクリックして、テキストファイルにコピペしておきます。これも後でJSを書くときに使用します。
- 名前は任意ですが初期値のまま「API キー 1」にしました。
- ラジオボタン「HTTPリファラー(ウェブサイト)」を選択します。
- "このHTTPリファラー(ウェブサイト)からのリクエストを受け入れる"の項目は例として「*example.com/*」ですが自身のドメインに合わせて設定してください。
- 保存をクリックします。
使いたいAPIを有効化する
- 「有効にする」をクリックします。
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の作成とその記述内容
- index.htmlを作成して、http://example.com/index.htmlで閲覧できるように配置します。
- 記述内容は以下の通りですが、2016年10月23日現在の公式のgithubサンプル「google-api-javascript-client/authSample.html at master · google/google-api-javascript-client · GitHub」をコピペしただけです。「クライアントID」「APIキー」の部分はご自身のものを入れてください。今後バージョンなどが変わると記述内容も変化があるかもしれないので、その都度公式のページをチェックすることを推奨します。
<!-- 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 が有効化されていませんでした。
おまけ
- http://example.com/index.html にJSを書く例で説明をしてきましたが、xamppなどで、http://localhost/index.html や http://localhost:8080/index.html などローカル環境からでも大丈夫でした。