飞书调用手册

创建云文档并追加正文

先创建一篇 Docx 文档,再在根块末尾追加一个普通文本块。

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

接入准备

  • 应用开通 docx:document,或分别开通 docx:document:create 和 docx:document:write_only。
  • 使用自建应用令牌;新建文档属于当前调用身份。操作他人文档还需独立的文档编辑权限。

准备环境变量

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

FEISHU_ACCESS_TOKEN
先运行应用消息场景的获取凭证操作,将响应 access_token 放入服务端环境变量;不是 App Secret。
FEISHU_DOCUMENT_ID
第一步创建结果中的 document_id。
终端
export FEISHU_ACCESS_TOKEN='replace_with_tenant_access_token'
export FEISHU_DOCUMENT_ID='dox_replace_with_document_id'

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

调用步骤

  1. 01

    按应用消息场景获取令牌,执行创建文档请求。

  2. 02

    从 data.document.document_id 取得新文档 ID,保存为 FEISHU_DOCUMENT_ID。

  3. 03

    根块 ID 与 document_id 相同,第二步在根块末尾追加正文。

  4. 04

    在需要给人类成员查看时,另行分享该文档;仅创建成功不会自动向全部成员开放。

调用 01

创建新版文档

不填 folder_token 时创建到调用身份的根目录;本例避免指定未经授权的个人文件夹。

POSThttps://open.feishu.cn/open-apis/docx/v1/documents

请求头

Authorization
Bearer ${FEISHU_ACCESS_TOKEN}
Content-Type
application/json; charset=utf-8

参数说明

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

字段 / 位置类型 / 必填说明
title请求体string可选纯文本标题,填写时长度 1–800 字符。
folder_token请求体string可选省略表示根目录;tenant_access_token 只能指定应用创建的文件夹,不可随意填他人的文件夹。

调用代码

替换示例 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://open.feishu.cn/open-apis/docx/v1/documents" \
  --header "Authorization: Bearer ${FEISHU_ACCESS_TOKEN}" \
  --header "Content-Type: application/json; charset=utf-8" \
  --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://open.feishu.cn/open-apis/docx/v1/documents")
headers = {
    "Authorization": expand("Bearer ${FEISHU_ACCESS_TOKEN}"),
    "Content-Type": expand("application/json; charset=utf-8"),
}
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))
if isinstance(result, dict) and "code" in result and result["code"] != 0:
    raise SystemExit("平台返回业务错误,请结合下方排错说明检查响应")
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://open.feishu.cn/open-apis/docx/v1/documents");
const headers = Object.fromEntries(
  Object.entries({
  "Authorization": "Bearer ${FEISHU_ACCESS_TOKEN}",
  "Content-Type": "application/json; charset=utf-8"
}).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));
if (Object.hasOwn(result, "code") && result["code"] !== 0) {
  throw new Error('平台返回业务错误,请结合下方排错说明检查响应');
}

返回示例

按官方字段整理的节选示意,使用虚构 ID,不是实测结果。把 document_id 用于下一步根块写入。 以下为结构示意,非本站实测结果。

JSON
{
  "code": 0,
  "msg": "success",
  "data": {
    "document": {
      "document_id": "dox_example",
      "revision_id": 1,
      "title": "API 接入测试记录"
    }
  }
}

常见错误与排查

1770039目标文件夹不存在
核对 folder_token;不确定时省略,先在根目录测试。
1770040缺少文件夹权限
确认调用身份及文件夹是否支持当前应用创建。
99991400应用请求限频
降至每秒 3 次以内并指数退避。

调用注意

  • 应用上限每秒 3 次;同一文件夹中串行创建。
调用 02

在根块追加文本

仅演示新增内容,document_revision_id=-1 使用最新版本;多人协作修改重要内容前应先读取版本与位置。

POSThttps://open.feishu.cn/open-apis/docx/v1/documents/${FEISHU_DOCUMENT_ID}/blocks/${FEISHU_DOCUMENT_ID}/children?document_revision_id=-1

请求头

Authorization
Bearer ${FEISHU_ACCESS_TOKEN}
Content-Type
application/json; charset=utf-8

参数说明

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

字段 / 位置类型 / 必填说明
document_id / block_idPathstring必填本例都用新文档的 document_id,表示根块。
document_revision_idQueryinteger可选默认 -1 表示最新版本;也可指定已读取的 revision_id。
index请求体integer可选默认 -1,追加到末尾;0 是第一个子块位置。
children请求体block[]必填本例文本块 block_type=2,正文在 text.elements[].text_run.content;一次创建 1–50 个子块。
client_tokenQuerystring可选可设置唯一幂等标识,响应会回传,超时重试复用同一个标识。

调用代码

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

cURL
cat > request-body.json <<'JSON'
{
  "index": -1,
  "children": [
    {
      "block_type": 2,
      "text": {
        "elements": [
          {
            "text_run": {
              "content": "这是通过 API 追加的测试正文。"
            }
          }
        ]
      }
    }
  ]
}
JSON

# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request POST \
  --url "https://open.feishu.cn/open-apis/docx/v1/documents/${FEISHU_DOCUMENT_ID}/blocks/${FEISHU_DOCUMENT_ID}/children?document_revision_id=-1" \
  --header "Authorization: Bearer ${FEISHU_ACCESS_TOKEN}" \
  --header "Content-Type: application/json; charset=utf-8" \
  --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://open.feishu.cn/open-apis/docx/v1/documents/${FEISHU_DOCUMENT_ID}/blocks/${FEISHU_DOCUMENT_ID}/children?document_revision_id=-1")
headers = {
    "Authorization": expand("Bearer ${FEISHU_ACCESS_TOKEN}"),
    "Content-Type": expand("application/json; charset=utf-8"),
}
body = {
    "index": -1,
    "children": [
        {
            "block_type": 2,
            "text": {
                "elements": [
                    {
                        "text_run": {
                            "content": "这是通过 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))
if isinstance(result, dict) and "code" in result and result["code"] != 0:
    raise SystemExit("平台返回业务错误,请结合下方排错说明检查响应")
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://open.feishu.cn/open-apis/docx/v1/documents/${FEISHU_DOCUMENT_ID}/blocks/${FEISHU_DOCUMENT_ID}/children?document_revision_id=-1");
const headers = Object.fromEntries(
  Object.entries({
  "Authorization": "Bearer ${FEISHU_ACCESS_TOKEN}",
  "Content-Type": "application/json; charset=utf-8"
}).map(([key, value]) => [key, expand(value)])
);
const body = {
  "index": -1,
  "children": [
    {
      "block_type": 2,
      "text": {
        "elements": [
          {
            "text_run": {
              "content": "这是通过 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));
if (Object.hasOwn(result, "code") && result["code"] !== 0) {
  throw new Error('平台返回业务错误,请结合下方排错说明检查响应');
}

返回示例

按官方字段整理的节选示意,使用虚构 ID,不是实测结果。返回新块 ID 及 document_revision_id;保存以便后续精确编辑。 以下为结构示意,非本站实测结果。

JSON
{
  "code": 0,
  "msg": "success",
  "data": {
    "children": [
      {
        "block_id": "dox_block_example",
        "block_type": 2,
        "parent_id": "dox_example",
        "text": {
          "elements": [
            {
              "text_run": {
                "content": "这是通过 API 追加的测试正文。"
              }
            }
          ]
        }
      }
    ],
    "document_revision_id": 2
  }
}

常见错误与排查

1770032无文档权限
为当前应用添加文档编辑权限;Token 权限不能代替资源分享。
1770006文档块结构不匹配
核对 block_type 与 text 结构,先使用普通文本块最小示例。
HTTP 429单篇文档并发编辑被限流
同文档串行写入;单文档编辑不超过每秒 3 次。

调用注意

  • 应用每秒 3 次、单篇文档并发编辑每秒 3 次;批量和单条编辑共同消耗限制。
  • 只追加一个文本块;没有覆盖或清空原文的操作。

注意事项

  • 创建及写块不是导入 Markdown;标题、列表、图片等应使用各自块结构。

核验来源

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

  1. 01
  2. 02
    创建新版文档核验日期 2026-10-15
  3. 03
    创建文档块核验日期 2026-10-15

飞书的其他调用手册

← 返回飞书的全部功能