使用Python+OAuth创建Google Forms遇API版本识别错误求解决方案
解决Google Forms API构建服务时的版本错误及替代实现
问题原因
- Google Forms API仅提供v1版本,v2、v3版本不存在,因此调用
build('forms', 'v2')或build('forms', 'v3')会触发UnknownApiNameOrVersion错误。 - 若使用v1仍无法识别API,大概率是本地discovery缓存过期,可通过禁用缓存或清理缓存解决。
正确实现示例(不依赖已弃用的oauth2client)
以下是使用google-auth、google-auth-oauthlib和google-api-python-client的完整可运行代码,用于授权并创建Google表单:
import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # 所需权限范围,创建表单需要forms.body,若需读取可添加forms.readonly SCOPES = ['https://www.googleapis.com/auth/forms.body'] def main(): creds = None # 检查本地是否有已保存的凭证文件 if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # 若无有效凭证,进行授权流程 if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # 保存凭证供下次使用 with open('token.json', 'w') as token: token.write(creds.to_json()) try: # 构建Forms API v1服务,注意版本必须是v1,禁用缓存避免识别问题 service = build('forms', 'v1', credentials=creds, cache_discovery=False) # 创建一个新表单 form = { "info": { "title": "测试表单", } } result = service.forms().create(body=form).execute() print(f"表单创建成功!表单ID: {result['formId']},编辑链接: https://docs.google.com/forms/d/{result['formId']}/edit") # 可选:向表单添加一个多项选择题 update = { "requests": [ { "createItem": { "item": { "title": "你最喜欢的编程语言是?", "questionItem": { "question": { "choiceQuestion": { "type": "RADIO", "options": [ {"value": "Python"}, {"value": "Java"}, {"value": "JavaScript"} ] } } } }, "location": {"index": 0} } } ] } update_result = service.forms().batchUpdate(formId=result['formId'], body=update).execute() print(f"题目添加成功!") except HttpError as error: print(f"发生错误: {error}") if __name__ == '__main__': main()
关键注意事项
- 必须使用
forms和v1作为服务名和版本,这是当前唯一可用的Forms API版本。 cache_discovery=False参数可强制重新获取discovery文档,避免因旧缓存导致的API识别失败。- 需提前在Google Cloud控制台创建项目,启用Forms API,并下载
credentials.json文件到代码目录。 - 首次运行会打开浏览器进行授权,授权后生成
token.json保存凭证,后续运行无需重复授权。
内容的提问来源于stack exchange,提问作者Sudheer Satyanarayana
相关产品推荐
相关产品推荐

