設定 Apps Script 專案,直接透過 REST 呼叫呼叫 Google 表單 API 非常簡單。假設您已設定 Google Cloud 專案,請執行下列操作:
- 建立新的 Apps Script 專案。
- 變更相關聯的 Google Cloud 專案編號,以符合您為 Google 表單 API 啟用的專案。
- 編輯資訊清單檔案 (
appsscript.json
),新增必要的 OAuth 範圍。 - 新增 Apps Script 程式碼,擷取 OAuth 權杖,並使用權杖發出 REST 呼叫。
以下快速介紹這些步驟。
建立及設定新的 Apps Script 專案
- 使用設定 GCP 專案時使用的 Google ID,前往 Apps Script 資訊主頁,然後按一下「新專案」。
- 開啟專案後,按一下「專案設定」 。
- 勾選「在編輯器中顯示『appsscript.json』資訊清單檔案」核取方塊。
- 在「Google Cloud Platform (GCP) 專案」部分,按一下「變更專案」,然後輸入您為 Forms API 設定的 GCP 專案編號。
您的 Apps Script 專案現已設定完成,可以存取 Google Forms API。下一個必要步驟是新增適當的 OAuth 範圍。
新增 OAuth 範圍
如要在 Apps Script 中產生適當範圍的 OAuth 權杖,您必須在專案的資訊清單檔案中設定必要範圍。
- 在編輯器中開啟
appsscript.json
。 將範圍新增至資訊清單的主體。
{ ... "oauthScopes": [ "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.readonly", "https://www.googleapis.com/auth/forms.body", "https://www.googleapis.com/auth/forms.body.readonly", "https://www.googleapis.com/auth/forms.responses.readonly" ], ... }
按一下「儲存專案」
,並視需要修正任何語法錯誤。您的專案現在應該可以透過 REST 呼叫來呼叫 Google 表單 API。
新增 Apps Script 程式碼以呼叫 API
在編寫呼叫表單的程式碼之前,您必須找出擁有回應的表單,並記下表單 ID。編輯表單時,您可以在網址中找到表單 ID:
https://docs.google.com/forms/d/<FORM_ID>/edit
如要呼叫 API,請使用 Apps Script UrlFetchApp
呼叫。
開啟 Code.gs,然後加入下列程式碼:
將
YOUR_FORM_ID
替換為您先前記下的值。範例:
var formId = 'tL5ygBC8zpbTnTp76JCZdIg80hA-cnpbTnTjnsewCKJH';
按一下
「儲存專案」,並視需要修正任何語法錯誤。
測試程式碼
- 按一下 「Run」。
- 視需要使用先前相同的 Google ID 授權專案。
啟動後,您應該會在執行記錄中看到類似以下的回應:
Execution started Calling the Forms API! OAuth token is: ya29.a0ARrdaM8IMjtlv… formsAPIUrl is: https://forms.googleapis.com/v1beta/forms/…/responses Response from Forms.responses was: { "responses": [ { "responseId":"...", "createTime": "2021-03-25T01:23:58.146Z", "lastSubmittedTime": "2021-03-25T01:23:58.146607Z", "answers": { "1e9b0ead": { "questionId": "1e9b0ead", "textAnswers": { "answers": [ { "value": "Red" } ] } }, "773ed8f3": { "questionId": "773ed8f3", "textAnswers": { "answers": [ { "value": "Tesla" } ] } } } } ] } Execution completed
後續步驟
成功使用 Apps Script 呼叫 API 後,請參閱參考文件,並嘗試呼叫其他 API。