Notion API客户端必须配置有效Integration令牌并传入context,否则返回401或context deadline exceeded;令牌需从notion.so/my-integrations创建并共享至目标空间,且所有方法首参必须为非nil context。

notionapi 客户端能直接用,但不配好集成令牌和上下文就必然 401 Unauthorized 或 context deadline exceeded —— 这不是代码写得不对,是初始化漏了关键约束。
初始化 client 时必须传入有效 integration token
Notion API 不接受个人 token,只认「Integration」类型令牌。你得在 https://www.notion.so/my-integrations 创建一个 integration,把它 share 到目标 workspace 和 page/database,再复制 Token(以 secret_ 开头)。
常见错误:
- 误用 Notion 账户的 session token(浏览器 Cookie 里的
token_v2),它不能用于 API - token 复制完整(共 60+ 字符),中间没空格或换行
- 忘记在 integration 页面把目标 database 或 page 手动 share 给该 integration
初始化示例:
client := notionapi.NewClient("secret_xxx...")
Page.Get 和 Database.Query 必须带 context.Context
所有方法第一个参数都是 context.Context,不能传 nil,否则 panic。多数场景用 context.Background() 即可,但生产环境建议加 timeout:
立即学习“go语言免费学习笔记(深入)”;
使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等
-
context.WithTimeout(context.Background(), 5*time.Second)防止网络卡住整个 goroutine - 调用
Database.Query时若不设page_size,默认只返回 100 条,大库容易漏数据 -
Page.Get返回的Page结构体里,Properties是 map[string]notionapi.PropertyValue,需按 type 字段二次解析(比如title、select、date的结构完全不同)
写操作(CreatePage / UpdatePage)要严格匹配 schema
Notion 对 block 和 property 的字段校验极严。例如:
- 往 database 里
CreatePage时,Properties字段名必须和 database 的 property 名**完全一致**(区分大小写、空格、emoji) -
Title类型 property 要传notionapi.TitleProperty{Title: []notionapi.RichText{{Text: notionapi.Text{Content: "xxx"}}}},少一层嵌套就400 Bad Request - 更新已有 page 时,
UpdatePage不支持 patch,必须传全量Properties,否则未传字段会被清空
错误处理别只看 err != nil
notionapi 的 error 多数是 HTTP 错误包装,需用类型断言提取真实状态码:
if err != nil {
var e *notionapi.ErrorResponse
if errors.As(err, &e) {
fmt.Printf("Notion API error: %d %s", e.Code, e.Message)
// e.Code 可能是 "validation_error"、"object_not_found"、"rate_limited" 等
}
}
特别注意:rate_limited 错误不会自动重试,得自己加 retry 逻辑;object_not_found 常因 page_id 写错或权限没开全导致,不是接口问题。
最常被跳过的点:database query 返回的 Results 是 slice,但 NextCursor 非空时说明还有数据,不手动分页就拿不全——这个字段不在 error 里,也不报错,只是静默截断。

















