如何通过Google Apps Script API重命名Google Apps Script项目?
如何通过API重命名Google Apps Script项目
我之前也碰到过这个困惑——一开始盯着Google Apps Script API找方法,结果发现根本没有直接修改项目名称的接口。后来才反应过来:Google Apps Script项目本质上就是Google Drive中的一个特殊文件,所以用Google Drive API就能轻松搞定重命名!
具体步骤
1. 准备工作
- 确保你已经在Google Cloud Console中启用了Google Drive API(搜索"Drive API"即可找到并启用)
- 授权时需要包含合适的权限范围,比如
https://www.googleapis.com/auth/drive(全Drive权限)或者更受限的https://www.googleapis.com/auth/drive.file(仅操作已授权的文件)
2. 直接用HTTP请求调用
你可以发送一个PUT请求到Drive API的文件更新端点:
PUT https://www.googleapis.com/drive/v3/files/{你的Script项目文件ID} Authorization: Bearer {你的授权令牌} Content-Type: application/json { "name": "你的新项目名称" }
3. 客户端库代码示例(以Python为例)
如果用代码实现,官方客户端库会更省心:
from googleapiclient.discovery import build from google.oauth2.credentials import Credentials # 加载已有的OAuth2授权凭据(比如通过授权流程生成的token.json) creds = Credentials.from_authorized_user_file('token.json') drive_service = build('drive', 'v3', credentials=creds) # 替换为你的Script项目ID和想要设置的新名称 script_project_id = "abc123XYZ...(你的项目ID)" new_project_name = "我的新Script项目" # 执行重命名操作 file_metadata = {"name": new_project_name} drive_service.files().update(fileId=script_project_id, body=file_metadata).execute() print(f"项目已成功重命名为:{new_project_name}")
关键注意点
- 如何获取Script项目的文件ID? 打开你的Apps Script项目,URL格式是
https://script.google.com/d/{项目ID}/edit,其中d/和/edit之间的字符串就是文件ID。 - 确保你对目标Script项目有编辑权限(所有者或协作者编辑权限),否则会返回权限错误。
- Google Apps Script API的
projects.update方法无法修改项目名称,因为该接口的元数据字段不包含name属性,所以必须用Drive API操作。
内容的提问来源于stack exchange,提问作者 GhostKU
相关产品推荐
相关产品推荐

