Notion Page Property Item API 與 Request Limits 載荷限制實戰:突破 25 條 Relation 截斷、超長文字分頁拉取、409 併發衝突重試與 TypeScript SDK 工程治理

2026 年 11 月 21 日

一、為什麼 GET /v1/pages/{id} 會靜默丟失資料?看懂 25 條截斷與載荷紅線

在構建財務對賬系統、研發專案同步中樞或企業級 BI 資料管道時,許多開發團隊都踩過同一個極其隱蔽的坑:一個父專案在 Notion 頁面裡明明關聯了 68 個子任務,或者某個備註欄位寫了 4,000 多字的富文字,但後端指令碼呼叫 GET /v1/pages/{page_id} 後,拿到的 relation 陣列長度卻永遠停在 25 條,下游統計出來的工時與金額全部少算一半——而且介面返回狀態碼是正常的 HTTP 200 OK,沒有任何報錯提示!

這一現象源於 Notion 官方為保障單頁響應延遲而設定的 屬性載荷截斷與 Request Limits(請求大小限制) 機制(關聯表設計基礎可參閱 Notion Relation 與 Rollup 工程治理實戰 與 Pages API 寫庫工程指南)。在生產環境下,忽略介面硬性邊界往往會觸發以下四類嚴重故障:

  1. 未檢查 has_more: true 導致關聯與彙總資料靜默截斷:GET /v1/pages/{page_id} 與 POST /v1/data_sources/{id}/query(及舊版 /databases/{id}/query)對每行記錄內的 relation、rollup、people、rich_text 和 title 屬性最多隻內聯返回前 25 個元素;超過 25 條時僅置位 "has_more": true,必須改調 Page Property Item API 分頁補全。
  2. 寫入單段富文字超過 2,000 字元觸發 400 validation_error:無論是寫入頁面 rich_text 屬性還是更新正文段落,單個 text.content 或數學公式 equation.expression 均不得超過 2,000 個字元;同時單次請求中 rich_text、multi_select、relation 陣列元素總數不能超過 100 個。
  3. 單次建頁或追加塊突破 100 塊 / 500 KB 載荷紅線:通過 POST /v1/pages 或 PATCH /v1/blocks/{id}/children 寫入結構化內容時,單層 children 陣列上限為 100 個 Block、單次巢狀最多 2 層、整包總塊數上限 1,000 個且 HTTP 請求體嚴禁超過 500 KB(正文遞迴寫入參閱 Blocks API 遞迴樹讀寫實戰)。
  4. 多協程併發更新同一頁面觸發 HTTP 409 conflict_error 直接崩潰:許多指令碼只對 HTTP 429(每秒 3 次平均速率限制)做重試,卻把併發寫同一頁面或同一區塊時返回的 409 conflict_error 當作不可還原錯誤直接拋棄,導致批次同步流水線大面積丟單。
介面與傳輸限制維度 Notion API 官方硬性上限 超限後的介面表現 / 返回狀態 生產級工程應對策略
GET /pages/{id} 關聯/富文字內聯上限 單屬性最多內聯 25 條元素 HTTP 200,屬性物件標記 has_more: true(靜默截斷) 檢測 has_more 後立即呼叫 GET /pages/{id}/properties/{prop_id} 游標翻頁
text.content / equation.expression 長度 單個文字/公式物件 ≤ 2,000 字元 HTTP 400 (validation_error) 拒絕寫入 按 1,900 字元安全閾值切分為多個 rich_text 片段物件陣列
url / email / phone_number 欄位長度 URL ≤ 2,000 字元;Email/Phone ≤ 200 字元 HTTP 400 (validation_error) 入庫前做正則校驗、短鏈壓縮或截斷清洗並記錄告警
單次屬性陣列元素數量 relation / multi_select / rich_text ≤ 100 項 HTTP 400 (validation_error) 關聯超過 100 項需分批 PATCH 追加或拆分為反向歸屬寫入
單次 Block 追加與請求體大小 單次 ≤ 100 children(≤ 2 層巢狀)、整包 ≤ 500 KB / 1,000 塊 HTTP 400 或 HTTP 413 載荷過大報錯 大文件改走 Markdown Content API 或按 80 塊分片提交
平均吞吐速率與併發鎖衝突 平均 3 req/s;同頁併發寫入觸發樂觀鎖 HTTP 429 (rate_limited) / HTTP 409 (conflict_error) 429 嚴格遵循 Retry-After;409 採用隨機抖動指數退避重放

Notion Page Property Item API 與 Request Li示意圖

二、Page Property Item API 分頁拉取與四步防截斷落地流程

結合 建立 Notion API 整合指南、Data Sources Query 複合查詢實戰 與 API 速率限制與容錯架構,研發團隊應在服務端統一封裝一套“按需下鑽 + 載荷分片 + 雙重退避”的資料訪問層,按以下四步落實:

步驟 1:識別 property_id 與需要分頁的 list 響應結構

  1. 從資料來源 Schema(GET /v1/data_sources/{data_source_id})或頁面返回體中讀取目標屬性的 id(URL 編碼安全,推薦優先使用固定 property_id 而非易變的中文屬性名,避免業務同學改列名後介面失效,Schema 管理參閱 Databases 與 Data Sources Schema API 實戰)。
  2. 當 GET /v1/pages/{page_id} 返回的屬性物件出現 "has_more": true,或屬性型別為複雜 rollup 時,呼叫 GET /v1/pages/{page_id}/properties/{property_id}(查詢引數可傳 page_size=100 與 start_cursor)。
  3. 注意區分該介面的兩種返回結構:簡單標量屬性(如 number、select、date、checkbox)直接返回 object: "property_item";而 relation、rich_text、title、people 與 array 型 rollup 會返回 object: "list" 分頁信封,通過 results 陣列承載單條 property_item,並依據 has_more 與 next_cursor 迴圈拉取直至 has_more === false。

步驟 2:在寫入前置層強制執行 1,900 字元與 80 元素安全分片

  1. 任何來自 LLM 摘要、客服工單正文或第三方 ERP 的長字串在拼裝 rich_text 前,必須通過分段函式按 1,900 字元(為多位元組 Emoji 與換行轉義預留安全餘量)切分為多個 {"type": "text", "text": {"content": "..."}} 元素;若切分後陣列超過 100 項,應自動降級寫入頁面正文 Block 或啟用 Markdown Content API,切勿硬塞進資料庫屬性列。
  2. 每次追加資料庫頁面關聯(relation)或標籤(multi_select)時,在 SDK 封裝層計算現有清單與增量清單的並集長度,若單次寫入接近 100 項限制則拆分為多輪冪等更新。

步驟 3:統一配置 HTTP 429 + HTTP 409 雙異常重試排程器

  1. 針對 HTTP 429(速率限制):優先解析響應頭 Retry-After(單位秒)併疊加 200~500ms 隨機抖動(Jitter),同時結合全域性令牌桶將單 Integration 併發度控制在 2~3 req/s。
  2. 針對 HTTP 409(conflict_error 樂觀鎖衝突):在多 Webhook 消費者同時更新同一張彙總專案頁時極為常見(事件訂閱架構參閱 Integration Webhooks 實戰)。捕獲 conflict_error 後按 300ms -> 700ms -> 1500ms 指數退避重放,並配合頁面級互斥佇列消除無謂碰撞。

步驟 4:對齊 Notion-Version: 2026-03-11 與 @notionhq/client 型別安全契約

  1. 升級官方 TypeScript SDK @notionhq/client 時,在使用者端初始化顯式鎖定 notionVersion: "2026-03-11"(相容 2025-09-03 多源資料庫模型),並使用 in_trash 替代已廢棄的 archived 欄位、使用 position 物件替代塊追加的扁平 after 字串。
  2. 對 pages.properties.retrieve() 返回聯合型別進行顯式型別收窄(Type Guard),區分 object === "list" 與單值 property_item,徹底杜絕執行時 undefined 崩潰。

三、TypeScript(@notionhq/client)生產級工程實現

以下 TypeScript 模組完整演示了基於官方 SDK 的 429/409 雙重試攔截器、Page Property Item 全量關聯與文字分頁提取器 以及 2,000 字元安全拆片工具:

import { Client, isNotionClientError, APIErrorCode } from "@notionhq/client";
import type {
  GetPagePropertyResponse,
  PropertyItemObjectResponse,
} from "@notionhq/client/build/src/api-endpoints";

export const notion = new Client({
  auth: process.env.NOTION_TOKEN,
  notionVersion: "2026-03-11",
});

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/** 统一重试封装:同时处理 429 速率限制与 409 并发冲突 */
export async function withNotionRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 5
): Promise<T> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err: unknown) {
      if (!isNotionClientError(err)) throw err;

      const isRateLimit = err.code === APIErrorCode.RateLimited;
      const isConflict = err.code === APIErrorCode.ConflictError;
      const isTransient5xx =
        err.code === APIErrorCode.InternalServerError ||
        err.code === APIErrorCode.ServiceUnavailable;

      if ((isRateLimit || isConflict || isTransient5xx) && attempt < maxRetries - 1) {
        const retryAfterHeader =
          "headers" in err && err.headers && typeof err.headers === "object"
            ? Number((err.headers as Record<string, string>)["retry-after"])
            : NaN;
        const baseWaitMs = Number.isFinite(retryAfterHeader)
          ? retryAfterHeader * 1000
          : Math.min(8000, 400 * 2 ** attempt);
        const jitterMs = Math.floor(Math.random() * 350);
        await sleep(baseWaitMs + jitterMs);
        continue;
      }
      throw err;
    }
  }
  throw new Error("Notion API retry attempts exhausted");
}

/** 分页拉取完整页面属性条目,彻底突破 GET /pages/{id} 的 25 条截断 */
export async function fetchAllPropertyItems(
  pageId: string,
  propertyId: string
): Promise<PropertyItemObjectResponse[]> {
  const items: PropertyItemObjectResponse[] = [];
  let cursor: string | undefined;

  while (true) {
    const res: GetPagePropertyResponse = await withNotionRetry(() =>
      notion.pages.properties.retrieve({
        page_id: pageId,
        property_id: propertyId,
        page_size: 100,
        start_cursor: cursor,
      })
    );

    if (res.object === "list") {
      items.push(...res.results);
      if (!res.has_more || !res.next_cursor) break;
      cursor = res.next_cursor;
    } else {
      items.push(res);
      break;
    }
  }

  return items;
}

/** 专门提取超过 25 个关联页面的全部 Target Page ID */
export async function fetchAllRelationIds(
  pageId: string,
  relationPropertyId: string
): Promise<string[]> {
  const items = await fetchAllPropertyItems(pageId, relationPropertyId);
  return items
    .filter((item): item is Extract<PropertyItemObjectResponse, { type: "relation" }> =>
      item.type === "relation"
    )
    .map((item) => item.relation.id);
}

/** 安全切分超长文本为符合 2000 字符与 100 元素上限的 rich_text 数组 */
export function buildSafeRichText(rawText: string, chunkSize = 1900) {
  const chunks: Array<{ type: "text"; text: { content: string } }> = [];
  for (let i = 0; i < rawText.length; i += chunkSize) {
    if (chunks.length >= 100) {
      throw new Error("文本总长度超出单个属性 100 个 rich_text 片段上限,请改用正文 Block 写入");
    }
    chunks.push({
      type: "text",
      text: { content: rawText.slice(i, i + chunkSize) },
    });
  }
  return chunks.length > 0 ? chunks : [{ type: "text" as const, text: { content: "" } }];
}

四、Formula 2.0 實戰:API 載荷超限與 25 條截斷風險巡檢門禁

在企業內部執行多個同步指令碼時,建議建立《Notion API 整合載荷健康臺賬》,記錄每條資料管道對應的 最大单行关联数(Number)、单属性最大字符数(Number)、单次请求块数(Number)、已启用属性分页接口(Checkbox)、已接入 409/429 重试(Checkbox)與 近7日报错次数(Number),並配置如下 载荷与截断健康门禁 Formula 2.0 屬性(語法細節參閱 Formula 2.0 速查手冊 與 資料庫架構規範):

lets(
  maxRelations, prop("最大单行关联数"),
  maxChars, prop("单属性最大字符数"),
  maxBlocks, prop("单次请求块数"),
  propPaginated, prop("已启用属性分页接口"),
  retryReady, prop("已接入 409/429 重试"),
  errCount, prop("近7日报错次数"),

  ifs(
    maxRelations > 25 && !propPaginated,
      style("🚨 静默截断高危:关联数已达 " + format(maxRelations) + " 条但未接入 Property Item 分页", "red", "bold", "red_background"),
    maxChars > 2000 || maxBlocks > 100,
      style("⛔ 载荷越界阻断:单文本超 2000 字或单次 Blocks 超 100 块,必发 400 报错", "red", "bold", "red_background"),
    !retryReady,
      style("⚠️ 缺少 409/429 退避重试:高并发写库存在丢单风险", "orange", "bold", "yellow_background"),
    errCount > 0,
      style("🟡 近 7 日存在 " + format(errCount) + " 次接口异常,请复核 Payload 与限流日志", "orange"),
    style("🟢 载荷分片、25+ 属性分页与并发重试全合规", "green")
  )
)

五、生產上線前核對清單與常見排障指引

在將任意 Notion API 整合推向生產環境前,建議逐項核驗以下三點(如遇 400 validation_error、409 conflict_error 或響應不完整,可直接查閱 Notion 常見報錯與故障診斷手冊):

  1. 禁止在 Data Sources Query 後再盲目遍歷全部單頁:僅當某行記錄的關鍵 relation、rollup 或 rich_text 欄位明確帶有 has_more: true 時,才觸發 GET /v1/pages/{id}/properties/{prop_id} 精準補抓,避免消耗無謂的每秒 3 次限流配額。
  2. 用 filter_properties 配合 Property Item 介面實現極限瘦身:清單查詢階段通過 filter_properties 只拉取主鍵、狀態與關鍵標誌位,將大文字與多關聯剝離到按需翻頁載入,能將同步吞吐率提升 3~5 倍。
  3. 寫庫載荷嚴禁原樣回傳唯讀屬性:跨庫同步或複製記錄時,務必在構造請求體前剝離 formula、rollup、created_time、last_edited_time、unique_id 與 button 等唯讀屬性,確保介面冪等穩定執行。

❓ 常見問題與答疑 (FAQ)

高頻疑難解析與避坑指南
A

完全不需要。绝大多数核心功能在免费 Starter 计划中均可完整体验与实操练习,无需额外付费购买付费团队版。