# Notion

A workspace's databases and pages from the back end, over Notion's own HTTP
API: a database's rows queried with filters and sorts and read page by page,
each property as a plain value (and into the program's own shapes by a fn of
its own), rows and pages made and changed, search, and a page's content read
as Markdown and written from Markdown, through the one Markdown reader Mote
has ([`syntax.parse(text, "markdown")`](text.md#markdown)). An
[extension](../extensions/README.md): `extensions/notion/`. Back to the
[map](README.md).

```mote
use "pkg:notion/notion.mote"

// The tasks of a team's Notion database, as the program has them.
shape Task
  id: string
  title: string
  status: string
  points: number
  due: string

fn taskOf(r: NotionRow): Task = {id: r.id, title: notionTextOf(r, "Name"), status: notionTextOf(r, "Status"), points: notionNumberOf(r, "Points"), due: notionTextOf(r, "Due")}

fn tasks(): string = env("NOTION_TASKS")

// What is still to do, the soonest first: every page of it.
server fn openTasks(): Task[] requires signedIn
  let rows = notionAll(tasks(), {filter: notionWhere("Status", "status", "does_not_equal", "Done"), sorts: [notionSort("Due", "ascending")]}, 500, "")?
  return rows.map(taskOf)

// A task made, its notes written as Markdown into the page.
server fn addTask(title: string, notes: string): Task requires signedIn
  return taskOf(notionCreate(tasks(), {Name: notionTitle(title), Status: notionStatus("To do")}, notes, "")?)

// A page's content, as Markdown, for the kit's Markdown to show.
server fn handbook(): string requires signedIn
  return notionRead(env("NOTION_HANDBOOK"), "")?
```

```sh
NOTION_TOKEN=ntn_… NOTION_TASKS=<data source id> bun dist/server/main.js
```

**Not met Notion.** Written from Notion's API reference as of 2026, for
the version `2025-09-03`, and run against a stand-in
(`tests/svc_standin.mjs work`) that answers in Notion's shapes and refuses
what Notion refuses (a request of more than a hundred blocks, blocks nested
deeper than two levels in one, a piece of text over 2000 characters, a
missing `Notion-Version`). The steps to check it with a real workspace are
[below](#checking-it-against-notion).

## The settings

| | |
|---|---|
| `NOTION_TOKEN` | An internal integration's secret (`ntn_…`; older ones `secret_…`), from notion.so/profile/integrations, a [secret](back-end.md#secrets). Every call takes a `token` last: `""` for this one, or another: a person's access token from a public integration's OAuth, to act in their workspace (OAuth is not this extension's). |
| `NOTION_VERSION` | The `Notion-Version` asked for: `2025-09-03` unsaid. |
| `NOTION_RATE` | Requests a second, at most, from this back end: 3 unsaid. |
| `NOTION_API` | Another address for the API (a stand-in). |

An integration sees only what is shared with it: a page's or a database's
`•••` menu → Connections → the integration. Its capabilities (Read content,
Update content, Insert content) are what its calls may do; a call it may
not make is `"auth"`.

**Databases and data sources.** Since `2025-09-03` a database holds one or
more *data sources*, each with its own properties and rows: rows are queried
and made in a data source. `notionSources(database, "")` gives a database's
(its id is in its address); a data source's id is also under the database's
`•••` → Manage data sources → Copy data source ID. Every call that takes an
id takes it with or without dashes, or a page's whole address.

## The calls

| | |
|---|---|
| `notionQuery(source, q, cursor, token)` | One page of a data source's rows (100 at most): `NotionRows {rows, next}`; `next` is `""` at the end. `q` is `{filter?, sorts?, size?}`. |
| `notionAll(source, q, most, token)` | Every page, up to `most` rows: `NotionRow[]`. |
| `notionPage(page, token)` | One page, as a row. |
| `notionCreate(source, properties, markdown, token)` | A row of a data source, with its content from Markdown (`""` for none). |
| `notionSubpage(parent, title, markdown, token)` | A page inside a page. |
| `notionUpdate(page, properties, token)` | Some properties set; the rest as they were. |
| `notionTrash(page, trashed, token)` | To the trash (`false`: back out). |
| `notionRead(page, token)` | The page's content as Markdown, every level down (eight at most). |
| `notionAppend(page, markdown, token)` | Markdown put at the end of a page (or under a block): the number of blocks made. |
| `notionReplace(page, markdown, token)` | The content made this Markdown: each block that was there to the trash, then the new. |
| `notionBlocks(block, depth, token)` | A block's children as Notion gives them, `depth` levels down, each block's own under `children`. |
| `notionSearch(words, kind, cursor, token)` | What the integration sees whose title has the words: `NotionFinds {found, next}`, each `{id, kind, title, url, edited}`; `kind` `"page"`, `"data_source"` or `""`. |
| `notionSources(database, token)` · `notionSource(source, token)` | A database's data sources; a data source with its properties' types (`{Name: "title", Status: "status", …}`). |

**A row** is `NotionRow {id, url, created, edited, trashed, values,
properties}`. `values` has each property by its name as a plain value:

| Property | Plain value |
|---|---|
| title, rich_text, url, email, phone_number, select, status, created_time, last_edited_time, verification | text (`""` when empty) |
| number | the number, or none |
| checkbox | `true` / `false` |
| date | its start (`notionDateOf(r, name)` gives `{start, end, zone}`) |
| multi_select | the names, a list |
| people, created_by, last_edited_by | the people's ids |
| relation | the pages' ids (Notion gives 25 at most in a row; more needs the page's property endpoint, not here) |
| files | their addresses (a file Notion keeps has an address that lasts an hour) |
| unique_id | `TASK-12` |
| formula | its result, as whichever of the above it is |
| rollup | a number, a date's start, or a list of plain values |

`notionTextOf(r, name)`, `notionNumberOf`, `notionBoolOf`, `notionListOf` and
`notionDateOf` read one, `""`, `0`, `false` or `[]` when it is not there; a
fn of the program's own (`taskOf` above) makes a row its own shape.
`properties` is what Notion sent, for anything else.

**Properties to write**, one fn a kind, each giving what Notion takes as
that property's new value: `notionTitle(text)`, `notionRichText(text)`,
`notionNumber(n)` (none empties it), `notionSelect(name)`,
`notionMultiSelect(names)`, `notionStatus(name)`, `notionDate(start, end)`
(`end` `""` for one day or moment), `notionCheckbox(on)`, `notionUrl(url)`,
`notionEmail(email)`, `notionPhone(phone)`, `notionPeople(ids)`,
`notionRelation(ids)`. Any record Notion takes may be given in their place.

**Filters and sorts** are Notion's own records, or made by
`notionWhere(property, type, test, value)` (`notionWhere("Due", "date",
"on_or_before", "2026-12-01")`), `notionAllOf([…])`, `notionAnyOf([…])` and
`notionSort(property, "ascending")` (`"created_time"` and
`"last_edited_time"` sort by those).

| Kind | |
|---|---|
| `"auth"` | The token is wrong, or the integration lacks the capability. |
| `"missing"` | No such page, block or data source, or it is not shared with the integration (the sentence says how to share it). |
| `"invalid"` | Notion did not take what was asked: `err.data.code` is Notion's (`validation_error`, …). |
| `"conflict"` | The same thing was being changed at once: ask again. |
| `"limited"` · `"notion"` · `"offline"` | Limited after the waits; Notion broke (5xx); no answer. |

`err.data` is `{status, code, request}`: `request` is Notion's request id,
for their support.

## Markdown

`notionBlocksOf(markdown)` gives the blocks Notion takes, and
`notionMarkdown(blocks)` Markdown of the blocks Notion gives; `notionRead`,
`notionAppend`, `notionReplace` and `notionCreate` use them.

| Markdown | Notion |
|---|---|
| `#`, `##`, `###` (and deeper, as `###`) | heading_1, heading_2, heading_3 |
| a paragraph; `**`, `*`, `~~`, `` ` ``, `[words](https://…)`; a line break | paragraph; bold, italic, strikethrough, code, a link; `\n` in the text |
| `-` and `1.` lists, nested | bulleted_list_item, numbered_list_item, the inner list as the item's children |
| `- [ ]`, `- [x]` | to_do |
| `>` | quote (its later paragraphs as children) |
| fenced code with a language | code, with Notion's name of the language (`ts` is `typescript`; one Notion has not is `plain text`) |
| `---` | divider |
| a table | table and table_row, the first row the column header |
| `![alt](https://…)` standing alone | image, the alt its caption |
| footnotes | paragraphs `[1] …` at the end |

Read back, a callout is a quote with its emoji, a toggle a list item with
what it holds under it, an equation `$$…$$` (inline, `$…$`), a file, a PDF,
a video or a bookmark a link, a child page or database a link to it, columns
and synced blocks what they hold. A mention is its words. Text that Markdown
would read as a mark is escaped (`2\*3`), and a paragraph that begins like a
heading or a list is too, so that Markdown written from blocks and read back
gives the same blocks for everything both have (`tests.mote` holds a
document that goes round both ways).

Writing, a hundred blocks go in one request, and a block's children with it
when they have none of their own (Notion takes two levels of nesting in a
request); deeper ones are put in after, under the block Notion made. A piece
of text longer than 2000 characters is cut into pieces of 2000.

Not carried either way: colours, underline (Markdown has none), a link that
is not a whole address (Notion takes none: its words stay), mentions written
(they come back as their words), and what Notion has no block for (raw HTML
is text, as the Markdown reader makes it).

## Limits

Notion takes about three requests a second from an integration, averaged,
and answers 429 with `Retry-After` past it. Every request here is given a
moment of its own, `NOTION_RATE` a second, shared by every fn and job of the
back end (a row, `NotionPace`); a 429 is waited out (twice at most) by
`net.send` itself: a write too, since a 429 says nothing was done. A request
is at most 1000 blocks and 500 KB to Notion: `notionAppend` keeps to a
hundred a request.

## In a person's name

Every call takes its `token` last: a public integration's access token for
a person's workspace works where `NOTION_TOKEN` does, and sees what they
shared with it. The [oauth](oauth.md) extension has no Notion provider yet:
Notion's OAuth is not OpenID Connect, and who someone is comes from
`/v1/users/me`, a kind of provider it does not know. When it has one, the
call is

```mote
server fn myTasks(source: string): NotionRows requires signedIn
  let token = oauthToken(notionProvider(), auth.me()?.id ?? "")?   // once oauth has notionProvider
  return notionQuery(source, {}, "", token)?
```

and until then a token from a flow of the program's own goes in the same
place.

## Left out

Comments, users and the bot's own user, a property's own endpoint (more
than 25 people or relations, a rollup over many), creating or changing a
database's or data source's schema, file uploads (Notion's own upload API),
moving pages, templates, webhooks (Notion's webhooks are an integration
setting with their own verification token: not written yet), and OAuth
(each call takes a token). The version is said in one setting:
`NOTION_VERSION`.

**Unsure.** The version `2025-09-03` is the latest Notion had published
when this was written; Notion may have published a later one in 2026, in
which case the shapes here are those of 2025-09-03 still, and that is the
version to ask for. `in_trash` (in place of `archived`) and the
`data_source_id` parent are as 2025-09-03 has them.

## Checking it against Notion

1. Make an internal integration at notion.so/profile/integrations, with Read,
   Update and Insert content; set its secret as `NOTION_TOKEN`.
2. Make a database with properties Name (title), Status (status), Points
   (number), Due (date), Tags (multi-select); share it with the integration
   (`•••` → Connections). `notionSources(<its id>, "")` gives the data
   source's id.
3. `notionCreate(source, {Name: notionTitle("A"), Status: notionStatus("Not
   started"), Points: notionNumber(2)}, "# Hello\n\n- one\n  - two\n    - three", "")`:
   the row is in the database, its page holds the heading and the list three
   deep.
4. `notionAll(source, {filter: notionWhere("Points", "number",
   "greater_than", 1)}, 500, "")` with more than a hundred rows: every one,
   in pages.
5. `notionRead(page, "")` of a page written by hand in Notion (a callout, a
   toggle, a table, code): Markdown as above.
6. A loop of fifty `notionPage` calls: no 429 (they are spaced), and if one
   comes, it is waited out.

Recorded in `tests/expect/real_svc_work.txt` (`tests/all.sh
real_svc_work`): a database's data sources, a row made with content nested
three deep, read back the same, rows two a page, a filter, an update, 130
blocks appended in two requests, content replaced, search, the trash, a
page not shared, a 429 waited out, a token refused, no request sooner than
the rate; and the extension's own `mote test`.
