LoginSignup
3
0

More than 1 year has passed since last update.

Google Apps Scriptでエンドポイント付きAPIを作る

Last updated at Posted at 2022-05-04

Google Apps Scriptとスプレッドシートだけで簡易的なAPIを作るよ。

仕様

GET /user
ユーザー取得
POST /user/create
ユーザー作成

実装

main.gs
function toJson(data) {
  console.log(ScriptApp.getOAuthToken())
  return ContentService.createTextOutput(JSON.stringify(data))
    .setMimeType(ContentService.MimeType.JSON);
}

function indexOf(id) {
  const sheet = SpreadsheetApp.getActiveSheet();
  const range = sheet.getDataRange();
  const values = range.getValues();
  return values.find((value) => value[0] == id);
}

function doGet(e) {
  const path = e.pathInfo;
  if (path == "user") {
    const query = e.parameter;
    return toJson(indexOf(query.id));
  } else {
    return toJson(null);
  }
}

function doPost(e) {
  const sheet = SpreadsheetApp.getActiveSheet();
  const path = e.pathInfo;
  const postdata = JSON.parse(e.postData.contents);
  if (path == "user/create") {
    sheet.appendRow([postdata.id, postdata.name]);
  } else {
    return toJson(null);
  }
}

完成?

作成したプロジェクトを実行者を自分、アクセスできるユーザーを全員にしてデプロイして実行すると・・・
image.png
動かない
image.png
アクセスできるユーザーを全員にしているため、本来であれば正常にPOSTできるはずだが、認証画面が帰ってきている。

何故正常に動かないのか

exec/の後にパスを続けて書くと、どの設定にしても認証が必要になるみたい。
詳しい理由が知りたいが、調べてもリファレンスに何も書いていなかったためよくわからない。

どうすればいいか

Googleの認証をパスするために、認証情報をパラメーターに加えればいい。

手順

1. プロジェクトの設定から、「appsscript.json」マニフェストファイルをエディタで表示するをチェックをする。

image.png

2. appsscript.jsonにスコープを追加する。

appsscript.json
"oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request" 
]

3. scriptのOAuthトークンを取得する

main.gs
function token() {
  console.log(ScriptApp.getOAuthToken());
}

4. URLパラメーターにaccess_token=取得したトークンを付けてアクセスする

image.png

これで認証をパスして外部からアクセスできる!

補遺

getOAuthTokenの公式リファレンスを見ると、この関数で取得したアクセストークンは数時間で使用できなくなるみたい。
回避方法としては、アクセストークンを発行するだけの別のプロジェクトを作成し、本命のプロジェクトにアクセスする前にトークンの発行をすれば大丈夫。

参考

Google Apps Scriptを使ってサーバーレスファンクションを作る
GAS で OAuth のスコープが足りなくてやったこと
【GAS】Drive上のファイルの共有リンクを取得し、ダイアログからダウンロードさせる

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0