能否用官方客户端库创建Google Form?技术咨询及示例需求
Google Forms API 自动化实现指南
为什么客户端库中找不到Forms API相关内容?
Google Forms API的客户端库确实存在,但并非所有通用客户端库文档都会直接高亮它。以Node.js的googleapis包为例,Forms API属于需要显式引用的服务,且必须先在Google Cloud控制台中启用Forms API服务,否则无法调用。官方文档的通用模板提示是有效的,并非不考虑可行性。
Node.js客户端库创建空白表单示例
步骤1:准备工作
- 在Google Cloud控制台创建项目,启用Google Forms API
- 创建服务账号密钥(JSON格式),下载后保存为
service-account-key.json - 安装依赖:
npm install googleapis
步骤2:代码示例
const { google } = require('googleapis'); const fs = require('fs'); async function createBlankForm() { // 服务账号认证 const auth = new google.auth.GoogleAuth({ keyFile: 'service-account-key.json', scopes: ['https://www.googleapis.com/auth/forms.body'], }); // 初始化Forms API客户端 const forms = google.forms({ version: 'v1', auth }); // 创建空白表单 const response = await forms.forms.create({ requestBody: { info: { title: 'Hello World 空白表单', }, }, }); console.log('创建的表单ID:', response.data.formId); console.log('表单链接:', `https://docs.google.com/forms/d/${response.data.formId}/edit`); } createBlankForm().catch(console.error);
其他客户端库示例(Python)
步骤1:安装依赖
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
步骤2:代码示例
from googleapiclient.discovery import build from google.oauth2.service_account import Credentials SCOPES = ['https://www.googleapis.com/auth/forms.body'] KEY_FILE = 'service-account-key.json' def create_blank_form(): creds = Credentials.from_service_account_file(KEY_FILE, scopes=SCOPES) service = build('forms', 'v1', credentials=creds) # 创建表单请求 form = { "info": { "title": "Hello World 空白表单" } } response = service.forms().create(body=form).execute() print(f"创建的表单ID: {response['formId']}") print(f"表单链接: https://docs.google.com/forms/d/{response['formId']}/edit") if __name__ == '__main__': create_blank_form()
使用curl创建表单示例
步骤1:获取访问令牌
使用服务账号密钥获取Bearer令牌:
curl -s -X POST "https://oauth2.googleapis.com/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=$(openssl dgst -sha256 -sign service-account-key.json <(echo -n '{"iss":"YOUR_SERVICE_ACCOUNT_EMAIL","scope":"https://www.googleapis.com/auth/forms.body","aud":"https://oauth2.googleapis.com/token","exp":'$(($(date +%s)+3600))',"iat":'$(date +%s)'}') | openssl base64 -A)"
替换YOUR_SERVICE_ACCOUNT_EMAIL为服务账号邮箱,执行后会返回包含access_token的JSON。
步骤2:创建表单
curl -X POST "https://forms.googleapis.com/v1/forms" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "info": { "title": "Hello World 空白表单" } }'
替换YOUR_ACCESS_TOKEN为上一步获取的令牌。
使用JavaScript fetch创建表单示例
// 建议在Node.js环境运行,浏览器环境使用服务账号密钥存在安全风险 const jwt = require('jsonwebtoken'); const fs = require('fs'); async function getAccessToken() { const serviceAccount = JSON.parse(fs.readFileSync('service-account-key.json', 'utf8')); const assertion = jwt.sign( { iss: serviceAccount.client_email, scope: 'https://www.googleapis.com/auth/forms.body', aud: 'https://oauth2.googleapis.com/token', exp: Math.floor(Date.now() / 1000) + 3600, iat: Math.floor(Date.now() / 1000) }, serviceAccount.private_key, { algorithm: 'RS256' } ); const response = await fetch('https://oauth2.googleapis.com/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=${assertion}` }); const data = await response.json(); return data.access_token; } async function createFormWithFetch() { const token = await getAccessToken(); const response = await fetch('https://forms.googleapis.com/v1/forms', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ info: { title: 'Hello World 空白表单' } }) }); const formData = await response.json(); console.log('表单ID:', formData.formId); console.log('表单链接:', `https://docs.google.com/forms/d/${formData.formId}/edit`); } createFormWithFetch().catch(console.error);
内容的提问来源于stack exchange,提问作者Daniel Kaplan
相关产品推荐
相关产品推荐

