GoogleDriveAPI を使ってブラウザからドライブ上のファイルにアクセスするまでの手順。
Google公式でクイックスタートがあるが、全部英語で毎回読むのが面倒なので日本語化して自分用のメモにしておく。
https://developers.google.com/drive/api/v3/quickstart/js?hl=JA
以下、基本的には↑の順番に沿って自分なりに意訳してます。
完全な和訳ではないのでご注意ください。
準備
・GoogleDriveが使えるGoogleアカウント
・python 2.4以上(http://localhost:8080 を立ち上げるため)
※Pythonを使えと書いてますが、サーバーさえ建てれればなんでもいい。私はChrome拡張機能のWeb Server for Chromeというやつを使った。
Step1: Drive API を使えるようにする
1.下記URLからGoogle Developers Consoleにアクセスし、新規プロジェクトを作成するか既存プロジェクトを使ってAPIを有効化します。
2.ダッシュボード的な画面に遷移すると思うので、左側のメニューから「認証情報」をクリック
3.「OAuth 同意画面」タブをクリック
4.アプリケーション名を入力し(なんでもいい)、アカウントを選択し、「保存」をクリック
5.「認証情報」タブをクリック
6.「認証情報を作成」→「OAuth クライアントID」クリック
7.「ウェブアプリケーション」を選択
8.「名前」はウェブクライアント 1 とかになってると思うのでそのままにして(変えてもいい)、「承認済みの JavaScript 生成元」に検証するURLを入力する。例えば http://localhost:8080 とか、ステージング用に取ってるドメインがあればそれを入力する。
9.「承認済みのリダイレクト URI」は空欄でOK。「作成」クリック。
10.クライアントIDがダイアログで表示されると思うので、コピーしてどこかにメモっておく(あとで使います)
11.続いて「認証情報」→「APIキー」をクリック
12.先程と同じくAPIキーが別ダイアログで表示されるので、これもメモる。「キーを制限する」というボタンもあるが今回は関係ないので無視。
※本番用などで、特定のWebサイトや特定IPアドレス、またはモバイルアプリからのアクセスしか受け付けないようにする場合はキーを制限する必要がある。
Step2: サンプルコードの作成
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>
と <YOUR_API_KEY>
に先程メモっておいた値を入力する。
Githubにもソースがあります。
https://github.com/gsuitedevs/browser-samples/blob/master/drive/quickstart/index.html
Step3: サンプルを実行する
Webサーバーを立ち上げます。
python 2.x 系の場合は
$ python -m SimpleHTTPServer 8000
python 3.x 系の場合は
$ python -m http.server 8000
でサーバーを立ち上げます。
http://localhost:8000 にアクセス。
「Authorize」ボタンを押してGoogleアカウントを認証し、ドライブのファイルを取得できたら成功!
おまけ:”Permission denied to generate login hint for target domain.”で怒られたとき
下記を参考にする。
https://www.sirloin-nagurigaki.net/entry/2019/04/25/231055