設定 Apps Script 專案以便直接透過 REST 呼叫呼叫 Google Form API。假設您已設定 Google Cloud 專案,請執行以下操作:
- 建立新的 Apps Script 專案。
- 變更相關聯的 Google Cloud 專案編號,以符合您為 Google 表單 API 啟用的專案。
- 編輯資訊清單檔案 (
appsscript.json
) 以新增必要的 OAuth 範圍。 - 新增 Apps Script 程式碼以擷取 OAuth 權杖並使用權杖發出 REST 呼叫。
以下是這些步驟的快速逐步操作說明。
建立及設定新的 Apps Script 專案
- 使用您設定 GCP 專案時使用的 Google ID,前往 Apps Script 資訊主頁,然後按一下「New project」。
- 專案開啟後,按一下 「Project Settings」(專案設定)。
- 勾選「在編輯器中顯示「appsscript.json」資訊清單檔案」核取方塊。
- 在「Google Cloud Platform (GCP) Project」部分,按一下「Change project」,然後輸入您為 Forms API 設定的 GCP 專案編號。
您的 Apps Script 專案現已設定完畢,可以存取 Google Form 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 Form 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';
按一下
「Save project」(儲存專案),然後視需要修正任何語法錯誤。
測試程式碼
- 按一下 「Run」(執行)。
- 使用與先前相同的 Google ID,視需要授權專案。
啟動後,您應該會在「Execution log」(執行記錄) 中看到類似以下的回應:
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 進行其他呼叫。