# Notion
<!--
ref: @integrations/notion
tags: [Notion, API, curl, automation]
triggers: [create pages, query databases, inspect DB schema, append blocks]
trigger_prompt: When you need to manage Notion pages or databases programmatically, whether for creating, querying, or updating content.
category: integration
last_reviewed: 2026-05-18
complements: [@integrations/curly, @integrations/gh, @integrations/apify, @protocol/agent-config-integration, @protocol/api-reference]
audience: [claude-code-user, agent-author, terminal-only]
version: 24
updated_at: 2026-11-22T15:42:12.683Z
-->
Use `curly notion` to interact with the Notion API efficiently without repetitive setup.
> **Use `curly notion`. Don't roll your own `curl https://api.notion.com/...`.**
> Raw curl forces you to re-set `Authorization`, `Notion-Version`, and `Content-Type` on every call — get any of them wrong (especially `Notion-Version`) and the same endpoint silently behaves differently from the rest of your tooling. `curly notion` is the single point where those are set; everything in this doc assumes it.
> **Prefer this over MCP.** The direct REST API doesn't require interactive `/mcp` auth per session, works in scripts, and gives you full control over requests.
## When to Use
- **Create pages** in a database with properties + block content
- **Query databases** by property filters + sorts (use `data_source_id`)
- **Inspect DB schema** (property names, types, multi-select options)
- **Append blocks** to an existing page
- **Search** pages by title across a workspace
## Setup
```bash
curly init notion # hidden prompt for the token → ~/.curly.yaml
```
`notion` is a built-in service — host, bearer auth, and the `Notion-Version` header ship with curly, so the token (`ntn_…`, from https://www.notion.so/profile/integrations) is all you supply. Setup flow and troubleshooting: [`@integrations/curly`](/@integrations/curly).
**Version pin.** `curly init notion` seeds `Notion-Version: 2026-03-11` (current stable; verified 2026-05-18). The modern version is **required** for `/data_sources/*` — older pins (`2022-06-28`) return **404 `invalid_request_url`** there, because the endpoint does not exist on that API version.
If `curly notion /data_sources/…` 404s, your pin is stale. It's data in `~/.curly.yaml`, not code — so re-run `init` to fix it (the token is left alone):
```bash
yq '.services.notion.headers."Notion-Version"' ~/.curly.yaml # what am I sending?
curly init notion Notion-Version=2026-03-11 # fix it
```
Note that `curly init` seeds the header **only when it creates the service**. Upgrading the curly script does *not* re-pin an entry you already have — that's the drift this protocol's version pin keeps biting on. To try a value without persisting it, pass `-H "Notion-Version: …"` per call (curl takes the last value of a repeated header). Keeping these pins fresh across services is [`@protocol/curly-versions-audit`](/@protocol/curly-versions-audit).
Verify the setup — both should succeed:
```bash
curly notion /users/me # auth + base headers
curly notion /data_sources/{id}/query -X POST -d '{"page_size":1}' # modern version path
```
### One-time: connect the integration to your pages
The token authenticates as a Notion **internal integration**, not a user. It has access **only** to pages and databases that have been explicitly connected to the integration in the Notion UI. Symptom of skipping this step: `users/me` succeeds, but every page or database call returns `object_not_found` (HTTP 404). Notion deliberately masks 403 as 404 for privacy.
Once per page or DB tree, in the Notion UI:
1. Open the page or DB.
2. `⋯` menu → **Connections** → **Connect to** → pick your integration.
Connections cascade to children, so connecting at a section root grants access to everything under it. Re-doing it after the integration token is rotated is *not* needed — the connection is keyed to the integration, not the token.
## Critical Gotchas (read first)
### ⚠️ `database_id` vs `data_source_id`
Not the same thing in the modern API. Get them wrong and endpoints 400.
| Endpoint | Takes | Why |
|---|---|---|
| `POST /pages` with `parent.database_id` | `database_id` | Still accepts DB IDs |
| `GET /databases/{id}` | `database_id` | Metadata + data_sources array |
| `GET /data_sources/{id}` | `data_source_id` | **This is where property schema lives** |
| `POST /data_sources/{id}/query` | `data_source_id` | Modern query endpoint |
| `POST /databases/{id}/query` | *(deprecated)* | 400 on `2025-09-03` and later versions |
Get the `data_source_id` from the database:
```bash
curly notion /databases/{db_id} | jq '.data_sources[0].id'
```
### ⚠️ Never PATCH `/databases/{id}` to modify select options
PATCHing a database to add/rename/remove select or multi_select options has caused **500+ row data loss** in practice. To add a new multi_select option, PATCH a single page with the new value — Notion auto-creates it:
```bash
# Correct way to add a multi_select option
curly notion /pages/{page_id} -X PATCH -d '{
"properties": {"Tags": {"multi_select": [{"name": "NewOption"}]}}
}'
```
### ⚠️ Paginated scraping — don't pipe `jq -c` into `while read`
Rich text with control characters (BLUF fields, descriptions with newlines/quotes) breaks shell parsing. Save each page to a numbered file, then jq-process all at once:
```bash
cursor=""
i=0
while :; do
body=$(curly notion /data_sources/{id}/query -X POST \
-d "{\"start_cursor\":\"${cursor:-null}\",\"page_size\":100}")
echo "$body" > "/tmp/scrape_$i.json"
has_more=$(jq -r '.has_more' <<< "$body")
cursor=$(jq -r '.next_cursor // empty' <<< "$body")
[ "$has_more" = "false" ] && break
i=$((i+1))
sleep 0.4 # see rate-limit gotcha below
done
# Then: jq -s '[.[] | .results[]]' /tmp/scrape_*.json
```
### ⚠️ Rate limit: ~3 requests/second
Notion enforces an average of **3 req/s** with brief bursts allowed. Exceeding it returns a JSON body shaped like `{"object":"error","status":429,"code":"rate_limited","message":"..."}` — *and* HTTP 429 with a `Retry-After` header (seconds). The pagination loop above will hit it on any non-trivial workspace; sleep ≥ 0.4s between calls or check `.code` and back off:
```bash
body=$(curly notion /data_sources/{id}/query -X POST -d '{"page_size":100}')
if [ "$(jq -r '.code // empty' <<< "$body")" = "rate_limited" ]; then
sleep 5
# retry the same call
fi
```
For larger backfills, the safe rule is `sleep 1` between page-fetches — slower but never trips.
## Common Errors
Notion error responses are JSON with a stable shape: `{"object":"error","status":<int>,"code":"<code>","message":"..."}`. **Always branch on `.code`, not HTTP status** — Notion intentionally folds 403 into 404 for privacy.
| HTTP | `.code` | Usually means |
|---|---|---|
| 400 | `validation_error` | Bad property type, missing required field, malformed `rich_text` |
| 401 | `unauthorized` | Token missing or invalid |
| 403 | `restricted_resource` | Integration lacks access — most often: not Connected to the page/DB |
| 404 | `object_not_found` | Either gone, or (more often) integration not Connected — see Setup |
| 404 | `invalid_request_url` | Path doesn't exist on the current `Notion-Version` |
| 409 | `conflict_error` | Concurrent edit; retry |
| 429 | `rate_limited` | See rate-limit gotcha |
## Cheat Sheet
### Pages
| Op | Call |
|----|------|
| Create in DB | `curly notion /pages -X POST -d '{"parent":{"database_id":"..."},"properties":{...},"children":[...]}'` |
| Get | `curly notion /pages/{page_id}` |
| Update props | `curly notion /pages/{page_id} -X PATCH -d '{"properties":{...}}'` |
| Archive | `curly notion /pages/{page_id} -X PATCH -d '{"archived":true}'` |
### Databases / data sources
| Op | Call |
|----|------|
| Get DB metadata | `curly notion /databases/{db_id}` |
| Get DB schema | `curly notion /data_sources/{data_source_id}` (returns `.properties`) |
| Query DB | `curly notion /data_sources/{data_source_id}/query -X POST -d '{"filter":{...},"sorts":[...]}'` |
### Blocks
| Op | Call |
|----|------|
| Get children | `curly notion /blocks/{block_id}/children` |
| Append | `curly notion /blocks/{parent_id}/children -X PATCH -d '{"children":[...]}'` |
| Update | `curly notion /blocks/{block_id} -X PATCH -d '{"type":"paragraph","paragraph":{...}}'` |
| Delete | `curly notion /blocks/{block_id} -X DELETE` |
### Search
| Op | Call |
|----|------|
| Search by title | `curly notion /search -X POST -d '{"query":"..."}'` |
## Patterns
> **Anything beyond a handful of single-row calls — drop to TS + bun.** See *Recipes (TS + bun)* below. Shell + jq is good for exploration; once you're touching >5 rows or composing logic (dedup, retry, project-to-JSONL), the ephemeral-script house style wins on both clarity and tokens.
### Anything non-trivial: use `-d @file.json`, not inline `-d '...'`
Inline `-d '{...}'` is fine for one-liners but breaks the moment your content has embedded quotes, newlines, or shell-special characters (which is most real Notion content). Write the body to a file, pass `-d @file.json`:
```bash
cat > /tmp/page.json <<'JSON'
{
"parent": {"database_id": "YOUR_DB_ID"},
"properties": {
"Name": {"title": [{"text": {"content": "Title with \"quotes\" and 'apostrophes'"}}]}
},
"children": [
{"object":"block","type":"paragraph","paragraph":{
"rich_text":[{"text":{"content":"Line one.\nLine two — em-dash, $vars, and \"quotes\" all safe."}}]
}}
]
}
JSON
curly notion /pages -X POST -d @/tmp/page.json
```
The single-quoted `'JSON'` heredoc delimiter disables shell interpolation, so `$`, backticks, and backslashes pass through verbatim. The inline examples below are kept for legibility — translate them to `-d @file.json` the moment your real content is non-trivial.
### Create a page in a DB with tags and body content
```bash
curly notion /pages -X POST -d '{
"parent": {"database_id": "YOUR_DB_ID"},
"properties": {
"Name": {"title": [{"text": {"content": "Page title"}}]},
"Tags": {"multi_select": [{"name": "Idea"}, {"name": "BizDev"}]}
},
"children": [
{"object":"block","type":"heading_2","heading_2":{"rich_text":[{"text":{"content":"Thesis"}}]}},
{"object":"block","type":"paragraph","paragraph":{"rich_text":[{"text":{"content":"Body..."}}]}},
{"object":"block","type":"bulleted_list_item","bulleted_list_item":{"rich_text":[{"text":{"content":"Point A"}}]}}
]
}'
```
### Inspect a DB's property schema before writing
```bash
# Get the data_source_id
DB_ID="<DATABASE_ID>"
DS_ID=$(curly notion /databases/$DB_ID | jq -r '.data_sources[0].id')
# Then list properties
curly notion /data_sources/$DS_ID | jq '.properties | to_entries | map({name: .key, type: .value.type})'
# And valid multi_select options
curly notion /data_sources/$DS_ID | jq '.properties.Tags.multi_select.options | map(.name)'
```
### Query a DB by status + sort
```bash
curly notion /data_sources/$DS_ID/query -X POST -d '{
"filter": {"property": "Status", "select": {"equals": "In Progress"}},
"sorts": [{"property": "Due Date", "direction": "ascending"}],
"page_size": 100
}'
```
### Append to an existing page
```bash
curly notion /blocks/{page_id}/children -X PATCH -d '{
"children": [
{"object":"block","type":"divider","divider":{}},
{"object":"block","type":"heading_3","heading_3":{"rich_text":[{"text":{"content":"Update"}}]}},
{"object":"block","type":"paragraph","paragraph":{"rich_text":[{"text":{"content":"New content"}}]}}
]
}'
```
### Update a page's status
```bash
curly notion /pages/{page_id} -X PATCH -d '{
"properties": {"Status": {"status": {"name": "Done"}}}
}'
```
## Recipes (TS + bun) — bulk operations
The shell + jq examples above are right for one-offs. The moment you're touching multiple rows, composing dedup logic, or projecting properties for analysis — drop to a TS file run with `bun`. House style: ephemeral scripts in `/tmp`, raw API JSON preserved end-to-end, composable with everything else.
### Foundation — the two helpers you keep reusing
```ts
// /tmp/work/op.ts
import { spawnSync } from "child_process";
function curly(path: string, body?: any): any {
const args = ["notion", path];
if (body !== undefined) args.push("-X", "POST", "-d", JSON.stringify(body));
const r = spawnSync("curly", args, { encoding: "utf8" });
if (r.status !== 0) throw new Error(`curly ${path}: ${r.stderr.slice(0, 300)}`);
return JSON.parse(r.stdout);
}
function patch(pageId: string, props: any, label?: string): boolean {
const r = spawnSync("curly", ["notion", `/pages/${pageId}`, "-X", "PATCH",
"-d", JSON.stringify({ properties: props })], { encoding: "utf8" });
if (r.status !== 0) { console.log(`FAIL ${label || pageId}: ${r.stderr.slice(0, 200)}`); return false; }
return true;
}
```
Run with `bun /tmp/work/op.ts`. These two helpers cover ~80% of bulk work.
### Recipe — Fetch all rows with auto-pagination
```ts
const DS = "<data_source_id>";
let cursor: string | undefined = undefined;
const all: any[] = [];
do {
const b: any = { page_size: 100 };
if (cursor) b.start_cursor = cursor;
const r: any = curly(`/data_sources/${DS}/query`, b);
all.push(...r.results);
cursor = r.has_more ? r.next_cursor : undefined;
// On workspaces >1k rows, throttle: await new Promise(r => setTimeout(r, 400));
} while (cursor);
console.log(`fetched ${all.length}`);
```
### Recipe — Bulk PATCH from a JSON file
```ts
const work = JSON.parse(await Bun.file("work.json").text()); // [{id, props, name?}, ...]
let ok = 0;
for (const r of work) if (patch(r.id, r.props, r.name)) ok++;
console.log(`${ok}/${work.length}`);
```
### Recipe — Find page by name substring
```ts
const r = curly(`/data_sources/${DS}/query`, {
filter: { property: "Name", title: { contains: "Smith" } },
page_size: 5,
});
for (const p of r.results) {
console.log(p.id, p.properties.Name.title[0]?.plain_text);
}
```
### Recipe — Project rows to compact JSONL for analysis
When you need to grep/sort/count over a DB, project relevant properties to JSONL then process with `jq` or another bun script:
```ts
const project = (p: any) => ({
id: p.id,
name: p.properties.Name.title[0]?.plain_text || "",
status: p.properties.Status?.status?.name || "",
score: p.properties.Score?.number ?? null,
tags: (p.properties.Tags?.multi_select || []).map((o: any) => o.name),
});
await Bun.write("rows.jsonl", all.map(p => JSON.stringify(project(p))).join("\n"));
```
### Recipe — Extract URLs (or anything) from page block content
When the data you need lives in the page body (not properties) — embedded Loom URLs, pasted links, bookmark blocks — fetch `/blocks/{id}/children` and pattern-match across both `url`-typed blocks and inline rich-text:
```ts
const LOOM_RE = /https?:\/\/[a-zA-Z0-9.\-]*loom\.com\/[^\s)>\]"']+/gi;
const blocks: any = curly(`/blocks/${pageId}/children?page_size=100`);
const hits: string[] = [];
for (const b of blocks.results || []) {
const inner = b[b.type];
if (inner?.url && /loom\.com/i.test(inner.url)) hits.push(inner.url);
for (const x of inner?.rich_text || []) {
if (x.plain_text) hits.push(...Array.from(x.plain_text.matchAll(LOOM_RE)).map((m: any) => m[0]));
if (x.href && /loom\.com/i.test(x.href)) hits.push(x.href);
}
}
```
Same shape generalizes to LinkedIn URLs, calendar links, e-mails inside callouts — swap the regex.
### Recipe — Move a value between columns (atomic)
When a column gets renamed or split (e.g., a `URL` column becomes `LinkedIn` + a fresh `URL`), the typical job is move + clear in one PATCH:
```ts
patch(pageId, {
Loom: { url: oldUrl },
URL: { url: null }, // see Null-clear semantics
}, name);
```
### Save the work — per-session JSONL
For multi-day work, keep the per-session pulls in `/tmp/<session>/rows.jsonl` (re-fetchable cheaply) and the durable record in a file you track. Don't carry full DB dumps in conversation context.
## Block Types
Common block types for `children` arrays. Each takes `rich_text: [{text: {content: "..."}}]` unless noted:
- `paragraph`
- `heading_1`, `heading_2`, `heading_3`
- `bulleted_list_item`, `numbered_list_item`
- `to_do` (adds `checked: true/false`)
- `quote`, `callout` (callout adds `icon: {emoji: "💡"}`)
- `divider` (no content, just `{"divider":{}}`)
- `code` (adds `language: "bash"` etc.)
- `toggle` (expandable — takes `children` for collapsed content)
- `bookmark`, `embed` (take `url`)
- `image`, `file`, `video` (take `external: {url: "..."}` or `file: {url: "..."}`)
- `table` + `table_row`
- `child_page`, `child_database` (nested)
## Rich Text Structure
Inside any text-bearing block:
```json
{
"rich_text": [
{"text": {"content": "Plain text"}},
{"text": {"content": "bold"}, "annotations": {"bold": true}},
{"text": {"content": "linked", "link": {"url": "https://example.com"}}},
{"mention": {"type": "page", "page": {"id": "page_id"}}}
]
}
```
`annotations`: `bold`, `italic`, `strikethrough`, `underline`, `code`, `color`.
## Property Write Formats
Common property types for page `properties`:
| Type | Write format |
|------|--------------|
| `title` | `{"title":[{"text":{"content":"..."}}]}` |
| `rich_text` | `{"rich_text":[{"text":{"content":"..."}}]}` |
| `number` | `{"number":42}` |
| `select` | `{"select":{"name":"Option"}}` |
| `multi_select` | `{"multi_select":[{"name":"A"},{"name":"B"}]}` |
| `status` | `{"status":{"name":"In Progress"}}` |
| `date` | `{"date":{"start":"2026-04-17","end":null}}` |
| `checkbox` | `{"checkbox":true}` |
| `url` / `email` / `phone_number` | `{"url":"https://..."}` |
| `relation` | `{"relation":[{"id":"page_id"}]}` |
| `people` | `{"people":[{"id":"user_id"}]}` |
## Null-clear semantics
How to clear a value on a page property. Notion treats `null` vs empty-array vs absent differently per type — this is the truth table. Verified 2026-06-09 against a live database for `url`, `select`, `multi_select`, `rich_text`; others extrapolated from API docs.
| Type | Clear with |
|------|-----------|
| `url` / `email` / `phone_number` | `{"url": null}` (use the matching key for each type) |
| `number` | `{"number": null}` |
| `select` | `{"select": null}` |
| `status` | `{"status": null}` *(may snap to first option — verify on your DB)* |
| `multi_select` | `{"multi_select": []}` |
| `rich_text` | `{"rich_text": []}` |
| `title` | `{"title": []}` *(creates an untitled page — rarely what you want)* |
| `date` | `{"date": null}` |
| `checkbox` | `{"checkbox": false}` (no true "clear" — defaults to false) |
| `relation` | `{"relation": []}` |
| `people` | `{"people": []}` |
## Filter Cookbook
The 6 shapes that cover ~80% of queries on `/data_sources/{id}/query`. Drop into the `filter` field:
```jsonc
// status equals
{"property": "Status", "status": {"equals": "Active"}}
// status NOT in a set — compound NOT
{"and": [{"property": "Status", "status": {"does_not_equal": "Dead"}},
{"property": "Status", "status": {"does_not_equal": "No Fit"}}]}
// multi_select contains a tag
{"property": "Tags", "multi_select": {"contains": "Hot"}}
// is_empty / is_not_empty (works on most types — use the type key)
{"property": "Loom", "url": {"is_empty": true}}
{"property": "Email", "email": {"is_not_empty": true}}
// title contains substring (case-insensitive)
{"property": "Name", "title": {"contains": "Jordan"}}
// number greater_than
{"property": "Score", "number": {"greater_than": 70}}
// date on/after
{"property": "LastReviewedAt", "date": {"on_or_after": "2026-01-01"}}
// AND / OR — compose any of the above
{"and": [<filter1>, <filter2>, ...]}
{"or": [<filter1>, <filter2>, ...]}
```
**Operator key by type** (the slot inside the type-keyed object):
- `title` / `rich_text` / `url` / `email` / `phone_number`: `equals`, `does_not_equal`, `contains`, `does_not_contain`, `starts_with`, `ends_with`, `is_empty`, `is_not_empty`
- `number`: `equals`, `does_not_equal`, `greater_than`, `less_than`, `greater_than_or_equal_to`, `less_than_or_equal_to`, `is_empty`, `is_not_empty`
- `select` / `status`: `equals`, `does_not_equal`, `is_empty`, `is_not_empty`
- `multi_select`: `contains`, `does_not_contain`, `is_empty`, `is_not_empty`
- `date`: `equals`, `before`, `after`, `on_or_before`, `on_or_after`, `past_week`, `past_month`, `past_year`, `next_week`, `next_month`, `next_year`, `is_empty`, `is_not_empty`
- `checkbox`: `equals`, `does_not_equal`
- `relation` / `people`: `contains`, `does_not_contain`, `is_empty`, `is_not_empty`
## Workspace Conventions
- Work additively — don't overwrite pages without explicit intent
- Tag Claude-authored pages with 🤖 emoji when appropriate
- Prefer DB properties over inline markdown for structured data
- Set `archived: true` instead of deleting
- Use search before creating to avoid duplicates
## Fallback: MCP
If `curly` isn't available, Notion MCP works but requires per-session `/mcp` auth. See the MCP docs. Direct API is strictly preferred.
## Docs
- [Notion API reference](https://developers.notion.com/reference)
- [Database properties](https://developers.notion.com/reference/page-property-values)
- [Block reference](https://developers.notion.com/reference/block)
## Database Registry
Keep your own registry of *which* Notion databases you use (ids, purposes, when-to-use) somewhere private, and read it before creating any page or querying a DB by a hardcoded id, so you use an existing database instead of guessing or recreating one. Real ids are per-owner configuration and do not belong in a public doc. Placeholders show the shape:
- **Contacts** — data_source `<CONTACTS_DS_ID>`, database `<CONTACTS_DB_ID>`.
- **Projects** — data_source `<PROJECTS_DS_ID>`, database `<PROJECTS_DB_ID>`.
**Block append position (MEASURED 2026-11-22, dev bleeding-edge run):** `PATCH /blocks/{id}/children` now rejects the old top-level `after` field. Use `"position":{"type":"after_block","after_block":{"id":"<block id>"}}` to insert after a sibling.
---
*Related: `@integrations/linkedin` · `@integrations/agent-browser` · `@protocol/protocol-api` · `@content/youtube/tiago-forte/how-they-organize-everything-the-code-challenge` · `@content/youtube/tiago-forte/the-code-challenge-begins-3-strangers-30-days-one-method`*
---
*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*
*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*