# 飞书文档 (Docx) API 实战笔记 ## Wiki → Docx token 转换 飞书知识库 (Wiki) 的 URL token 和文档 (Docx) 的 obj_token 不同。读取 Wiki 文档内容必须先转换: ``` Wiki URL: https://xxx.feishu.cn/wiki/{wiki_token} ↓ GET /open-apis/wiki/v2/spaces/get_node?token={wiki_token} ↓ Response: node.obj_token = docx_document_id (obj_type = "docx") ↓ GET /open-apis/docx/v1/documents/{obj_token}/blocks ``` ## 文档读写权限模型 文档权限和 Bitable/IM 权限完全独立。 | 操作 | 需要条件 | |------|----------| | 读取文档 blocks | 应用有 docx:document:readonly + 文档对应用可见 | | 插入 text block | 应用有 docx:document (写) + 文档协作者中包含该应用 | | 插入 image block | ❌ API 不支持创建 | | 替换已有 image block 的图片 | ✅ 通过 replace_image + Drive upload_all(见下方) | ### 文档协作授权(关键陷阱) 即使应用有 docx:document 写权限 scope,文档本身也必须把应用加为协作者: 1. 打开文档 → 右上角「分享」按钮 2. 搜索应用名(如 "pixel phone agent") 3. 权限选「可编辑」 4. 确认 症状:不授权时写入返回 code:1770032 forBidden(HTTP 403)。 区别于权限 scope 缺失:scope 缺失返回 404;文档未授权返回 403。 ## Block 类型速查 | block_type | 名称 | 内容字段 | |------------|------|----------| | 1 | Page (根) | children[] | | 2 | Text | text.elements[].text_run.content | | 3-12 | Heading 1-10 | headingN.elements[] | | 13 | Bullet list | bullet.elements[] | | 14 | Ordered list | ordered.elements[] | | 15 | Code block | code.elements[] | | 19 | Divider | (无内容) | | 27 | Image | image.{token,width,height,align,scale} | | 34 | Unknown (video?) | — | ## 插入 Text Block(支持) ```python POST /open-apis/docx/v1/documents/{doc_id}/blocks/{doc_id}/children body = { "index": N, "children": [{ "block_type": 2, "text": {"elements": [{"text_run": {"content": "内容"}}]} }] } ``` 批量插入:children 数组可含多个 block。反向插入(从后往前)避免索引偏移。 ## 删除 Block(支持) ```python DELETE /open-apis/docx/v1/documents/{doc_id}/blocks/{doc_id}/children/batch_delete body = {"start_index": 0, "end_index": 1} ``` 单个 block DELETE 不支持(404),必须用 batch_delete。 ## ❌ 创建 Image Block(不支持) 飞书 Docx API 不支持通过 API 创建图片 block (block_type=27)。 错误码: 1770029 "block not support to create" 尝试过的方式均失败:block_type 27/22/29/30/31,各种 image 字段组合,PATCH 更新,IM image_key 作为 token。 根因:create children 端点只支持 text 类 block,不支持媒体类 block。 ## ✅ 替换已有 Image Block 的图片(支持!但慎用) > **⚠️ 安全警告**: `replace_image` 是**破坏性操作** — 会永久覆盖原图。飞书没有版本历史 API,一旦替换无法通过 API 恢复。 > > **铁律**: 用户说「在文档中插入图片」「把图放在对应章节下面」时,不要用 `replace_image` 替换已有图片。应该:把图发到飞书聊天 → 让用户手动拖到文档中。 > > 只有用户明确说「替换这张图」时才用 `replace_image`,且执行前必须先记录原始 token。 虽然不能创建图片 block,但可以**替换已有图片 block 中的图片内容**。这是 2026-07-21 实战验证的路径。 ### 两步流程 ```python import requests TOKEN = "t-g1047..." DOC_ID = "FGbsdJvCUohmxkxSnatcYvtdn2b" # Step 1: 上传新图到 Drive # ⚠️ parent_node 必须是 image block 的 block_id,不是文档 ID! # ⚠️ parent_type 必须小写 "docx_image" img_path = "/path/to/new_image.png" img_size = os.path.getsize(img_path) result = requests.post( 'https://open.feishu.cn/open-apis/drive/v1/medias/upload_all', headers={'Authorization': f'Bearer {TOKEN}'}, data={ 'file_name': 'new.png', 'parent_type': 'docx_image', 'parent_node': image_block_id, # ⚠️ block_id, not doc_id 'size': str(img_size), }, files={'file': ('new.png', open(img_path, 'rb'), 'image/png')}, timeout=30 ) file_token = result.json()['data']['file_token'] # Step 2: 用 replace_image 替换图片 # ⚠️ 字段名是 "replace_image",不是 "update_image" result = requests.patch( f"https://open.feishu.cn/open-apis/docx/v1/documents/{DOC_ID}/blocks/{image_block_id}", headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'}, json={"replace_image": {"token": file_token}}, timeout=15 ) # → code=0, success! ``` ### 关键陷阱 | 陷阱 | 正确做法 | |------|----------| | `parent_type` 大写 `DOCX_IMAGE` | 小写 `docx_image` | | `parent_node` = 文档 ID | 必须是 image block 的 block_id(否则 `1770013: relation mismatch`) | | 用 `update_image` 字段 | 用 `replace_image`(update_image 返回 invalid param) | | 用 IM image_key 作为 token | 必须用 Drive upload_all 返回的 file_token | ### 批量替换文档中的图片(实战模板) 场景:文档中每个标题下有原图,需要替换为新图。 ```python # 1. 读取文档结构,找到 heading → image block 的映射 blocks = GET(f"/docx/v1/documents/{DOC_ID}/blocks?page_size=500") root = next(b for b in blocks if b['block_type'] == 1) children = root['children'] block_map = {b['block_id']: b for b in blocks} # 2. 遍历 children,找到每个 heading 后面最近的 image block step_images = {} # step_num → image_block_id for i, cid in enumerate(children): b = block_map[cid] if b['block_type'] == 4: # heading2 for j in range(i+1, min(i+20, len(children))): nb = block_map[children[j]] if nb['block_type'] == 27: step_images[step_num] = nb['block_id'] break # 3. 对每个 image block: 上传新图 → replace_image for step_num, block_id in step_images.items(): file_token = upload_image(f"step_{step_num}.png", parent_node=block_id) PATCH(f"/docx/v1/documents/{DOC_ID}/blocks/{block_id}", json={"replace_image": {"token": file_token}}) time.sleep(0.35) # 限频 ~3 req/s ``` ## Drive 图片上传 — 正确参数 ```python POST /open-apis/drive/v1/medias/upload_all # multipart/form-data # 字段名: "file"(不是 "image") # parent_type: 小写 "docx_image"(不是 "DOCX_IMAGE"!) # parent_node: 取决于用途 # - 替换已有图片 block: 用 image block_id # - 其他用途: 用文档 document_id ``` parent_type 完整可选值(从 error.field_violations 获取): doc_image, docx_image, sheet_image, doc_file, docx_file, sheet_file, bitable_image, bitable_file, moments, calendar, whiteboard, mindnote_image, comment_image, slide_img, slide_file, email, vc_virtual_background, base_global, lark_ai_media_analysis, bitable_tmp_point, office_sheet_file, office_slide_file ## IM 图片上传 — 正确参数 ```python POST /open-apis/im/v1/images # multipart/form-data # 字段名: "image"(不是 "file"!) ← 和 Drive 相反! # image_type: message ``` 关键陷阱 — IM vs Drive 字段名相反: - Drive upload_all: file - IM images: image - 搞混返回 code:234001 IM image_key **不能**用于 docx image block 的 token。文档图片必须通过 Drive upload_all 上传。 ## 常见错误码 | code | 含义 | 解决 | |------|------|------| | 1770032 | forBidden | 文档分享设置中添加应用为协作者 | | 1770001 | invalid param | 检查 block_type 和字段名 | | 1770029 | block not support to create | 该 block_type 不支持 API 创建(image block) | | 1770013 | relation mismatch | replace_image 时 parent_node 不是 block_id | | 1061002 | params error (Drive) | parent_type 用小写 docx_image | | 234001 | Invalid request param (IM) | 字段名用 image 不是 file | | 99992402 | field validation failed | 检查字段值格式和大小写 | ## 限频 - 文档 API 限频约 3 req/s - 批量操作时 `time.sleep(0.35)` 避免限频