Google Apps 脚本快速入门

快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。

Google Workspace 快速入门使用 API 客户端库来处理身份验证和授权流程的某些详细信息。我们建议您在自己的应用中使用客户端库。本快速入门使用适用于测试环境的简化身份验证方法。对于生产环境,我们建议您先了解身份验证和授权,然后再选择适合您应用的访问凭据

创建向 Google 文档 API 发出请求的 Google Apps 脚本

目标

  • 创建脚本。
  • 启用 Google 文档 API。
  • 运行示例。

前提条件

  • Google 账号
  • 访问 Google 云端硬盘

创建脚本

  1. 转到 script.google.com/create 创建新脚本。
  2. 将脚本编辑器的内容替换为以下代码:

docs/quickstart/quickstart.gs
/**
 * Prints the title of the sample document:
 * https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/get
 */
function printDocTitle() {
  const documentId = '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE';
  try {
    // Get the document using document id
    const doc = Docs.Documents.get(documentId);
    // Log the title  of document.
    console.log('The title of the doc is: %s', doc.title);
  } catch (err) {
    // TODO (developer) - Handle exception from Docs API
    console.log('Failed to found document with an error %s', err.message);
  }
}

  1. 点击“保存”
  2. 点击未命名项目,输入 quickstart,然后点击 Rename

启用 Google 文档 API

  1. 打开 Apps 脚本项目。
  2. 点击编辑器
  3. 点击服务旁边的“添加服务”图标
  4. 选择 Google 文档 API,然后点击添加

运行示例

在 Apps 脚本编辑器中,点击运行

首次运行示例时,它会提示您授予访问权限:

  1. 点击查看权限
  2. 选择账号。
  3. 点击允许

脚本的执行日志会显示在窗口底部。

后续步骤