設定 Apps Script 專案,透過 REST 呼叫直接呼叫 Google Forms API 的程序很簡單。假設您已設定 Google Cloud 專案,請執行下列操作:
- 建立新的 Apps Script 專案。
- 將相關聯的 Google Cloud 專案編號變更為您為 Google Forms 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 Forms 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';按一下「儲存專案」,並視需要修正語法錯誤。
測試程式碼
- 按一下「執行」。
- 使用與先前相同的 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 發出其他呼叫。