# Airtable

A base's tables from the back end, over Airtable's Web API: records listed
with a formula, a view, sorts and fields, page by page, into the program's
own shapes; made, changed, upserted and deleted ten a request, as Airtable
takes them; the base's limit of five requests a second kept; and a base's
changes told to the program through Airtable's webhooks, each checked and
told once. An [extension](../extensions/README.md): `extensions/airtable/`.
Back to the [map](README.md).

```mote
use "pkg:airtable/webhooks.mote"

shape Lead
  id: string
  name: string
  email: string
  stage: string
  value: number

fn leadOf(r: AirtableRecord): Lead = {id: r.id, name: airtableTextOf(r, "Name"), email: airtableTextOf(r, "Email"), stage: airtableTextOf(r, "Stage"), value: airtableNumberOf(r, "Deal value")}

fn crm(): string = env("AIRTABLE_BASE")

// The leads still open, the biggest first, every page of them.
server fn openLeads(): Lead[] requires signedIn
  let rows = airtableAll(crm(), "Leads", {formula: `NOT(${airtableEq("Stage", "Closed")})`, sort: [{field: "Deal value", direction: "desc"}]}, 1000, "")?
  return rows.map(leadOf)

// Sign-ups from the program's own form, kept in the CRM by their email: one made, or changed.
server fn keepLead(name: string, email: string): string requires anyone limit 10 per minute by ip
  let done = airtableUpsert(crm(), "Leads", [{Name: name, Email: email, Stage: "New"}], ["Email"], true, "")?
  return done.created.length > 0 ? "new" : "known"

// Told when someone changes the table in Airtable.
fn airtableChanged(c: AirtableChanged): bool
  log.info("leads changed", {made: c.created.length, changed: c.changed.length, gone: c.destroyed.length})
  return true
```

```sh
AIRTABLE_TOKEN=pat… AIRTABLE_BASE=app… bun dist/server/main.js
```

**Not met Airtable.** Written from Airtable's Web API reference as of 2026
and run against a stand-in (`tests/svc_standin.mjs work`) that answers in
its shapes, refuses more than ten records a request, notes a request sooner
than five a second, and pings the program's webhook signed as Airtable
does. The steps to check it with a real base are
[below](#checking-it-against-airtable).

## The settings

| | |
|---|---|
| `AIRTABLE_TOKEN` | A personal access token (`pat…`, airtable.com/create/tokens), with the scopes `data.records:read`, `data.records:write` (and `webhook:manage` for webhooks) and the bases it may reach. A [secret](back-end.md#secrets). Every call takes a `token` last: `""` for this one, or another (a person's, from Airtable's OAuth, which is not this extension's). |
| `AIRTABLE_RATE` | Requests a second to one base, at most, from this back end: 5 unsaid. |
| `AIRTABLE_WAIT` | The longest wait after a 429, in seconds: 35 unsaid. |
| `AIRTABLE_API` | Another address for the API (a stand-in). |

A base is its id (`app…`, in its address); a table is its id (`tbl…`) or its
name; a field its name, or its id with `byId: true` (an id does not change
when the field is renamed: a program that must outlast renames uses ids).

## The calls

| | |
|---|---|
| `airtableList(base, table, q, offset, token)` | One page (100 at most): `AirtableRecords {records, offset}`; `offset` is `""` at the end. |
| `airtableAll(base, table, q, most, token)` | Every page, up to `most`: `AirtableRecord[]`. |
| `airtableGet(base, table, id, token)` | One record. |
| `airtableCreate(base, table, rows, typecast, token)` | Records made from their fields (`[{Name: "Lamp", Price: 45}]`), ten a request. |
| `airtableUpdate(base, table, changes, typecast, token)` | `[{id, fields}]`: those fields set, the others left. |
| `airtableUpsert(base, table, rows, mergeOn, typecast, token)` | Each row changes the record whose `mergeOn` fields are its own, or is made: `AirtableUpserted {records, created, updated}` (the ids). |
| `airtableDelete(base, table, ids, token)` | The ids deleted. |

`q` is `AirtableQuery`, each part optional: `formula` (a formula a record
must make true), `view` (its filters, its order and only its records),
`sort` (`[{field, direction: "asc" | "desc"}]`), `fields` (only these),
`size` (a page), `byId`, `zone`, `cellFormat` (`"string"`: each value as
Airtable shows it). It is sent as `listRecords` with the query in a body, so
a long formula is never too long for an address.

`typecast`: Airtable makes a text into the field's kind (a new select
option, a linked record by its name). A write of more than ten goes in
groups of ten; one that fails says, in `err.data.done`, how many the groups
before it wrote.

**A record** is `AirtableRecord {id, created, fields}`; an empty field is
not in `fields` at all (Airtable leaves it out). `airtableTextOf(r, field)`
(a select's text, a collaborator's name, a list joined), `airtableNumberOf`,
`airtableBoolOf`, `airtableListOf` (a multiple select, linked records' ids, a
lookup), `airtableFilesOf` (`{id, url, name, type, size}`; the addresses
last a couple of hours) read one; a fn of the program's own (`leadOf` above)
makes a record its own shape.

**Formulas**: `airtableEq(field, value)` is `{Field} = "value"`,
`airtableField(name)` a field (`{Due date}`), `airtableQuote(text)` a text as
a formula's literal; quotes, backslashes and braces in them are escaped.

| Kind | |
|---|---|
| `"auth"` | The token is wrong, lacks a scope, may not reach the base, or the base or table is not there (Airtable answers 403 for each and does not say which). |
| `"missing"` | No such record. |
| `"invalid"` | Airtable did not take what was asked (`err.data.type`: `INVALID_VALUE_FOR_COLUMN`, `UNKNOWN_FIELD_NAME`, …). |
| `"limited"` · `"airtable"` · `"offline"` | Limited after the waits; Airtable broke (5xx); no answer. |

## Limits

Airtable takes five requests a second for each base (and fifty for each
token across bases); past that it answers 429 and takes nothing more from
that base for thirty seconds. Every request here is given a moment of its
own for its base (`AIRTABLE_RATE` a second), shared by every fn and job of
the back end (a row, `AirtablePace`); after a 429 the base is held for every
caller (`Retry-After` when Airtable sends it, else thirty seconds) and the
request asked again, twice at most. Asked to wait longer than
`AIRTABLE_WAIT`, a call fails `"limited"` at once (`err.data.retryAfter`). A
`GET` or `DELETE` is asked again on 5xx; a write is not (Airtable keeps no
idempotency keys).

## Webhooks

`use "pkg:airtable/webhooks.mote"`. Airtable does not post a change: it
pings the program's address that something changed, signed, and the program
reads the changes from the webhook.

```text
airtableWatch(base, table, "https://<site>/airtable/webhook", "")?    a webhook, kept (AirtableHook)
airtableUnwatch(id, "")?                                               let go
fn airtableChanged(c: AirtableChanged): bool                           the program's hook
```

- **The ping** at `POST /airtable/webhook` is checked first: its
  `X-Airtable-Content-MAC` must be `hmac-sha256=` and the hex of an
  HMAC-SHA256 of the body, under the webhook's secret (Airtable gives it
  once, in base64, when the webhook is made: it is kept in `AirtableHook`,
  the program's database). A ping not signed is a 401. A signed one is
  answered at once, and the reading handed to a job.
- **The job** (`airtablePull`, `unique`) reads every payload after the
  webhook's cursor, tells the program each table's change, and keeps the
  cursor. Each change is told once, by the base's transaction
  (`AirtableSeen`), however many pings arrive.
- **`AirtableChanged`**: `{base, table, created, changed, destroyed, cells,
  source, at, transaction}`: the ids made, changed and deleted, the cells of
  those made and changed now (by record id, then field id), and what made it
  (`"client"`, `"publicApi"`, `"formSubmission"`, `"automation"`, …).
- A hook that fails is tried again from the same payload: make it safe to
  run twice. Each day a webhook that would lapse within two days (Airtable
  lets one go seven days after it was made or refreshed) is refreshed.
- The payloads are read with `AIRTABLE_TOKEN`: a webhook made with another
  token is read with this one.

## Left out

Comments, the metadata API (bases, tables and fields listed or changed),
attachments uploaded (Airtable's upload endpoint), `PUT` that clears the
fields unsaid, a webhook's filters beyond one table's data, and OAuth.

## Checking it against Airtable

1. A token at airtable.com/create/tokens with `data.records:read`,
   `data.records:write`, `webhook:manage` and one base; `AIRTABLE_TOKEN`.
2. A table Tasks with Name (text), Status (single select), Points (number).
3. `airtableCreate(base, "Tasks", <25 rows>, true, "")`: 25 records, three
   requests; `airtableAll(base, "Tasks", {formula: airtableEq("Status",
   "Open"), size: 10}, 100, "")` gives them back in pages of ten.
4. `airtableUpsert(…, ["Name"], …)` with one name that is there and one
   that is not: one changed, one made.
5. A loop of thirty `airtableGet` calls: none refused (they are spaced).
6. `airtableWatch(base, "<tbl id>", "https://<a public address of the
   program>/airtable/webhook", "")`, then change a record by hand in
   Airtable: `airtableChanged` is told, once.

Recorded in `tests/expect/real_svc_work.txt` (`tests/all.sh
real_svc_work`): a webhook made, 23 records made in three requests, read ten
a page, a formula, an upsert, an update, twelve deleted in two requests, a
value refused, a table that is not there, a 429 waited out, the seven
changes told once each by the webhook, a ping not signed refused, no
request sooner than the rate; and the extension's own `mote test`.
