Notion API 页面创建失败的常见原因与正确写法详解

10次阅读

Notion API 页面创建失败的常见原因与正确写法详解

本文详解 notion api 创建页面时返回 400 错误的根本原因:属性值结构不匹配(如将 `title` 或 `rich_text` 字段误写为数组形式),并提供符合官方 schema 的完整代码示例与关键注意事项。

在使用 Notion API 创建数据库页面(notion.pages.create)时,一个高频却极易被忽略的错误是:属性(Property)值的嵌套结构不符合 Notion 的严格 Schema 要求。你遇到的 400 Bad Request 错误(如 body.properties.Link.id should be defined, instead was undefined)并非因权限、ID 或 Token 问题,而是因为 API 将你传入的 Link: { url: “…” } 等非文本类属性,错误识别为“未初始化的空对象”——其根本原因在于:所有非纯字符串类型的属性(包括 title、rich_text、url、checkbox、relation 等)都必须以明确的类型键(type key)作为外层包装,且该键不可省略或错位

例如,Name 字段在数据库中若定义为 Title 类型,则其值必须是 { title: […] };若定义为 Text(即 Rich Text)类型,则必须是 { rich_text: […] };而 Link 字段若为 URL 类型,则必须是 { url: “https://…” } ——注意:url 是顶层键,不是 rich_text 的子字段,也不接受数组形式。

以下是修正后的标准写法(关键变更已加注释):

const { Client } = require("@notionhq/client");  const notion = new Client({   auth: process.env.NOTION_TOKEN, });  async function main() {   try {     await notion.pages.create({       parent: {         type: "database_id",         database_id: process.env.DB_ID, // ✅ 确保 DB_ID 是有效 UUID 格式(含连字符)       },       properties: {         // ✅ Title 类型:必须用 { title: [...] }         Name: {           title: [             {               text: { content: "Test name" },             },           ],         },          // ✅ URL 类型:必须用 { url: "https://..." },且协议不可省略         Link: {           url: "https://www.google.com", // ⚠️ 原代码缺少 "https://",Notion 会拒绝无效 URL         },          // ✅ Rich Text 类型:必须用 { rich_text: [...] }         Notes: {           rich_text: [             {               text: { content: "sample notes" },             },           ],         },          // ✅ 同样适用于其他 Rich Text 字段(如 Year)         Year: {           rich_text: [             {               text: { content: "2020" },             },           ],         },       },     });     console.log("✅ Page created successfully!");   } catch (Error) {     console.error("❌ Failed to create page:", error.body?.message || error.message);   } }  main();

⚠️ 关键注意事项

  • URL 必须带协议:url 字段值必须为完整 URL(如 “https://google.com”),”www.google.com” 或 “google.com” 会被视为非法,导致 400;
  • 类型键不可省略:Name: […](数组)或 Name: { text: … } 均非法;必须显式声明 title / rich_text / url / checkbox 等类型键;
  • 数据库字段名需完全一致:properties 中的键名(如 “Name”、”Link”)必须与 Notion 数据库中对应列的精确显示名称(区分大小写、空格)完全匹配;
  • Relation / Checkbox 等复杂类型需额外结构:例如 Relation 需传 { relation: [{ id: “xxx-xxx-xxx” }] },Checkbox 需 { checkbox: true },不可直接传布尔值或 ID 数组;
  • 调试建议:启用 console.error(error.body) 可获取 Notion 返回的详细校验错误(如字段类型不匹配提示),比仅看 error.message 更精准。

遵循上述结构规范后,你的页面创建请求将严格符合 Notion API 的 OpenAPI Schema,彻底规避误导性的 undefined 字段报错。记住:Notion API 不接受“约定优于配置”,一切以 Property Value Objects 文档 中定义的 jsON 结构为准。

text=ZqhQzanResources