Google 文档与文件 API调用手册

创建 Docs 文档并写入正文

先创建空文档,再向新文档插入一段文字,并读取确认。

官方资料核对 2026-10-15示例代码,未进行真实接口实测
← 返回平台功能

接入准备

  • 访问令牌含 https://www.googleapis.com/auth/documents;对目标文档有编辑权限。

准备环境变量

示例值需要替换为自己的凭证或资源 ID。代码在本机或服务端运行;密钥不应放进公开网页。

GOOGLE_ACCESS_TOKEN
先执行本站本平台的获取与刷新用户令牌场景;令牌必须含当前场景要求的 scope,不能使用 API Key。
GOOGLE_DOCUMENT_ID
来自创建操作的 documentId;示例值虚构。
终端
export GOOGLE_ACCESS_TOKEN='replace_with_oauth_access_token'
export GOOGLE_DOCUMENT_ID='example_document_id'

以上 export 适用于 macOS / Linux 的终端,在同一终端内运行后续代码。Python 示例保存为 request.py 后执行 python3 request.py。

调用步骤

  1. 01

    先在本站 OAuth 场景申请 documents 范围,取得 GOOGLE_ACCESS_TOKEN;只申请 Drive 元数据范围不能编辑文档。

  2. 02

    执行创建操作,取响应 documentId,设置为 GOOGLE_DOCUMENT_ID;不要使用下方虚构 ID。

  3. 03

    执行 batchUpdate 插入正文。示例仅适用于新建空文档的第一标签;编辑已有多人协作文档前应读取真实结构与修订控制。

  4. 04

    最后执行读取操作,检查 tabs[].documentTab.body.content;API 接受请求与网页中内容准确出现应分别确认。

调用 01

创建空文档

create 只以 title 建立空文档,正文通过下一步插入。

POSThttps://docs.googleapis.com/v1/documents

请求头

Authorization
Bearer ${GOOGLE_ACCESS_TOKEN}
Content-Type
application/json

参数说明

参数表可左右滑动,查看完整说明。

字段 / 位置类型 / 必填说明
title请求体string可选文档标题;本例为接入测试文档。

调用代码

替换示例 ID 与请求体内容后运行。cURL 会报 HTTP 错误,业务状态还需按下方返回示例核对。

cURL
cat > request-body.json <<'JSON'
{
  "title": "API 接入测试文档"
}
JSON

# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request POST \
  --url "https://docs.googleapis.com/v1/documents" \
  --header "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request-body.json
Python 3
import json
import os
import re
import urllib.request
import urllib.error

def expand(value):
    return re.sub(r"\$\{([A-Z][A-Z0-9_]*)\}",
                  lambda match: os.environ[match.group(1)], value)

url = expand("https://docs.googleapis.com/v1/documents")
headers = {
    "Authorization": expand("Bearer ${GOOGLE_ACCESS_TOKEN}"),
    "Content-Type": expand("application/json"),
}
body = {
    "title": "API 接入测试文档",
}
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(url, data=data, headers=headers, method="POST")
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
except urllib.error.HTTPError as error:
    print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
    raise SystemExit(1)
print(json.dumps(result, ensure_ascii=False, indent=2))
Node.js
// Node.js 22+,保存为 request.mjs 后运行 node request.mjs
function expand(value) {
  return value.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (_, name) => {
    if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`);
    return process.env[name];
  });
}

const url = expand("https://docs.googleapis.com/v1/documents");
const headers = Object.fromEntries(
  Object.entries({
  "Authorization": "Bearer ${GOOGLE_ACCESS_TOKEN}",
  "Content-Type": "application/json"
}).map(([key, value]) => [key, expand(value)])
);
const body = {
  "title": "API 接入测试文档"
};
const response = await fetch(url, {
  method: "POST",
  headers,
  body: JSON.stringify(body),
  signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
const result = JSON.parse(text);
console.log(JSON.stringify(result, null, 2));

返回示例

按官方字段整理的响应结构示意,ID、文本和数字均为虚构,非接口实测结果。取 documentId 供后续使用。 以下为结构示意,非本站实测结果。

JSON
{
  "documentId": "example_document_id",
  "title": "API 接入测试文档"
}

常见错误与排查

HTTP 401访问令牌缺失、无效或已过期。
按本站授权场景使用 refresh_token 刷新;不要把 client_secret 或 API Key 当成 access_token。
HTTP 403权限不足、组织策略限制或达到用户配额。
读取 error.details/reason;核对已授权 scope、文件共享权限和项目配额,不能只重复授权同一个 scope。
HTTP 429达到服务请求频率限制。
采用带随机抖动的指数退避,限制重试次数,并减少批量轮询。

调用注意

  • create 不会自动把请求中其他文档内容写入;正文与格式编辑属于 batchUpdate。
  • 重复执行会创建多个文件;超时后先确认是否已成功,避免无条件重试。
调用 02

在新文档正文开头插入文本

将上一步真实 documentId 放入环境变量;index=1 对新建空文档有效。

POSThttps://docs.googleapis.com/v1/documents/${GOOGLE_DOCUMENT_ID}:batchUpdate

请求头

Authorization
Bearer ${GOOGLE_ACCESS_TOKEN}
Content-Type
application/json

参数说明

参数表可左右滑动,查看完整说明。

字段 / 位置类型 / 必填说明
documentIdPathstring必填创建返回的文档 ID。
requests请求体array必填批量编辑动作数组,所有动作先校验再一起应用。
requests[].insertText.text请求体string必填要插入的纯文本;换行用 。
requests[].insertText.location.index请求体integer必填本例 1;已有文档必须按真实结构选位置。

调用代码

替换示例 ID 与请求体内容后运行。cURL 会报 HTTP 错误,业务状态还需按下方返回示例核对。

cURL
cat > request-body.json <<'JSON'
{
  "requests": [
    {
      "insertText": {
        "location": {
          "index": 1
        },
        "text": "这是通过 API 写入的测试正文。\n"
      }
    }
  ]
}
JSON

# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request POST \
  --url "https://docs.googleapis.com/v1/documents/${GOOGLE_DOCUMENT_ID}:batchUpdate" \
  --header "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request-body.json
Python 3
import json
import os
import re
import urllib.request
import urllib.error

def expand(value):
    return re.sub(r"\$\{([A-Z][A-Z0-9_]*)\}",
                  lambda match: os.environ[match.group(1)], value)

url = expand("https://docs.googleapis.com/v1/documents/${GOOGLE_DOCUMENT_ID}:batchUpdate")
headers = {
    "Authorization": expand("Bearer ${GOOGLE_ACCESS_TOKEN}"),
    "Content-Type": expand("application/json"),
}
body = {
    "requests": [
        {
            "insertText": {
                "location": {
                    "index": 1,
                },
                "text": "这是通过 API 写入的测试正文。\n",
            },
        },
    ],
}
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(url, data=data, headers=headers, method="POST")
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
except urllib.error.HTTPError as error:
    print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
    raise SystemExit(1)
print(json.dumps(result, ensure_ascii=False, indent=2))
Node.js
// Node.js 22+,保存为 request.mjs 后运行 node request.mjs
function expand(value) {
  return value.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (_, name) => {
    if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`);
    return process.env[name];
  });
}

const url = expand("https://docs.googleapis.com/v1/documents/${GOOGLE_DOCUMENT_ID}:batchUpdate");
const headers = Object.fromEntries(
  Object.entries({
  "Authorization": "Bearer ${GOOGLE_ACCESS_TOKEN}",
  "Content-Type": "application/json"
}).map(([key, value]) => [key, expand(value)])
);
const body = {
  "requests": [
    {
      "insertText": {
        "location": {
          "index": 1
        },
        "text": "这是通过 API 写入的测试正文。\n"
      }
    }
  ]
};
const response = await fetch(url, {
  method: "POST",
  headers,
  body: JSON.stringify(body),
  signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
const result = JSON.parse(text);
console.log(JSON.stringify(result, null, 2));

返回示例

按官方字段整理的响应结构示意,ID、文本和数字均为虚构,非接口实测结果。普通 insertText 的 replies 项可以是空对象;不等于没有执行。 以下为结构示意,非本站实测结果。

JSON
{
  "documentId": "example_document_id",
  "replies": [
    {}
  ],
  "writeControl": {
    "requiredRevisionId": "example_revision"
  }
}

常见错误与排查

HTTP 401访问令牌缺失、无效或已过期。
按本站授权场景使用 refresh_token 刷新;不要把 client_secret 或 API Key 当成 access_token。
HTTP 403权限不足、组织策略限制或达到用户配额。
读取 error.details/reason;核对已授权 scope、文件共享权限和项目配额,不能只重复授权同一个 scope。
HTTP 429达到服务请求频率限制。
采用带随机抖动的指数退避,限制重试次数,并减少批量轮询。
HTTP 400插入位置、请求结构或范围不合法。
确认是新建空文档、index 在可编辑段落内;任何一个 batch 动作无效会导致整批不应用。

调用注意

  • 本例省略 tabId,作用于第一标签;已有多标签文档应先读取 tabs 与目标 tabId,再明确指定。
  • 插入不是幂等操作;超时后先读取确认,重复发送会重复插入。
调用 03

读取正文确认

includeTabsContent=true 请求包含各标签内容,避免只检查旧的顶层 body 字段。

GEThttps://docs.googleapis.com/v1/documents/${GOOGLE_DOCUMENT_ID}?includeTabsContent=true

请求头

Authorization
Bearer ${GOOGLE_ACCESS_TOKEN}

参数说明

参数表可左右滑动,查看完整说明。

字段 / 位置类型 / 必填说明
documentIdPathstring必填目标文档 ID。
includeTabsContentQueryboolean可选本例 true;从 tabs 的 documentTab 中读取正文。

调用代码

替换示例 ID 与请求体内容后运行。cURL 会报 HTTP 错误,业务状态还需按下方返回示例核对。

cURL
# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request GET \
  --url "https://docs.googleapis.com/v1/documents/${GOOGLE_DOCUMENT_ID}?includeTabsContent=true" \
  --header "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"
Python 3
import json
import os
import re
import urllib.request
import urllib.error

def expand(value):
    return re.sub(r"\$\{([A-Z][A-Z0-9_]*)\}",
                  lambda match: os.environ[match.group(1)], value)

url = expand("https://docs.googleapis.com/v1/documents/${GOOGLE_DOCUMENT_ID}?includeTabsContent=true")
headers = {
    "Authorization": expand("Bearer ${GOOGLE_ACCESS_TOKEN}"),
}
data = None
request = urllib.request.Request(url, data=data, headers=headers, method="GET")
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
except urllib.error.HTTPError as error:
    print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
    raise SystemExit(1)
print(json.dumps(result, ensure_ascii=False, indent=2))
Node.js
// Node.js 22+,保存为 request.mjs 后运行 node request.mjs
function expand(value) {
  return value.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (_, name) => {
    if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`);
    return process.env[name];
  });
}

const url = expand("https://docs.googleapis.com/v1/documents/${GOOGLE_DOCUMENT_ID}?includeTabsContent=true");
const headers = Object.fromEntries(
  Object.entries({
  "Authorization": "Bearer ${GOOGLE_ACCESS_TOKEN}"
}).map(([key, value]) => [key, expand(value)])
);
const response = await fetch(url, {
  method: "GET",
  headers,
  signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
const result = JSON.parse(text);
console.log(JSON.stringify(result, null, 2));

返回示例

按官方字段整理的响应结构示意,ID、文本和数字均为虚构,非接口实测结果。此结构示意省略分页、样式与其他内容节点;实际需遍历标签和段落元素。 以下为结构示意,非本站实测结果。

JSON
{
  "documentId": "example_document_id",
  "title": "API 接入测试文档",
  "tabs": [
    {
      "tabProperties": {
        "tabId": "example_tab"
      },
      "documentTab": {
        "body": {
          "content": [
            {
              "startIndex": 1,
              "paragraph": {
                "elements": [
                  {
                    "textRun": {
                      "content": "这是通过 API 写入的测试正文。\n"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  ]
}

常见错误与排查

HTTP 401访问令牌缺失、无效或已过期。
按本站授权场景使用 refresh_token 刷新;不要把 client_secret 或 API Key 当成 access_token。
HTTP 403权限不足、组织策略限制或达到用户配额。
读取 error.details/reason;核对已授权 scope、文件共享权限和项目配额,不能只重复授权同一个 scope。
HTTP 429达到服务请求频率限制。
采用带随机抖动的指数退避,限制重试次数,并减少批量轮询。

调用注意

  • 读取成功不代替业务校验;需要确认写入文字、标签和重复执行状态。

注意事项

  • 核验日官方仍说明标准 API 使用无额外费用,同时公告 2026 年晚些时候计划对超配额用量计费;不把当前规则写成永久免费承诺。以项目配额及官方生效通知为准。
  • Docs 当前默认每项目每分钟 600 次写请求、每用户每项目每分钟 60 次写请求;以实际项目配额为准。

核验来源

本站按官方资料整理本场景的必要调用步骤与代码,覆盖范围以本页列出的接口为准。官方资料用于追溯规范及查看变更。

  1. 01
  2. 02
    Docs API 配额与费用核验日期 2026-10-15
  3. 03
    Docs documents.create核验日期 2026-10-15
  4. 04
    Docs documents.batchUpdate核验日期 2026-10-15
  5. 05
  6. 06
    Docs documents.get核验日期 2026-10-15

Google 文档与文件 API的其他调用手册

← 返回Google 文档与文件 API的全部功能