Notion API 進階實操:使用 Node.js / Python 自動化同步資料與 SaaS 整合
1. 為什麼掌握 Notion API 是技術人員的超級槓桿?
Notion 不僅是一款強大的筆記和知識庫軟體,更是現代輕量級業務系統的無程式碼資料庫。然而,當資料量龐大或需要與外部 CRM、財務系統、電商訂單或自研後台打通時,手動複製貼上不僅極其低效,更易造成資料不一致。
透過官方 Notion REST API,我們可以使用 Node.js、Python 或 Go 等任意程式語言,將 Notion 作為一個具備優雅前端 UI 的 Headless CMS 或低程式碼業務資料底座。
2. 授權認證與整合權限(Integration Setup)
在編寫程式碼前,必須在 Notion 開發者平台完成整合授權:
┌────────────────────────────────────────────────────────┐
│ 1. Notion Developers 開發者控制台 │
│ (https://www.notion.so/my-integrations) │
│ 建立新 Integration -> 取得 Internal Integration Secret │
└───────────────────────────┬────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ 2. 目標資料庫/頁面明確授權 (Crucial Step!) │
│ 開啟資料庫頁面 -> 右上角 "..." -> "Connections" │
│ -> 新增剛才建立的 Integration (否則回傳 404 錯誤!) │
└────────────────────────────────────────────────────────┘
常見報錯提示
初學者呼叫 API 出現最多的錯誤是 object_not_found (404)。這是因為即使你的 Secret 金鑰正確,若沒有在具體資料庫頁面透過 Connections 手動新增該整合,Notion 安全沙箱也會徹底拒絕對該資料庫的存取。
3. Node.js 生產實戰:查詢與寫入多維資料庫
官方為 JavaScript / TypeScript 開發者提供了成熟的 @notionhq/client SDK。
3.1 環境準備與安裝
npm install @notionhq/client dotenv
3.2 自動化腳本:查詢待處理任務並更新狀態
import { Client } from '@notionhq/client';
import dotenv from 'dotenv';
dotenv.config();
const notion = new Client({ auth: process.env.NOTION_API_KEY });
const DATABASE_ID = process.env.NOTION_DATABASE_ID;
async function syncPendingTasks() {
try {
// 1. 篩選查詢狀態為 "待處理" 且優先級為 "High" 的卡片
const response = await notion.databases.query({
database_id: DATABASE_ID,
filter: {
and: [
{
property: 'Status',
status: { equals: '待處理' }
},
{
property: 'Priority',
select: { equals: 'High' }
}
]
},
sorts: [
{
property: 'CreatedAt',
direction: 'ascending'
}
]
});
console.log(`成功撈取 ${response.results.length} 筆待辦任務`);
// 2. 逐筆處理並更新屬性
for (const page of response.results) {
await notion.pages.update({
page_id: page.id,
properties: {
Status: {
status: { name: '同步中' }
},
SyncedAt: {
date: { start: new Date().toISOString() }
}
}
});
}
} catch (error) {
console.error('Notion API 異常:', error);
}
}
syncPendingTasks();
4. Python 生產實戰:定時向 Notion 推送營運資料
Python 憑藉豐富的資料科學與網路爬蟲生態,非常適合做業務監控報表的自動化回填。
4.1 安裝第三方或使用官方 notion-client
pip install notion-client requests
4.2 Python 自動化腳本:新增客戶紀錄
import os
from datetime import datetime
from notion_client import Client
notion = Client(auth=os.environ.get("NOTION_API_KEY"))
database_id = os.environ.get("NOTION_DATABASE_ID")
def insert_new_lead(customer_name, email, deal_amount):
"""向 Notion 客戶名單庫新增一筆銷售紀錄"""
new_page = {
"parent": {"database_id": database_id},
"properties": {
"CustomerName": {
"title": [{"text": {"content": customer_name}}]
},
"Email": {
"email": email
},
"DealAmount": {
"number": deal_amount
},
"LeadDate": {
"date": {"start": datetime.now().strftime("%Y-%m-%d")}
},
"Status": {
"status": {"name": "新名單待認領"}
}
}
}
response = notion.pages.create(**new_page)
print(f"成功建立頁面 ID: {response['id']}")
return response['id']
if __name__ == "__main__":
insert_new_lead("某某科技股份有限公司", "contact@example.com", 88000)
5. API 效能調優、分頁與速率限制(Rate Limits)
當接入生產級資料管線時,必須考慮介面穩定性和強健性:
- 處理速率限制(Rate Limiting):
- Notion API 官方預設限制為 平均每秒 3 次請求(3 requests/sec);
- 突發請求可能回傳
HTTP 429 Too Many Requests; - 用戶端必須實作指數退避重試(Exponential Backoff)機制;
- 游標分頁(Cursor Pagination):
databases.query預設單頁最多回傳 100 筆紀錄;- 若資料庫紀錄數大於 100,檢查回應中的
has_more欄位,並將next_cursor作為下一次請求的start_cursor遞迴拉取;
- 富文字字元邊界保護:
- 單一 Rich Text 區塊的
content最大不能超過 2000 個字元;長篇文字入庫前必須在程式碼中按 2000 字元切片。
- 單一 Rich Text 區塊的
核心手冊與速查工具
高頻手冊與實用生產力工具直達常見問題與答疑 (FAQ)
高頻疑難解析與避坑指南完全不需要。绝大多数核心功能在免费 Starter 计划中均可完整体验与实操练习,无需额外付费购买付费团队版。
建议从理解弹性盒子模型(Flexbox)开始,熟练运用 Hug(适应内容)、Fill(填充容器)与 Fixed(固定尺寸),再结合绝对定位和负间距完成复杂响应式组件构建。
在 Notion 画布中按快捷键 Shift + I 打开 Resources 资源弹窗,切换到「Plugins」选项卡,即可直接搜索并一键运行海量社区优质插件。
Notion Variables 支持颜色、数值、字符串和布尔值等多种类型,可建立轻暗色模式切换、多平台间距规范等,配合 Dev Mode 可无缝导出为前端生产代码。