Notion 数据 API调用手册

定位数据源并查询数据库条目

先从数据库获取 data_sources,再用数据源 ID 查询行,避免把 database_id 与 data_source_id 混用。

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

接入准备

  • Read content capability;连接已经添加到原始数据库。
  • 本手册固定 2026-03-11 版本,采用 database 容器 + data_source 行与 schema 的模型。

准备环境变量

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

NOTION_TOKEN
内部 connection 的 API Secret;在页面连接菜单授予访问,不是登录 Cookie。
NOTION_DATABASE_ID
原始 database 容器 ID,不是视图 ID。
NOTION_DATA_SOURCE_ID
第一步 data_sources 数组中选中的数据源 ID。
终端
export NOTION_TOKEN='replace_with_internal_connection_token'
export NOTION_DATABASE_ID='55555555-5555-4555-8555-555555555555'
export NOTION_DATA_SOURCE_ID='66666666-6666-4666-8666-666666666666'

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

调用步骤

  1. 01

    从数据库原始页面地址取得数据库 ID,保存为 NOTION_DATABASE_ID。

  2. 02

    执行检索数据库,选取响应 data_sources 中目标数据源的 id,保存到 NOTION_DATA_SOURCE_ID。

  3. 03

    查询首批条目;下一页把 next_cursor 放入请求体 start_cursor,保留相同筛选排序。

  4. 04

    检查每页 request_status;即使 has_more=false,也可能因单次查询 10000 条上限而不完整。

调用 01

读取数据库容器

当前版本响应 data_sources 列表;一个数据库可能包含多个数据源。

GEThttps://api.notion.com/v1/databases/${NOTION_DATABASE_ID}

请求头

Authorization
Bearer ${NOTION_TOKEN}
Notion-Version
2026-03-11
Content-Type
application/json

参数说明

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

字段 / 位置类型 / 必填说明
database_idPathUUID必填原始数据库 ID;linked database 视图不是另一个可独立查询的源。

调用代码

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

cURL
# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request GET \
  --url "https://api.notion.com/v1/databases/${NOTION_DATABASE_ID}" \
  --header "Authorization: Bearer ${NOTION_TOKEN}" \
  --header "Notion-Version: 2026-03-11" \
  --header "Content-Type: application/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://api.notion.com/v1/databases/${NOTION_DATABASE_ID}")
headers = {
    "Authorization": expand("Bearer ${NOTION_TOKEN}"),
    "Notion-Version": expand("2026-03-11"),
    "Content-Type": expand("application/json"),
}
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://api.notion.com/v1/databases/${NOTION_DATABASE_ID}");
const headers = Object.fromEntries(
  Object.entries({
  "Authorization": "Bearer ${NOTION_TOKEN}",
  "Notion-Version": "2026-03-11",
  "Content-Type": "application/json"
}).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,不是实测结果。取 data_sources[].id 作为下一步路径参数。 以下为结构示意,非本站实测结果。

JSON
{
  "object": "database",
  "id": "55555555-5555-4555-8555-555555555555",
  "data_sources": [
    {
      "id": "66666666-6666-4666-8666-666666666666",
      "name": "测试事项"
    }
  ]
}

常见错误与排查

401 unauthorized令牌无效
核对完整 Bearer Token 与 connection 状态。
403 restricted_resource连接权限不足
开通所需 Read/Insert content capability,并核对资源授权。
404 object_not_found资源不存在或连接无权访问
确认 ID 并在原始页面/数据库的 Connections 菜单添加连接。
429 rate_limited请求频率超过限制
按 Retry-After 响应头等待后重试。

调用注意

  • 不要从旧 2022-06-28 文档推断此处直接返回全部列和行。
调用 02

查询数据源条目

本例无字段假设,按创建时间倒序取 20 条。

POSThttps://api.notion.com/v1/data_sources/${NOTION_DATA_SOURCE_ID}/query

请求头

Authorization
Bearer ${NOTION_TOKEN}
Notion-Version
2026-03-11
Content-Type
application/json

参数说明

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

字段 / 位置类型 / 必填说明
data_source_idPathUUID必填目标数据源 ID,与 database_id 不同。
page_size请求体integer可选最大 100;服务端可能返回不足 page_size 条,不据此判断结束。
start_cursor请求体string可选首次省略;下一页填上次 next_cursor。
sorts请求体object[]可选按属性或 created_time/last_edited_time 排序;本例使用系统创建时间。
filter请求体object可选按数据源字段类型构造筛选;名称与类型需先核对 schema。

调用代码

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

cURL
cat > request-body.json <<'JSON'
{
  "page_size": 20,
  "sorts": [
    {
      "timestamp": "created_time",
      "direction": "descending"
    }
  ]
}
JSON

# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request POST \
  --url "https://api.notion.com/v1/data_sources/${NOTION_DATA_SOURCE_ID}/query" \
  --header "Authorization: Bearer ${NOTION_TOKEN}" \
  --header "Notion-Version: 2026-03-11" \
  --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://api.notion.com/v1/data_sources/${NOTION_DATA_SOURCE_ID}/query")
headers = {
    "Authorization": expand("Bearer ${NOTION_TOKEN}"),
    "Notion-Version": expand("2026-03-11"),
    "Content-Type": expand("application/json"),
}
body = {
    "page_size": 20,
    "sorts": [
        {
            "timestamp": "created_time",
            "direction": "descending",
        },
    ],
}
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://api.notion.com/v1/data_sources/${NOTION_DATA_SOURCE_ID}/query");
const headers = Object.fromEntries(
  Object.entries({
  "Authorization": "Bearer ${NOTION_TOKEN}",
  "Notion-Version": "2026-03-11",
  "Content-Type": "application/json"
}).map(([key, value]) => [key, expand(value)])
);
const body = {
  "page_size": 20,
  "sorts": [
    {
      "timestamp": "created_time",
      "direction": "descending"
    }
  ]
};
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,不是实测结果。读取 results、next_cursor、has_more,并检查 request_status。 以下为结构示意,非本站实测结果。

JSON
{
  "object": "list",
  "type": "page_or_data_source",
  "page_or_data_source": {},
  "results": [
    {
      "object": "page",
      "id": "77777777-7777-4777-8777-777777777777",
      "properties": {}
    }
  ],
  "next_cursor": null,
  "has_more": false,
  "request_status": {
    "type": "complete"
  }
}

常见错误与排查

401 unauthorized令牌无效
核对完整 Bearer Token 与 connection 状态。
403 restricted_resource连接权限不足
开通所需 Read/Insert content capability,并核对资源授权。
404 object_not_found资源不存在或连接无权访问
确认 ID 并在原始页面/数据库的 Connections 菜单添加连接。
429 rate_limited请求频率超过限制
按 Retry-After 响应头等待后重试。

调用注意

  • 每个查询最多分页 10000 条;若 request_status.type=incomplete 且 incomplete_reason=query_result_limit_reached,需按时间窗口拆查询,不把 false 当全量完成。
  • 查询返回属性,不返回完整正文;要正文再按页面 ID 读取 block children。

注意事项

  • 数据库关系引用的资源也需授权;第三方共享链接不能代替 connection 资源权限。

核验来源

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

  1. 01
    Create your first connection核验日期 2026-10-15
  2. 02
    API versioning核验日期 2026-10-15
  3. 03
  4. 04
    Query a data source核验日期 2026-10-15

Notion 数据 API的其他调用手册

← 返回Notion 数据 API的全部功能