Attributes: defining, archiving and writing them
Merge semantics: only the keys present in values are touched, and each
request succeeds or fails atomically (batch items are the partial-success
unit). Every “You send” form below is a branch of the AttributeValueWrite
component, so a generated client can validate a write statically: the op
objects are MultiSelectOp, CounterOp and CounterOpBatch, and a
counter full replace is an array of CounterEntry. Which branches a given
attribute accepts follows from its data_type — the server validates that
per attribute and answers a FieldErrorCode keyed on the attribute, never
as a body-path schema error. Which code depends on how the form is wrong, and
the four are worth telling apart before you write the branch:
| What you sent | Code |
|---|---|
a plain value of the wrong JSON type (a number for a select, an array for a scalar, a non-string inside a multi_select array) | type_mismatch |
| an op object to an attribute that takes no ops at all (every scalar type) | op_not_supported |
| an op object to an attribute that DOES take ops, naming the wrong op family or a member the op has not got | invalid_op |
a well-formed select/multi_select value outside the definition’s options | unknown_option |
Field error codes defines every member
individually — read them there rather than inferring semantics from
detail, which is prose written for a human reading a log.
| You send | Effect |
|---|---|
"key": null | clears the value (deletes the row — “not set”) |
"key": <scalar> | sets a text/number/boolean/date/datetime/select value (JSON type must match) |
multi_select: ["a","b"] | full replace. [] empties the set but keeps it “set”; null unsets it |
multi_select: {"op":"add"|"remove","values":[…]} | atomic mutation; values is required and non-empty |
counter_list: {"op":"increment","key":"k","by":2,"at":"…"} | one op; by defaults 1, must be a whole number, may be negative, floors at 0 |
counter_list: {"op":"set_key","key":"k","count":9,"last_at":"…"} | one op; sets that key’s count outright (whole, ≥ 0) instead of adding to it. last_at defaults to the stored one, or now for a new key |
counter_list: {"op":"remove_key","key":"k"} | one op; drops that key. A no-op when it is not there, never an error |
counter_list: {"ops":[…]} | up to 100 of the three ops above, applied in order under the row lock |
counter_list: [{key,count,last_at?},…] | full replace (STRICT element schema) |
A multi_select is a set on both write forms: a full replace
deduplicates exactly as add does, so ["a","a","b"] stores two values,
add of a value already present is a no-op, and remove of one takes the
only copy there is. Order is first-seen — new values append — and it carries no
meaning beyond being stable. A duplicate therefore cannot consume the
multi_select_values_per_row budget twice.
Counter zero-representation: count 0 removes the entry — an absent key IS
the zero; you never see {"count": 0} in a read. last_at is a monotonic
max bumped only by positive increments (backfilled reports never rewind
recency); on replace, an omitted last_at preserves the stored one. Counter
keys are distinct: a full replace naming one twice is rejected rather than
stored as two entries the op forms could not then address.
counter_list entry order is NOT the stable property multi_select’s
is. Two reads of an unchanged value agree, but a write re-orders: an
{"ops":[…]} request moves every key it touches to the END of the array, so
incrementing one key of five changes the position of that key on the next read.
Treat the array as an unordered map keyed by key, and sort by count or
last_at yourself if you need a ranking — do not index by position and do not
diff two reads positionally.
Increment a counter rather than replace it
Section titled “Increment a counter rather than replace it”A full replace ([…]) overwrites the whole list, and with it the counts other
integrations wrote into it. To add to a count, send
{"op":"increment",…}, which the server applies under the row lock without
needing the old value.
Which options constrain a write, and which do not
Section titled “Which options constrain a write, and which do not”options is the only field whose meaning changes with the attribute’s
data_type, and the two shapes differ in whether they are a contract or a
hint. Both are published as schemas — SelectOption and
CounterListOptions — so this is the summary, not the definition:
| data_type | options | Constrains writes? |
|---|---|---|
select, multi_select | [{value,label}] | Yes. A value outside the list answers unknown_option, which names the accepted ones. |
counter_list | {groups:[{key,label,item_keys}]} | No. Any key may be incremented, declared or not. |
| everything else | none | — |
A counter’s key space is open, and that is the design. A restaurant sells a
dish before anyone edits an attribute definition, so requiring a declaration
would make the first sale of every new item fail. item_keys is therefore a
statement about keys, not a gate on them: it is what a segment rule resolves
when it asks “has this guest ordered any mains” (the key_in_group
operator — see SegmentAttributeCondition.group_key), and what the Nine
Tables app offers a person picking keys by hand. Nothing in a counter read or
write mentions a group: CounterEntry and all three CounterOp branches
carry a bare key.
Consequences worth knowing before you model counters:
- Declaring a group is optional, and so is its
item_keys. A group with no items is legal; it simply stands for no keys and matches nothing. - Groups and item keys are append-only. A
PATCHthat drops one is rejected, because a segment could be compiled against it. - Two limits, two different things.
counter_item_keys_per_groupbounds what you may DECLARE on the definition.counter_keys_per_rowbounds how many distinct keys one customer’s stored value may CARRY, and is the one a write can exceed. They are unrelated numbers; neither implies the other.
Responses echo the post-write values with per-value updated_at and source.
When your key holds attributes:read, the echo is the record’s FULL value set.
Otherwise it carries only the keys the request
wrote, so an empty values echoes {}. A key you send with the value already stored is a no-op: its
updated_at and source stay those of the last real change, so the token
another integration holds stays valid.
Guard a write on the value you read
Section titled “Guard a write on the value you read”Every write is last-write-wins unless you send the optional expect map,
which guards it on the updated_at token you last read for each key. When a
token no longer matches that value’s current updated_at, the value changed
since you read it: the whole patch is refused with 409 conflict-stale-write,
nothing is written, and drifted names the keys to re-read.
Reading values
Section titled “Reading values”GET /customers/{customerRef}/attributes and
GET /bookings/{bookingRef}/attributes answer the value set alone, keyed by
definition key, each value with its own updated_at and source;
GET /customers/{customerRef}, which requires customers:read, answers the
same set beside the customer when your key also holds attributes:read, and
leaves values out without it. Values
of archived definitions are left out unless you pass include_archived=true.
The booking read also carries the booking itself, as booking, when your key
holds bookings:read, because attributes:read does not read the diary.
Writing many records with POST /batch
Section titled “Writing many records with POST /batch”POST /batch takes up to 100 items
{entity, ref, values} and applies them SEQUENTIALLY in array order, one
transaction per item, so the ITEM rather than the request is the unit of
success. A refused item costs its neighbours nothing: the items that succeeded
stay applied, there is no rollback of a batch, and no later item is skipped
because an earlier one failed, a fault on our side included.
The call therefore answers 200 whatever its items did, with one result per
item in request order: branch on each result’s status, never on the
response status. A result carries:
index, the item’s 0-based position, so a client that sorts, filters or splits its array can still pair every result with the item it sent;entityandref, echoed exactly as you sent them. Neither is inferred, normalised, case-folded or replaced by the id it resolved to, so an item that sayscustomerfor a ref that is in fact a booking comes back ascustomerwith a404, because the ref was looked up among customers;status, the status the same write would have answered as a singlePATCH …/attributes:200when it applied,400for a malformedrefor a refused value,404when therefmatched no record,409for a staleexpector a booking pair naming bookings at several restaurants (ambiguous-ref), and500(internal) for a fault on our side;- exactly one of
valuesandproblem. On a200,valuesis the post-write echo described above, so withattributes:reada successful item doubles as a full read of its record. Otherwiseproblemis the item’s complete problem body, byte-identical to what the single write would have answered,type,codeanderrors[]included: dispatch on itstypeas you would on a top-level error. The response itself isapplication/json, notapplication/problem+json, because these problems ride inside a successful envelope.
A 500 item may still have been applied, because the fault can come after its
write commits. Read the record before sending that item again, and send it in a
new request under a new Idempotency-Key, since this batch’s key replays this
response (see Idempotency).
A fault in the ENVELOPE answers a whole-request 400 validation-failed:
items missing, empty, longer than 100 or
than your key’s rate_limit_per_min (see
Rate limits), or an item with an unknown
member. Every per-item failure rides in the 200 as that item’s problem.
Defining an attribute
Section titled “Defining an attribute”A value is written against an attribute definition, which must exist first.
GET /definitions is the catalogue: every definition the tenant holds, of both
entities unless entity= narrows it, in display_order with ties broken on
key, and unpaginated, since a tenant holds at most
200 definitions of its own, archived ones
included. Archived definitions are left out unless you pass
include_archived=true.
A definition’s identity is the pair (entity, key):
entityiscustomerorbooking. A customer attribute holds one value per guest, written withPATCH /customers/{customerRef}/attributes; a booking attribute holds one value per visit, written withPATCH /bookings/{bookingRef}/attributes, and is what a segment’s booking conditions read. The two are separate namespaces, sospendmay exist on both as two unrelated attributes. A write naming a key that exists only on the OTHER entity is refusedentity_mismatch, where a key that exists nowhere isunknown_attribute.keyis the name you write values under invalues, and theattribute_keyordefinition_keya segment condition names: lowercase[a-z0-9_]starting with a letter, at most 64 characters. It is immutable, with no rename, and an archived definition keeps it reserved.
That is why POST /definitions carries entity in its body rather than its
path, and why its 201’s Location points at /definitions/{entity}/{key}.
entity, key and data_type are fixed at creation, and PATCH has no
member for any of them.
The rest of a definition describes how the Nine Tables app shows it, and none of it changes which values this API accepts:
label, 1 to 200 characters, is the name staff see. It carries no machine meaning, so it is safe to change;keyis what your code holds on to.description, up to 2000 characters, is helper text for the staff who fill the attribute in. OnPATCH,nullclears it and omitting it leaves it.categoryfiles the attribute under one category.display_ordersorts ascending, any integer of 0 or more, and defaults to0. Nothing re-numbers for you, so space values out (10, 20, 30) if you expect to insert between two later.display_hintformats anumber:currencyrenders it in the active restaurant’s currency, so store a major-unit amount (450shows as 450,00; nothing on this API is in minor units),percentrenders a 0 to 100 scale (store12.5for 12.5%, as the built-inno_show_ratedoes), andduration_minutesrenders a count of minutes. It is not checked againstdata_type, and the app ignores it on every other type.show_on_customer_cardpromotes a customer attribute into the summary on a guest’s customer card, andshow_on_booking_panelshows a booking attribute on the panel staff work a booking from. Both default tofalse, and each is stored, echoed and consulted by nothing on the other entity.
A PATCH of a definition or a category applies only the members it carries,
so one with none is accepted and changes nothing. The record’s updated_at
tracks the record itself, never the values written against a definition or the
definitions filed under a category, each of which carries its own. Every
accepted PATCH moves it, even one that re-sends a member’s current value,
while a PATCH asking for no change at all writes nothing and leaves it alone.
A definition’s computed member that means the rule it already holds is the
one exception: it changes nothing
(Changing a rule), so a PATCH
carrying only it leaves updated_at where it was. A computed definition’s
updated_at also moves with its computation, with no request of yours: when
one starts (a POST …/recompute of a definition not already computing
included), each time the platform records its computed.progress or
computed.error while it computes, and when it settles ready or failed.
Data types
Section titled “Data types”data_type fixes the JSON shape of every write to an attribute and is
immutable, so a client may cache one decoder per key: a wrong choice is a new
definition, never a PATCH.
text— a string of at most 4096 characters (value_too_longbeyond that). Nothing is trimmed, folded or normalised.number— a JSON number, integer or decimal. A quoted"4"istype_mismatch, not a coerced 4.boolean—trueorfalse.date— a calendar day,YYYY-MM-DD, for when the day itself is the fact (a birthday, an anniversary); see Timestamps.datetime— an instant that must carry its offset; see Timestamps.select— one string out of the definition’soptions.multi_select— a set of strings out of the sameoptions.counter_list— a keyed tally, written with the counter ops and read as an array ofCounterEntry.
Only the last three take options (see
Which options constrain a write);
sending options with any other type is refused type_mismatch.
A select or multi_select must be created with at least one option. Its
options list is the closed set every write is checked against, so a
definition created without one could never hold a value: every write would be
refused unknown_option against an empty set. options is append-only, so
send the values you are sure of and add the rest later. A PATCH sends the
FULL options value, the existing entries plus the new ones rather than a
delta, and may add entries and edit labels: dropping an option value, a group
key or an item key is refused. A counter_list’s options are optional display
groups and constrain nothing.
Who may write a value
Section titled “Who may write a value”Two flags say who may write an attribute’s values, and only one of them concerns this API:
api_writabledecides whether a value may be written over THIS API.falserefuses every write withnot_api_writablehowever well-formed the value, so check it before writing. It defaults totrueon a definition you create; sendfalseto publish an attribute the app maintains and your integration only reads.ui_writabledecides whether staff may edit the attribute in the Nine Tables app, and governs nothing on this API. It is published so an integration can tell an attribute staff maintain from one only it maintains. It defaults totrue, except on acounter_list, which defaults tofalseand refusestruewith400 validation-failed: a counter moves by the counter ops, which no in-app editor offers.
Categories
Section titled “Categories”Every definition is filed under exactly one category, and the Nine Tables app
renders a record’s attributes as one section per category, ordered by the
category’s display_order and, inside it, by each definition’s. That is the
whole job of a category: it grants no permission and namespaces nothing, since
attribute keys are unique per entity across ALL categories, and no validation
or writability follows from it.
POST /definitions requires category, the key of a category that already
exists: there is no default and no auto-create. A key no category holds is
400 validation-failed keyed on category, so create it with
POST /categories first. A live definition may never sit in an archived
category, so naming one, on create or on a PATCH that moves a live
definition, is 400 validation-failed keyed on (root). An archived definition
can be moved into an archived category, and it is then its restore that is
refused. A PATCH that sends archived: false checks the
category it names in the same call, so one request can restore a definition
and lift it out of an archived category.
A tenant holds at most 50 categories of its
own, in one list that customer and booking definitions share, and archived ones
count, since an archived key stays reserved. Past that, POST /categories
answers 400 validation-failed keyed on (root). GET /categories lists them
unpaginated in display_order, ties broken on key, and leaves the archived
ones out unless you pass include_archived=true. A category’s key is
lowercase [a-z0-9_], 1 to 64 characters, and immutable, so choose one that
outlives the label; its label, 1 to 200 characters, is the part you are meant
to change, and can be replaced but not cleared.
The one category is_system marks, system, is provisioned by Nine Tables
and holds the built-in attributes. You cannot create one (POST /categories
always answers is_system: false), its label cannot be changed and it cannot
be archived, though its display_order is yours. It does not count toward the
cap, and nothing refuses a definition of your own inside it.
Archive, never delete
Section titled “Archive, never delete”A definition owns stored values and a category carries attribute history, so
neither is ever deleted. DELETE /definitions/{entity}/{key} and
DELETE /categories/{key} always answer 405, with an Allow header naming the
methods the path does take; authentication and the per-key rate limit run
first, so a 401 or a 429 can come before the 405. Both are archived and restored through their PATCH,
with {"archived": true} stamping archived_at and {"archived": false}
clearing it. Sending the state a record is already in is accepted, and true
on an archived record re-stamps archived_at.
An archived record keeps its key, so a create naming that key answers
409 conflict-key-exists, whose detail says whether the record holding it is
live or archived and, when archived, to restore it rather than recreate it.
Archiving a definition keeps its stored values, which come back when it is
restored. While it is archived it drops out of GET /definitions unless you
pass include_archived=true, its values are left out of every attribute echo,
and a write to it is refused attribute_archived. Two states refuse the
change with a 409:
- archiving while a dynamic segment still references the definition is
conflict-archive-blocked, whoseblockers[]names every reference your key can read with itskind, so you can re-point or archive them without re-deriving the set; thedetailnames the first few. A segment a key limited to restaurants cannot see still blocks the archive but is never named:hidden_blockerscounts those, and is 0 when every blocker is inblockers[]; - restoring while its category is archived is
conflict-category-archived: restore the category first, or send a livecategoryin the samePATCH.
Archiving a category is refused with 409 conflict-archive-blocked while
any non-archived definition is filed under it, blockers[] naming every one
and the detail the first few, so archive or re-categorise those first. An
archived category drops out of GET /categories unless you pass
include_archived=true (GET /categories/{key} still returns it), accepts no
new definition, and blocks the restore of every archived definition still filed
under it.
System attributes are computed
Section titled “System attributes are computed”System attributes, such as last_visit_at, are computed and never writable:
a write to one is refused with not_api_writable, keyed on the attribute,
its detail reading a Nine Tables attribute. Write the bookings they are
computed from instead. The same holds for a computed attribute you define
yourself, refused with the detail computed from bookings;
Computed attributes covers rules, the
catalogue and how computing settles.
A system attribute is a definition with source: "system", a built-in whose
MEANING, its rule included, belongs to Nine Tables, where one you create is
source: "tenant". Built-ins are never created and never deleted: they are a
catalogue, each off and holding no values until the tenant switches it on
with enabled (see
Catalogue), and each key is
reserved either way. Where a built-in APPEARS is still yours, so PATCH
accepts category, display_order, show_on_customer_card and
show_on_booking_panel on one like on any other definition; a switched-off
built-in stays in the system category, where switching it off files it. Its
meaning is locked, and PATCH refuses each change to it with a 400 naming the
member: label, description, options, display_hint, computed,
archived: true, and ui_writable or api_writable set to true, since a
computed value has no direct write to enable. archived: false is always accepted, so a built-in
archived before this rule existed can still be restored.
Which characters a string may contain
Section titled “Which characters a string may contain”Every character except two shapes, and the rule is the same in every string
in every request body — an attribute value, a label, a source_key, a
url, an object key. Emoji, astral characters, newlines, tabs and the
remaining C0 control characters are all fine: nothing is normalised, folded or
stripped, and what you send round-trips byte-identically.
The two exceptions are not policy — they have no representation in the database:
U+0000(NUL), at any position.- An unpaired surrogate — a
\uD800–\uDBFFwith no\uDC00–\uDFFFafter it, or a low surrogate with no high one before it. A correctly paired pair is an ordinary astral character and is accepted.
Either one is 400 validation-failed. Inside values the error is keyed on
the ATTRIBUTE with invalid_value, like every other refused value; anywhere
else it is keyed on the body path with schema_invalid. In POST /batch it
is a per-ITEM problem, so one bad item does not cost the others their writes.
This is worth a sanitiser on your side if you forward free text out of a POS export, where a stray NUL is ordinary and a truncated UTF-16 field produces exactly the unpaired half.