# ECSON: ECMAScript Object Notation
Version: 0.2.0 · Status: draft · License: Apache-2.0
Source: lingodata/ecson@fe27835
## 0. Introduction
ECSON (ECMAScript Object Notation) is a JSON-based format that preserves the JavaScript (ECMAScript) types JSON cannot express, such as [dates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), [big integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), [special numbers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), [sets](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set), [maps](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and [binary data](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). It is part of the **LingoData** family of specifications for data interoperability.
### 0.1 Motivation
JSON has 6 types. JavaScript has dozens. Every attempt to bridge this gap makes a different trade-off:
- **[MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/)**: inline `$`-prefixed types, but closed to extension and tied to BSON.
- **[Meteor EJSON](https://docs.meteor.com/api/ejson.html)**: extensible, but diverges from MongoDB Extended JSON and is incomplete for native JavaScript types.
- **[Superjson](https://github.com/ravionhq/superjson)**: covers native JavaScript types and is extensible, but stores type metadata in a separate envelope.
ECSON combines their strengths:
- inline `$`-prefixed typed values, without a separate envelope;
- full coverage of native JavaScript types, including special numbers (`$number`) and Temporal;
- formal extension through type sets and namespaced application tags;
- exact compatibility with MongoDB Extended JSON through the BSON type set;
- an encoding that does not depend on which types each side knows, so data can pass through any intermediary unchanged;
- output that is always valid JSON, with [JSON5](https://spec.json5.org/) accepted as input.
### 0.2 Conventions
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)) when, and only when, they appear in all capitals, as shown here.
Normative rules are identified by a code (for example [`ESCAPE_SERIALIZE`](#ESCAPE_SERIALIZE)). Notes, examples and rationales are informative.
### 0.3 Terminology
- **Typed value**: a JSON object with a single key starting with a single `$` ([section 1](#1-typed-values)).
- **Tag**: the key of a typed value, such as `$date`.
- **Plain object**: any JSON object that is not a typed value. On the host side, the object that serializes to it: in ECMAScript, an object whose prototype is `Object.prototype` or `null` ([section 5.5](#55-values-outside-the-model)).
- **Type set**: a named group of tags and their serialized forms (sections 3 and 4).
- **Writer** and **reader**: an implementation when serializing and when deserializing, respectively.
## 1. Typed values
ECSON represents values that JSON cannot express natively (dates, big integers, sets, maps, binary data and others) as **typed values**: small JSON objects whose single key names the type.
### 1.1 Output format
**Rule `OUTPUT_JSON`**: MUST
Every ECSON serialization MUST be a valid JSON text as defined in [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259).
### 1.2 Definition
**Rule `TYPED_VALUE`**: MUST
A JSON object with exactly one key, where that key starts with a single `$` (and not with `$$`), MUST be interpreted as a typed value. The key is the **tag** and its value is the serialized form of the type.
**Rule `TYPED_PLAIN_OTHERWISE`**: MUST
Any other JSON object (with zero or more than one key, or whose single key does not start with a single `$`) MUST be interpreted as a plain object, never as a typed value.
> **Tip (non-normative): Example**
>
> | JSON | Interpretation |
> |---|---|
> | `{ "$date": "2024-01-15T00:00:00.000Z" }` | typed value, tag `$date` |
> | `{ "$date": "2024-01-15T00:00:00.000Z", "x": 1 }` | plain object with keys `$date` (escaped on output, see [section 2](#2-escape-convention)) and `x` |
> | `{ "$$date": "text" }` | escaped plain object with key `$date` (see [section 2](#2-escape-convention)) |
> | `{ "date": "2024-01-15" }` | plain object |
### 1.3 Recursion
**Rule `RECURSION`**: MUST
Serialization and deserialization MUST be recursive: typed values MAY contain other typed values and plain objects, and the escape convention ([section 2](#2-escape-convention)) MUST be applied to every plain object at any depth, including plain objects inside typed values.
> **Tip (non-normative): Example**
>
> ```json
> {
> "$map": [
> ["createdAt", { "$date": "2024-01-15T00:00:00.000Z" }],
> ["tags", { "$set": ["a", "b"] }],
> ["meta", { "$$source": "import" }]
> ]
> }
> ```
### 1.4 Key order and canonical form
**Rule `KEY_ORDER_PRESERVE`**: MUST
When serializing a plain object, an implementation MUST emit its keys in the enumeration order of the source object in the host language.
**Rule `CANONICAL_JCS`**: MAY
An implementation MAY offer a canonical serialization mode. In canonical mode, the output MUST follow the JSON Canonicalization Scheme (JCS) defined in [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785), applied after ECSON serialization, and MUST fail for strings, including object keys, with lone UTF-16 surrogates, which RFC 8785 does not allow.
## 2. Escape convention
Plain objects in user data may contain keys starting with `$`. To keep them distinguishable from typed values, ECSON escapes every such key, regardless of which tags are registered.
**Rule `ESCAPE_SERIALIZE`**: MUST
When serializing a plain object, every key starting with `$` MUST be prefixed with an additional `$`.
**Rule `ESCAPE_DESERIALIZE`**: MUST
When deserializing a plain object, every key starting with `$$` MUST have one leading `$` removed.
**Rule `ESCAPE_NOT_TYPED`**: MUST
An object whose single key starts with `$$` MUST be treated as an escaped plain object, never as a typed value.
**Rule `DUPLICATE_KEYS`**: MUST
When a JSON object has the same key more than once, the last one MUST be used, as ECMAScript `JSON.parse` does. This happens before [`TYPED_VALUE`](#TYPED_VALUE) and [`TYPED_PLAIN_OTHERWISE`](#TYPED_PLAIN_OTHERWISE) count the keys, so `{ "$date": 0, "$date": 1 }` is a typed value with the form `1`.
**Rule `ESCAPE_COLLISION`**: MUST
When two keys of a plain object become equal after removing the escape (such as `$$a` and `$a`), deserialization MUST fail.
**Rule `PROTO_OWN_PROPERTY`**: MUST
In hosts where the key `__proto__` sets the prototype of an object, such as ECMAScript, a deserialized key `__proto__` MUST become an own property, never the prototype.
> **Tip (non-normative): Example**
>
> | Value | Serialized |
> |---|---|
> | `{ "$price": 10 }` (plain object) | `{ "$$price": 10 }` |
> | `{ "$$price": 10 }` (plain object) | `{ "$$$price": 10 }` |
> | `{ "$price": 10, "name": "x" }` (plain object) | `{ "$$price": 10, "name": "x" }` |
> | `new Date(0)` (typed value) | `{ "$date": "1970-01-01T00:00:00.000Z" }` |
## 3. Built-in types
Built-in types are the native JavaScript types that every full ECSON implementation supports. They form the **core type set**. Other types are added through extension type sets ([section 4](#4-extension-type-sets)).
Each built-in type has a single serialized form, except where a type explicitly defines alternatives (such as `$date`). There are no global serialization modes.
### 3.1 `$date`
Represents a `Date` object.
**Rule `TYPE_DATE_STRING`**: SHOULD
A valid date SHOULD be serialized as a string in the [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339) format, in UTC, with millisecond precision and the `Z` suffix (`YYYY-MM-DDTHH:mm:ss.sssZ`).
**Rule `TYPE_DATE_EPOCH`**: MAY
A valid date MAY be serialized as an integer number of milliseconds since the [Unix epoch](https://tc39.es/ecma262/#sec-time-values-and-time-range).
**Rule `TYPE_DATE_EPOCH_RANGE`**: MUST
A valid date whose year is outside the range 0000 to 9999 MUST be serialized as an integer number of milliseconds since the Unix epoch, because RFC 3339 cannot represent it.
**Rule `TYPE_DATE_READ`**: MUST
When deserializing `$date`, an implementation MUST accept both the RFC 3339 string form and the integer epoch form.
**Rule `TYPE_DATE_READ_STRICT`**: MUST
When deserializing `$date`, the string form MUST follow the `date-time` production of RFC 3339, section 5.6, with these differences: a leap second (`:60`) MUST fail, and fractions longer than milliseconds MUST be truncated, not rounded. Any UTC offset is accepted, and `t` and `z` are accepted in lowercase. A space instead of `T`, an epoch that is not an integer, and an epoch outside plus or minus 8.64e15 milliseconds (the ECMAScript time range) MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).
**Rule `TYPE_DATE_INVALID`**: MUST
An invalid date (a `Date` whose time value is `NaN`) MUST be serialized as `{ "$date": null }`, and `{ "$date": null }` MUST be deserialized as an invalid date.
> **Tip (non-normative): Example**
>
> ```json
> { "$date": "2024-01-15T00:00:00.000Z" }
> { "$date": 1705276800000 }
> { "$date": 8640000000000000 }
> { "$date": null }
> ```
> The third value is the largest JavaScript date (year 275760), which only the epoch form can represent.
### 3.2 `$bigint`
Represents a `BigInt` value.
**Rule `TYPE_BIGINT`**: MUST
A `BigInt` MUST be serialized as a string of decimal digits, with an optional leading `-`, no leading `+` and no leading zeros (the value zero is `"0"`).
> **Tip (non-normative): Example**
>
> `{ "$bigint": "9007199254740993" }`, `{ "$bigint": "-42" }`, `{ "$bigint": "0" }`
> **Note (non-normative): Rationale**
>
> A string is used instead of a JSON number because JSON parsers commonly convert numbers to IEEE 754 doubles, which lose precision beyond 2^53: only integers in the range [-(2^53)+1, (2^53)-1] are interoperable ([RFC 8259, section 6](https://www.rfc-editor.org/rfc/rfc8259#section-6)), and I-JSON recommends encoding larger integers as JSON strings ([RFC 7493, section 2.2](https://www.rfc-editor.org/rfc/rfc7493#section-2.2)).
### 3.3 `$number`
Represents the IEEE 754 values that JSON cannot express.
**Rule `TYPE_NUMBER_SPECIAL`**: MUST
The number values `NaN`, `Infinity`, `-Infinity` and negative zero MUST be serialized as `{ "$number": "NaN" }`, `{ "$number": "Infinity" }`, `{ "$number": "-Infinity" }` and `{ "$number": "-0" }`, respectively.
**Rule `TYPE_NUMBER_PLAIN`**: MUST
All other number values MUST be serialized as plain JSON numbers, never as `$number`.
**Rule `TYPE_NUMBER_ZERO_READ`**: MUST
When deserializing ECSON or reading the plain JSON form, a JSON or JSON5 number that converts to an IEEE 754 double equal to zero MUST be read as positive zero, including `-0`, `-0.0`, `-1e-400` and, in JSON5, `-0x0`. Negative zero is only read from `{ "$number": "-0" }`.
> **Note (non-normative)**
>
> [`TYPE_NUMBER_ZERO_READ`](#TYPE_NUMBER_ZERO_READ) deliberately differs from ECMAScript `JSON.parse`, which returns negative zero for `-0` and for negative numbers that round to zero, such as `-1e-400`. ECSON writers never emit these numbers: negative zero is written as `{ "$number": "-0" }` ([`TYPE_NUMBER_SPECIAL`](#TYPE_NUMBER_SPECIAL)).
> **Note (non-normative)**
>
> Scientific notation (for example `1e300` or `1.5E-7`) is already part of the JSON number grammar (RFC 8259, section 6) and needs no typed value.
> **Note (non-normative): Rationale**
>
> `JSON.stringify` turns `NaN` and `Infinity` into `null` and `-0` into `0`, silently changing the data. MongoDB Extended JSON solves the same problem with `$numberDouble`.
### 3.4 `$undefined`
Represents `undefined`, including inside objects and arrays, where `JSON.stringify` would drop the property or replace the element with `null`.
**Rule `TYPE_UNDEFINED`**: MUST
`undefined` MUST be serialized as `{ "$undefined": true }`.
> **Tip (non-normative): Example**
>
> `{ "a": undefined, "list": [1, undefined] }` serializes as `{ "a": { "$undefined": true }, "list": [1, { "$undefined": true }] }`.
### 3.5 `$regexp`
Represents a `RegExp` object.
**Rule `TYPE_REGEXP`**: MUST
A `RegExp` MUST be serialized as an object with a `source` string, using the ECMAScript regular expression syntax, and a `flags` string containing only the characters `d`, `g`, `i`, `m`, `s`, `u`, `v` and `y`.
**Rule `TYPE_REGEXP_VALID`**: MUST
When deserializing, a `$regexp` value whose `flags` repeat a character, or whose `source` and `flags` are rejected by ECMAScript (for example both `u` and `v`, or a `source` with an unbalanced `(`), MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)), also under [`TYPE_REGEXP_OPAQUE`](#TYPE_REGEXP_OPAQUE).
**Rule `TYPE_REGEXP_OPAQUE`**: MAY
An implementation whose host language cannot represent ECMAScript regular expressions MAY keep `$regexp` values as opaque values, without compiling `source`. It still validates `source` and `flags` against the ECMAScript syntax ([`TYPE_REGEXP_VALID`](#TYPE_REGEXP_VALID)), so that every reader accepts the same values.
> **Tip (non-normative): Example**
>
> `{ "$regexp": { "source": "^foo", "flags": "i" } }`
### 3.6 `$symbol`
Represents a `Symbol`.
**Rule `TYPE_SYMBOL_UNIQUE`**: MUST
A symbol that is not in the global symbol registry MUST be serialized as a string with its description (`""` when it has none), and MUST be deserialized as a new symbol with that description.
**Rule `TYPE_SYMBOL_REGISTERED`**: MUST
A symbol in the global symbol registry MUST be serialized as an object `{ "for": key }`, where `key` is its registry key, and MUST be deserialized as the registered symbol for that key (`Symbol.for(key)`).
**Rule `TYPE_SYMBOL_WELL_KNOWN`**: MUST
Serializing a well-known symbol (such as `Symbol.iterator`) MUST fail.
> **Tip (non-normative): Example**
>
> | Value | Serialized |
> |---|---|
> | `Symbol("id")` | `{ "$symbol": "id" }` |
> | `Symbol()` | `{ "$symbol": "" }` |
> | `Symbol.for("app.key")` | `{ "$symbol": { "for": "app.key" } }` |
### 3.7 `$set`
Represents a `Set`.
**Rule `TYPE_SET`**: MUST
A `Set` MUST be serialized as an array of its values, serialized recursively, in iteration order. Deserialization MUST preserve that order.
> **Tip (non-normative): Example**
>
> `{ "$set": ["a", "b", { "$date": "2024-01-15T00:00:00.000Z" }] }`
### 3.8 `$map`
Represents a `Map`.
**Rule `TYPE_MAP`**: MUST
A `Map` MUST be serialized as an array of `[key, value]` pairs, both serialized recursively, in iteration order. Keys MAY be any ECSON value. Deserialization MUST preserve that order.
**Rule `TYPE_SET_MAP_DUPLICATES`**: MUST
When deserializing, a `$set` with two equal values, or a `$map` with two equal keys, MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)). Equality is ECMAScript `SameValueZero` on the deserialized values: primitives compare by value (`$bigint`, `$undefined`, numbers, where `NaN` equals `NaN` and `-0` equals `0`, strings, booleans, `null`, and registered symbols with the same key), while objects (plain objects, arrays and every other typed value, such as `$date`, `$regexp`, `$set` and Temporal types) and unique symbols are never equal to each other.
> **Tip (non-normative): Example**
>
> `{ "$map": [["key", 42], [{ "$date": "2024-01-15T00:00:00.000Z" }, "a date key"], [{ "id": 1 }, "an object key"]] }`
>
> `{ "$set": [{ "$date": 0 }, { "$date": 0 }] }` is valid: the two dates are distinct objects. `{ "$set": [1, 1] }`, `{ "$set": [0, { "$number": "-0" }] }` and `{ "$set": [{ "$bigint": "1" }, { "$bigint": "1" }] }` fail.
> **Note (non-normative)**
>
> An implementation that keeps Temporal values as opaque strings ([`TYPE_TEMPORAL_OPAQUE`](#TYPE_TEMPORAL_OPAQUE)) still treats them as distinct objects, so that its result does not depend on the host.
### 3.9 `$bytes`
Represents binary data: `ArrayBuffer`, Node.js `Buffer` and the typed array family.
**Rule `TYPE_BYTES`**: MUST
Binary data MUST be serialized as an object with a `type` string and a `data` string containing the bytes in Base64, as defined in [RFC 4648, section 4](https://www.rfc-editor.org/rfc/rfc4648#section-4), with padding.
**Rule `TYPE_BYTES_VALID`**: MUST
A `$bytes` value whose `data` is not Base64 with padding (without spaces, and with zero padding bits), or whose number of bytes is not a multiple of the element size of its `type`, MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).
**Rule `TYPE_BYTES_TYPES`**: MUST
`type` MUST be one of `ArrayBuffer`, `Buffer`, `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `Float16Array`, `Float32Array`, `Float64Array`, `BigInt64Array` or `BigUint64Array`.
**Rule `TYPE_BYTES_LITTLE_ENDIAN`**: MUST
Typed arrays with elements larger than one byte MUST be serialized with each element in little-endian byte order, regardless of the host platform.
**Rule `TYPE_BYTES_FALLBACK`**: MAY
An implementation that cannot represent the given `type` MAY deserialize the value as a plain byte sequence (for example, `Buffer` as `Uint8Array` outside Node.js).
> **Tip (non-normative): Example**
>
> ```json
> { "$bytes": { "type": "Uint8Array", "data": "c3VyZS4=" } }
> { "$bytes": { "type": "Float32Array", "data": "AACAPw==" } }
> ```
> The second value is `new Float32Array([1])`, whose bytes are `00 00 80 3F` in little-endian order.
> **Note (non-normative): Rationale**
>
> Typed arrays use the byte order of the host platform. Without a fixed byte order, the same `Float32Array` would serialize to different bytes on different machines.
>
> `$binary` is intentionally not used as a tag here, to avoid collision with the MongoDB Extended JSON `$binary`, which carries BSON subtype semantics. BSON binary data is covered by the BSON type set ([section 4](#4-extension-type-sets)).
### 3.10 Temporal types
Represent the [ECMAScript Temporal](https://tc39.es/proposal-temporal/) types, part of ECMAScript since ES2026.
**Rule `TYPE_TEMPORAL`**: MUST
Temporal values MUST be serialized as strings, using the tag for their type from the table below and the string format that ECMAScript Temporal's `toString()` produces with default options, which follows [RFC 9557](https://www.rfc-editor.org/rfc/rfc9557).
| Temporal type | Tag | Example |
|---|---|---|
| `Temporal.Instant` | `$instant` | `{ "$instant": "2024-01-15T00:00:00Z" }` |
| `Temporal.ZonedDateTime` | `$zoneddatetime` | `{ "$zoneddatetime": "2024-01-15T12:30:00-03:00[America/Sao_Paulo]" }` |
| `Temporal.PlainDateTime` | `$plaindatetime` | `{ "$plaindatetime": "2024-01-15T12:30:00" }` |
| `Temporal.PlainDate` | `$plaindate` | `{ "$plaindate": "2024-01-15" }` |
| `Temporal.PlainTime` | `$plaintime` | `{ "$plaintime": "12:30:00" }` |
| `Temporal.PlainYearMonth` | `$plainyearmonth` | `{ "$plainyearmonth": "2024-01" }` |
| `Temporal.PlainMonthDay` | `$plainmonthday` | `{ "$plainmonthday": "01-15" }` |
| `Temporal.Duration` | `$duration` | `{ "$duration": "P1Y2M3DT4H5M6S" }` |
> **Tip (non-normative): Example: canonical strings**
>
> | Tag | Accepted | Rejected |
> |---|---|---|
> | `$instant` | `2024-01-15T00:00:00Z`, `2024-01-15T00:00:00.5Z` | `2024-01-15T00:00:00.000Z`, `2024-01-15T00:00:00.500Z`, `2024-01-15T00:00:00+00:00` |
> | `$plaindate` | `2024-01-15`, `2024-01-15[u-ca=hebrew]` | `20240115`, `2024-01-15[u-ca=iso8601]` |
> | `$plainyearmonth` | `2024-01` | `2024-01-01`, `2024-01[u-ca=iso8601]` |
> | `$duration` | `PT0S`, `PT1.5S` | `P0D`, `PT1.50S` |
**Rule `TYPE_TEMPORAL_OPAQUE`**: MAY
An implementation whose host language has no equivalent for a Temporal type MAY keep its value as an opaque string.
**Rule `TYPE_TEMPORAL_SYNTAX`**: MUST
When deserializing, a Temporal string MUST be a string that `toString()` with default options can produce for its type, whether the implementation has native Temporal or keeps opaque strings. Other strings that `Temporal.*.from()` accepts, such as `20240115` for a `$plaindate` or `2024-01-15T00:00:00.000Z` for an `$instant`, MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).
**Rule `TYPE_TEMPORAL_ISO_YEAR_MONTH_DAY`**: MUST
`$plainyearmonth` and `$plainmonthday` values MUST use the ISO 8601 calendar. Serialization MUST fail for values in other calendars, and deserialization MUST fail for strings with any calendar annotation, including `[u-ca=iso8601]`, which `toString()` never writes.
> **Note (non-normative): Rationale**
>
> For these two types in a non-ISO calendar, `toString()` writes a reference ISO day (`$plainyearmonth`, for example `2024-01-11[u-ca=hebrew]`) or a reference ISO year (`$plainmonthday`, for example `1972-09-22[u-ca=chinese]`) computed by the calendar, which an implementation that keeps Temporal values as opaque strings cannot compute. Restricting them to the ISO calendar keeps the round trip identical in every implementation. Other Temporal types keep any calendar.
> **Note (non-normative)**
>
> Non-ISO calendars appear as an annotation, for example `2024-01-15[u-ca=hebrew]` (except for `$plainyearmonth` and `$plainmonthday`, see [`TYPE_TEMPORAL_ISO_YEAR_MONTH_DAY`](#TYPE_TEMPORAL_ISO_YEAR_MONTH_DAY)). Values keep the full precision of Temporal (up to nanoseconds).
## 4. Extension type sets
A **type set** is a named group of tags with their serialized forms. The core type set ([section 3](#3-built-in-types)) contains the native JavaScript types. **Official extension type sets**, defined in this section, cover types from other ecosystems and native types that are not in the core type set, such as errors. Implementations decide how to package each set.
**Rule `TYPESET_OPTIONAL`**: MAY
An implementation MAY support any official extension type set, in whole. Partial support of a set is not compliant with that set.
### 4.1 BSON type set
Covers the BSON types used by MongoDB that are not native JavaScript types. Its forms are identical to [MongoDB Extended JSON v2](https://github.com/mongodb/specifications/blob/master/source/extended-json/extended-json.md), so that ECSON values can be exchanged with MongoDB tools.
**Rule `BSON_FORMS`**: MUST
The BSON type set MUST use the tags and forms in the table below, which are identical to the [canonical format](https://github.com/mongodb/specifications/blob/master/source/extended-json/extended-json.md) of MongoDB Extended JSON v2.
| BSON type | Form |
|---|---|
| ObjectId | `{ "$oid": "507f1f77bcf86cd799439011" }`: 24 hexadecimal characters, big-endian bytes |
| Binary | `{ "$binary": { "base64": "c3VyZS4=", "subType": "00" } }`: Base64 with padding, subtype as a 1 or 2 digit hexadecimal string |
| Decimal128 | `{ "$numberDecimal": "9.99" }` |
| Timestamp | `{ "$timestamp": { "t": 1678886400, "i": 1 } }`: non-negative integers |
| MinKey | `{ "$minKey": 1 }` |
| MaxKey | `{ "$maxKey": 1 }` |
**Rule `BSON_HEX_CASE`**: MUST
Writers MUST emit hexadecimal strings (`$oid`, `subType`) in lowercase, and readers MUST accept them in any case.
**Rule `BSON_DECIMAL_EXACT`**: MUST
When deserializing, a `$numberDecimal` string MUST follow the string syntax of the [MongoDB Decimal128 specification](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.md) (`e` or `E` for the exponent; `Inf`, `Infinity` and `NaN` in any case) and MUST represent a Decimal128 exactly: clamping and rounding that do not change the value are allowed, and a string that needs inexact rounding, overflows or underflows MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).
**Rule `BSON_DECIMAL_CANONICAL`**: MUST
Writers MUST emit the canonical Decimal128 string of the MongoDB Decimal128 specification (for example, `1e3` is written as `1E+3`).
**Rule `BSON_READ_CANONICAL_DATE`**: MAY
A reader that supports the BSON type set MAY also accept the MongoDB canonical date form `{ "$date": { "$numberLong": "" } }` when deserializing. Writers MUST NOT emit it: dates are always written in the core `$date` form ([section 3.1](#31-date)).
> **Note (non-normative)**
>
> Other MongoDB Extended JSON tags, such as `$numberLong`, `$numberInt` and `$numberDouble`, are not part of the BSON type set: in ECSON they are covered by plain JSON numbers, `$bigint` and `$number`. A reader without support for them preserves them as unknown tags ([section 7](#7-unknown-tags)).
### 4.2 References type set
Covers references from one value to another resource: links to anything addressable by a URI, and references to resources in the same data source.
**Rule `REF_TAG`**: MUST
The References type set MUST use the tag `$rel`, whose value is one of the forms in the table below, or `null` for an empty reference: a single reference that points to nothing.
| Form | Value | Example |
|---|---|---|
| URI | a string with a URI ([RFC 3986, section 3](https://www.rfc-editor.org/rfc/rfc3986#section-3)), either a URL or a URN, with an optional fragment | `{ "$rel": "urn:isbn:9780262033848" }` |
| Link header | a string with the value of an HTTP `Link` header field ([RFC 8288, section 3](https://www.rfc-editor.org/rfc/rfc8288#section-3)), with one or more links | `{ "$rel": "; rel=\"author\", ; rel=\"editor\"" }` |
| Link object | an object with an `href` URI string and, optionally, `rel` and the target attributes of [RFC 9264, section 4.2](https://www.rfc-editor.org/rfc/rfc9264#section-4.2) (`type`, `title`, `hreflang` and others) | `{ "$rel": { "href": "https://api.example.com/users/42", "rel": "author", "type": "application/vnd.ecson+json", "title": "Ana", "hreflang": ["pt-BR"] } }` |
| Collection object | an object with a `collection` name and either an `id` or an `ids` array | `{ "$rel": { "collection": "tags", "ids": ["promo", "delivery"] } }` |
| Array | an array of URI strings, link objects and collection objects, for several references | `{ "$rel": ["https://example.com/a", { "href": "https://example.com/b", "rel": "related" }, { "collection": "products", "id": "p1" }] }` |
**Rule `REF_STRING_FORMS`**: MUST
A string value starting with `<` MUST be interpreted as a Link header value; any other string MUST be interpreted as a URI ([RFC 3986, section 3](https://www.rfc-editor.org/rfc/rfc3986#section-3)). A string that is not a URI, such as a relative reference (`/users/42`) or the empty string, makes the value malformed.
**Rule `REF_OBJECT_FORMS`**: MUST
An object value with an `href` member MUST be interpreted as a link object, and an object value with a `collection` member as a collection object. An object with both, or with neither, is malformed.
**Rule `REF_ARRAY`**: MUST
An array value MUST contain only URI strings, link objects and collection objects, in any combination; it MUST NOT contain Link header strings, which already represent several links, nor nested arrays.
**Rule `REF_EMPTY`**: MUST
An empty array value and a collection object with an empty `ids` array MUST be accepted as zero references: a list that has no references, which is not the same as `null`, the empty reference of [`REF_TAG`](#REF_TAG). With an empty `ids`, `data`, when present, is an empty array.
**Rule `REF_COLLECTION_ID`**: MUST
The `id` of a collection object, and each element of `ids`, MUST be an ECSON value other than `null`, `$undefined`, a boolean, an array or a plain object, such as a string, a number, a `$bigint` or an `$oid`. Other values make the collection object malformed.
**Rule `REF_LINK_ATTRIBUTES`**: MUST
The members of a link object MUST have the JSON types of RFC 9264, section 4.2: `href`, `rel`, `title`, `type` and `media` are strings; attributes whose name ends with `*` are arrays of objects with a `value` string, an optional `language` string and no other members; `hreflang` and the other attributes, including extension attributes, are arrays of strings. Other types make the link object malformed.
**Rule `REF_COLLECTION_DATA`**: MAY
A collection object MAY include a `data` member with a snapshot of the referenced data: an object (or `null`, when not found) for `id`, or an array in the same order as `ids`. The `data` member is not part of the reference: writers that store references MUST ignore it.
> **Tip (non-normative): Example: several references**
>
> | Case | Value |
> |---|---|
> | several Resources of one Collection | `{ "$rel": { "collection": "tags", "ids": ["promo", "delivery"] } }` |
> | several links in one string | `{ "$rel": "; rel=\"author\", ; rel=\"editor\"" }` |
> | several links as objects | `{ "$rel": [{ "href": "https://example.com/u/42", "rel": "author" }, { "href": "https://example.com/u/7", "rel": "editor" }] }` |
> | Resources of different Collections | `{ "$rel": [{ "collection": "products", "id": "p1" }, { "collection": "services", "id": "s9" }] }` |
**Rule `REF_COLLECTION_SAME_SOURCE`**: MUST
A collection object MUST refer to Resources stored in the same data source as the value that contains it. References to anything else MUST use a URI, Link header or link object form.
> **Note (non-normative)**
>
> The link object follows the JSON link target object of RFC 9264, with one addition and two restrictions. The addition is an optional `rel` member, a registered relation type name or a URI, because a single reference has no enclosing link context object to carry the relation type. The restrictions: `href` is a URI, not a relative reference (RFC 9264 only says it SHOULD NOT be one), because a value has no base URI to resolve it against; and the objects of attributes ending with `*` have no members other than `value` and `language`.
> **Note (non-normative): Rationale**
>
> The URI and Link header forms reuse existing standards for links, including the IANA link relations registry, so references to external resources need no new vocabulary. The collection object covers the common case of references inside the same data source, which a Provider can resolve without network access.
### 4.3 Error type set
Covers ECMAScript error objects.
**Rule `ERROR_FORM`**: MUST
An error MUST be serialized under the tag `$error` as an object with a `name` string and a `message` string, and MAY include `cause` (any ECSON value), `errors` (an array of ECSON values, for `AggregateError` and for any other error whose own `errors` property is an array), `stack` (a string) and `props` (an object with the own enumerable properties of the error other than `name`, `message`, `cause`, `errors` and `stack`, such as `code`, serialized as ECSON). Other members MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).
**Rule `ERROR_NATIVE`**: MUST
When deserializing, an implementation MUST create the native error type named by `name` when it is one of `Error`, `EvalError`, `RangeError`, `ReferenceError`, `SyntaxError`, `TypeError`, `URIError` or `AggregateError`, and MUST otherwise create an `Error` whose `name` is the received `name`.
**Rule `ERROR_ERRORS_READ`**: MUST
When deserializing, an error whose `name` is `AggregateError` and that has no `errors` MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)). An `errors` in an error with another `name` MUST be restored as an own property `errors` of the created error.
**Rule `ERROR_STACK_READ`**: MUST
When deserializing, a received `stack` MUST replace the `stack` of the created error.
**Rule `ERROR_PROPS`**: MUST
When deserializing, the members of `props` MUST be restored as own properties of the error.
**Rule `ERROR_PROPS_KEYS`**: MUST
A `props` with the key `name`, `message`, `cause`, `errors` or `stack` MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)). An empty `props` is valid.
> **Note (non-normative)**
>
> Restoring one of these keys from `props` would overwrite a member of the error.
**Rule `ERROR_STACK_OPT_IN`**: SHOULD NOT
Implementations SHOULD NOT serialize `stack` unless the application asks for it.
> **Tip (non-normative): Example**
>
> `{ "$error": { "name": "TypeError", "message": "amount must be a string", "cause": { "$error": { "name": "Error", "message": "invalid input" } } } }`
>
> `{ "$error": { "name": "Error", "message": "file not found", "props": { "code": "ENOENT", "path": "/tmp/a.txt" } } }`
>
> `{ "$error": { "name": "AggregateError", "message": "2 uploads failed", "errors": [{ "$error": { "name": "Error", "message": "timeout" } }, { "$error": { "name": "RangeError", "message": "file too large" } }] } }`
> **Note (non-normative)**
>
> A missing `cause` and a `cause` of `{ "$undefined": true }` are different ([`TYPE_UNDEFINED`](#TYPE_UNDEFINED)): the first is an error without a `cause` property, the second an error whose own `cause` property is `undefined`, as `new Error("x", { cause: undefined })` creates.
> **Caution (non-normative): Security**
>
> Stack traces expose file paths and internal structure of the sender. Sending them should be opt-in.
## 5. Type definitions and processing
This section defines the abstract model that every implementation follows. It does not define a programming interface: function names and signatures are left to each implementation.
ECSON is a serialization for transport. The types defined by ECSON form a model of values; ECSON serializes them without loss, and the plain JSON form ([section 5.3](#53-plain-json-form)) serializes them with loss, for receivers that do not use ECSON. Applications and data stores keep values in their own native types, not as ECSON.
Sections 5.4 and 5.5 name ECMAScript mechanisms: the `toJSON` method, the static `fromJSON` method and the behavior of `JSON.stringify`. Implementations in other host languages use the equivalent mechanism of their language and state which one ([`CONFORMANCE_DECLARE`](#CONFORMANCE_DECLARE)). The serialized forms are the same in every language, such as `$class` with `ctor` and `value`.
### 5.1 Type definitions
A **type definition** describes one tag. It consists of:
- the **tag**, a string starting with a single `$`;
- the **serialized form**: the JSON value that represents an instance of the type;
- the **validation** of the serialized form, which states when a value under that tag is malformed;
- the **plain JSON form**: the JSON value used when the value is sent without ECSON ([section 5.3](#53-plain-json-form)).
Each type in sections 3 and 4 is a type definition. The `$class` form ([section 5.4](#54-application-classes)) is also a type definition, defined by this section and outside any type set. Applications MAY add their own type definitions, following the namespace rules in [section 6](#6-tag-ownership-and-namespaces).
**Rule `TYPEDEF_VALIDATE`**: MUST
When deserializing a typed value whose tag is known, an implementation MUST fail if the serialized form does not match the type definition.
> **Tip (non-normative): Example**
>
> `{ "$bigint": "12.5" }` is malformed ([`TYPE_BIGINT`](#TYPE_BIGINT) allows only decimal digits) and deserialization fails. `{ "$acme.unknown": 1 }`, with an unknown tag, does not fail and is preserved ([section 7](#7-unknown-tags)).
### 5.2 Processing limits
**Rule `CIRCULAR_FAIL`**: MUST
Serialization MUST fail when the value contains a circular reference, including one reached through the result of a `toJSON` method.
**Rule `DEPTH_LIMIT`**: MAY
An implementation MAY limit the nesting depth it serializes or deserializes. The depth is counted in the JSON text of the ECSON form, where each array and object, including the root, is one level, so `{ "$set": [] }` has two levels. When the limit is exceeded, the implementation MUST fail, rather than truncate.
**Rule `TAG_ALLOWLIST`**: MAY
An implementation MAY let users restrict processing to a list of tags. Typed values with tags outside the list MUST then be handled as unknown tags ([section 7](#7-unknown-tags)) when deserializing, and serializing a native value whose tag would be outside the list MUST fail. Unknown typed values preserved under [`UNKNOWN_PRESERVE`](#UNKNOWN_PRESERVE) are written back unchanged.
### 5.3 Plain JSON form
The plain JSON form lets a value be sent to a receiver that reads only JSON. It keeps the data that JSON can carry and drops the type information.
**Rule `PLAIN_FORM_DEFAULT`**: MUST
The plain JSON form of a typed value MUST be its serialized form, itself in plain JSON form, without the tag, except for the types in the table below.
| Tag | Plain JSON form |
|---|---|
| `$date` | the RFC 3339 string of [`TYPE_DATE_STRING`](#TYPE_DATE_STRING); for years outside 0000 to 9999, the expanded year string of ECMAScript `Date.prototype.toISOString` (for example `+275760-09-13T00:00:00.000Z`); `null` for an invalid date |
| `$bigint` | a JSON number |
| `$number` | `null`, and `0` for negative zero |
| `$undefined` | omitted as a member of an object; `null` elsewhere, including at the root and inside `$set` and `$map` |
| `$class` | for a registered class, the plain JSON form of `value`; for an unregistered identifier, the raw object with `ctor` and `value`, as for any unknown tag ([`CLASS_REGISTERED_ONLY`](#CLASS_REGISTERED_ONLY), [`PLAIN_FORM_UNKNOWN`](#PLAIN_FORM_UNKNOWN)) |
| `$regexp` | the string `/source/flags` |
| `$symbol` | the description string, or the registry key for a registered symbol |
| `$bytes` | the Base64 string of `data` |
| `$binary` (BSON) | the Base64 string of `base64` |
| `$minKey`, `$maxKey` (BSON) | `null` |
> **Tip (non-normative): Example**
>
> | ECSON | Plain JSON form |
> |---|---|
> | `{ "$date": "2026-11-06T12:00:00.000Z" }` | `"2026-11-06T12:00:00.000Z"` |
> | `{ "$set": [1, 2] }` | `[1, 2]` |
> | `{ "$map": [[{ "$date": "2026-11-06T12:00:00.000Z" }, "a"]] }` | `[["2026-11-06T12:00:00.000Z", "a"]]` |
> | `{ "$bigint": "42" }` | `42` |
> | `{ "$acme.money": { "amount": "9.90", "currency": "BRL" } }` | `{ "amount": "9.90", "currency": "BRL" }` |
> | `{ "$error": { "name": "TypeError", "message": "bad amount", "props": { "code": "E1" } } }` | `{ "name": "TypeError", "message": "bad amount", "props": { "code": "E1" } }` |
**Rule `PLAIN_FORM_CUSTOM`**: MAY
A type definition outside this specification MAY declare another plain JSON form.
**Rule `PLAIN_FORM_UNKNOWN`**: MUST
The plain JSON form of an unknown tag ([section 7](#7-unknown-tags)) MUST be its raw serialized value, without the tag: keys inside it are not unescaped and typed values inside it are not converted ([`UNKNOWN_RAW`](#UNKNOWN_RAW)).
**Rule `PLAIN_FORM_NO_ESCAPE`**: MUST
In the plain JSON form, keys of plain objects MUST NOT be escaped ([section 2](#2-escape-convention)): a key `$ref` is written as `$ref`.
**Rule `PLAIN_FORM_READ`**: MUST
A JSON text received in the plain JSON form MUST be read as plain JSON: keys starting with `$` are plain keys, and no object is interpreted as a typed value.
> **Note (non-normative)**
>
> Reading the plain JSON form does not recover the types: a date arrives as a string. Recovering them needs information outside ECSON, such as a schema. JavaScript parsers round integers above 2^53 − 1, so a large `$bigint` can lose precision in its plain JSON form, although JSON allows integers of any size ([RFC 8259, section 6](https://www.rfc-editor.org/rfc/rfc8259#section-6)). Senders that must keep every value exact use ECSON.
### 5.4 Application classes
Applications that own a type define it with a namespaced tag (sections 5.1 and 6), such as `$acme.money`, and register it in the implementation. For instances of application classes that have no registered tag, ECSON defines a generic form based on `toJSON` and `fromJSON`.
**Rule `CLASS_FORM`**: MUST
An instance of a registered class MUST be serialized under the tag `$class` as an object with two members: `ctor`, the class identifier, and `value`, the result of `toJSON()` serialized as ECSON. A registered class is a class without a registered tag, with a `toJSON` method and a static `fromJSON` method, that the application registered under a class identifier.
**Rule `CLASS_IDENTIFIER`**: MUST
The class identifier MUST be declared by the application when it registers the class, and MUST NOT be taken from the runtime name of the class. It MUST follow [`TAG_GRAMMAR`](#TAG_GRAMMAR) without the leading `$`: a namespace, a `.` and a class name (for example `acme.Money`).
**Rule `CLASS_EXACT`**: MUST
The `$class` form MUST apply only to instances of the registered class itself, not of its subclasses. An instance of a subclass that is not registered itself goes on to the next steps of [`SERIALIZE_ORDER`](#SERIALIZE_ORDER): the type sets, when it is an instance of one of their types, or else the `toJSON` step, through the inherited `toJSON`. Either way it loses its class.
**Rule `CLASS_READ_FORM`**: MUST
When deserializing, a `$class` value whose `ctor` does not follow the grammar of [`CLASS_IDENTIFIER`](#CLASS_IDENTIFIER), without `value`, or with members other than `ctor` and `value`, MUST fail ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)).
> **Note (non-normative): Rationale**
>
> Minifiers rename classes: in a minified build, `Money.name` may become `"o"`, so data written by one build could not be read by another. Namespaces avoid collisions between libraries that use the same class name.
**Rule `CLASS_REGISTERED_ONLY`**: MUST
When deserializing a `$class` value, an implementation MUST call the static `fromJSON` method with the deserialized `value` only for classes registered by the application under that identifier, and MUST NOT look up classes by name in any other way. A `$class` value with an unregistered identifier MUST be handled as an unknown tag ([section 7](#7-unknown-tags)).
> **Caution (non-normative): Security**
>
> Creating instances from a class name received in the data would let a sender run code of any class the receiver can reach. Only registered classes are instantiated.
> **Tip (non-normative): Example**
>
> An application registers the class `Money` as `acme.Money`. An instance whose `toJSON()` returns `{ amount: "9.90", currency: "BRL" }` is written as `{ "$class": { "ctor": "acme.Money", "value": { "amount": "9.90", "currency": "BRL" } } }`, and that value is read as `Money.fromJSON({ amount: "9.90", currency: "BRL" })`. A reader that did not register `acme.Money` keeps the value as an unknown tag ([`CLASS_REGISTERED_ONLY`](#CLASS_REGISTERED_ONLY)).
### 5.5 Values outside the model
A value that is not JSON, not a known type and not a plain object (an object whose prototype is `Object.prototype` or `null`) is outside the model: for example a function, a `WeakMap` or an instance of an application class that has no registered tag and is not a registered class ([section 5.4](#54-application-classes)). [`SERIALIZE_ORDER`](#SERIALIZE_ORDER) decides how each one is written.
**Rule `SERIALIZE_ORDER`**: MUST
Serialization MUST try, in order: (1) the registered application types; (2) the `$class` form ([section 5.4](#54-application-classes)); (3) the core type set and the extension type sets the implementation supports; (4) for a value that does not meet [`CLASS_FORM`](#CLASS_FORM), the result of its `toJSON` method, except for functions ([`FUNCTION_NOT_SERIALIZED`](#FUNCTION_NOT_SERIALIZED)); and (5), for any other value, the behavior of ECMAScript `JSON.stringify` ([`OUT_OF_MODEL_JSON`](#OUT_OF_MODEL_JSON)).
**Rule `CLASS_OVER_ERROR`**: MUST
An instance of a registered class ([`CLASS_FORM`](#CLASS_FORM)) MUST be serialized in the `$class` form, even when it is also an array or an instance of a type of the core type set or of an extension type set, such as a subclass of `Array`, `Map`, `Date` or `Error`. An instance of such a type that is not a registered class keeps the form of its type set.
**Rule `SERIALIZE_ORDER_SCOPE`**: MUST
The `toJSON` step MUST NOT apply to plain objects and arrays, which are in the model.
**Rule `TOJSON_CALL`**: MUST
Every call to `toJSON`, in the `$class` form and in the `toJSON` step, MUST pass the key as `JSON.stringify` does: the member name, the array index as a string, and the empty string at the root. Inside `$set` and `$map`, which `JSON.stringify` does not serialize, the key MUST be the empty string.
**Rule `TOJSON_RESULT`**: MUST
The result of `toJSON` MUST be serialized as ECSON, so that a `Date` inside it becomes `$date`, but it MUST NOT go through the `$class` and `toJSON` steps again: its own `toJSON` is never called. Its members go through the whole order.
**Rule `OUT_OF_MODEL_JSON`**: MUST
Values that reach the last step of [`SERIALIZE_ORDER`](#SERIALIZE_ORDER) MUST be serialized as `JSON.stringify` does. A `Number`, `String`, `Boolean` or `BigInt` object is unboxed, and the primitive is serialized as ECSON (so `Object(1n)` becomes `$bigint`). Any other object becomes a plain object with its own enumerable string-keyed properties, whose values are serialized as ECSON, so that a `Date` inside it becomes `$date`. A function, or a symbol or `undefined` in an implementation that does not support `$symbol` or `$undefined`, is omitted as a member of an object and becomes `null` elsewhere, including at the root and inside `$set` and `$map`.
**Rule `OUT_OF_MODEL_REPORT`**: MAY
An implementation MAY report the values handled by [`OUT_OF_MODEL_JSON`](#OUT_OF_MODEL_JSON), with their path and reason, without failing.
**Rule `FUNCTION_NOT_SERIALIZED`**: MUST NOT
The source code of a function MUST NOT be serialized, and a `toJSON` method of a function MUST NOT be called.
**Rule `CODE_NOT_EVALUATED`**: MUST NOT
When deserializing, an implementation MUST NOT evaluate code received in the data.
> **Note (non-normative): Rationale**
>
> Serializing a function means writing its source code and evaluating it on the receiving side, which is remote code execution, and it would still lose the variables the function captures. `WeakMap`, `WeakSet`, `WeakRef` and `Promise` cannot be inspected, so there is nothing to serialize.
## 6. Tag ownership and namespaces
Every tag must mean the same thing to every reader. This section defines who may define a tag.
**Rule `TAG_RESERVED`**: MUST NOT
A tag defined by the core type set, by an official extension type set or by [section 5](#5-type-definitions-and-processing) (`$class`) MUST NOT be redefined, overridden or given another form by any other type set or application.
**Rule `TAG_UNNAMESPACED_RESERVED`**: MUST NOT
Applications MUST NOT define tags without a `.` (such as `$money`): those tags are reserved for this specification.
**Rule `TAG_NAMESPACE`**: SHOULD
Application-defined tags SHOULD use a namespace followed by `.` and the type name, such as `$acme.money`, where the namespace identifies the application or organization.
**Rule `TAG_GRAMMAR`**: MUST
A tag that contains a `.` MUST be `$` followed by two or more non-empty segments separated by `.`, and its first segment MUST NOT start with `$` (a key starting with `$$` is never a tag, [`ESCAPE_NOT_TYPED`](#ESCAPE_NOT_TYPED)). Segments MUST NOT contain white space (Unicode property `White_Space`), control or invisible format characters (general categories `Cc` and `Cf`, such as U+200B and U+202E) or lone surrogates; any other character, including non-ASCII letters, is allowed. The last segment is the type name, and the segments before it form the **namespace**: in `$acme.billing.money`, the namespace is `acme.billing`. Tags such as `$acme.`, `$.money`, `$a..b` and `$acme. money` are malformed.
**Rule `TAG_MALFORMED_READ`**: MUST
When deserializing, a typed value whose tag is malformed MUST be handled as an unknown tag ([section 7](#7-unknown-tags)).
**Rule `TAG_DOLLAR_ONLY`**: MUST
The tag `$`, made only of `$`, is not defined by this specification and MUST NOT be defined by applications ([`TAG_UNNAMESPACED_RESERVED`](#TAG_UNNAMESPACED_RESERVED)). When deserializing, it MUST be handled as an unknown tag ([section 7](#7-unknown-tags)).
> **Tip (non-normative): Example: redefining a core tag**
>
> MongoDB writes dates in its canonical format as `{ "$date": { "$numberLong": "1705276800000" } }`. If a type set redefined `$date` to emit that form, a reader with only the core type set would find a known tag with an unexpected value and would fail or misread it. Under [`TAG_RESERVED`](#TAG_RESERVED), writers always emit the core `$date` form; the BSON type set may only accept the MongoDB form when reading ([`BSON_READ_CANONICAL_DATE`](#BSON_READ_CANONICAL_DATE)).
> **Tip (non-normative): Example: application tags**
>
> An e-commerce application defines `{ "$money": { "amount": "10.50", "currency": "BRL" } }`. If a future ECSON version defines an official `$money` with another form, the stored data becomes ambiguous; if another application also defines `$money`, data from both mixes in the same store. With `$shop.money` and `$acme.money`, neither collides with the specification nor with each other.
## 7. Unknown tags
A reader may receive a typed value whose tag it does not know, for example a client without BSON support receiving `{ "$oid": "..." }`.
**Rule `UNKNOWN_IGNORE_DEFAULT`**: MUST
By default, an implementation MUST NOT fail when deserializing a typed value with an unknown tag, except as stated in [`UNKNOWN_NOT_JSON`](#UNKNOWN_NOT_JSON).
**Rule `UNKNOWN_PRESERVE`**: MUST
When an unknown tag is ignored, the implementation MUST preserve the tag and its serialized value, so that serializing the result again produces the same typed value.
**Rule `UNKNOWN_RAW`**: MUST
The serialized value of an unknown tag MUST be preserved as it is: keys inside it MUST NOT be unescaped and typed values inside it MUST NOT be interpreted.
**Rule `UNKNOWN_NOT_JSON`**: MUST
When deserializing, an unknown tag whose value contains `NaN`, `Infinity` or `-Infinity`, which JSON5 input allows and JSON cannot represent, MUST fail, because it could not be written back unchanged ([`UNKNOWN_PRESERVE`](#UNKNOWN_PRESERVE)). Other JSON5 numbers inside it, such as `+1`, `.5`, `0x10` and `-0`, keep their value and are written back in JSON syntax (`1`, `0.5`, `16` and `0`, see [`TYPE_NUMBER_ZERO_READ`](#TYPE_NUMBER_ZERO_READ)).
**Rule `UNKNOWN_ERROR_MODE`**: MAY
An implementation MAY offer a mode that fails when deserializing a typed value with an unknown tag.
> **Note (non-normative): Rationale**
>
> With unconditional escaping ([section 2](#2-escape-convention)), turning an unknown typed value into a plain object would corrupt it: on the next serialization its key would be escaped (`$oid` becomes `$$oid`) and it would stop being a typed value. Preserving unknown typed values lets intermediaries (proxies, providers, caches) pass data they do not understand without changing it.
> **Tip (non-normative): Example**
>
> A reader without BSON support receives `{ "id": { "$oid": "507f1f77bcf86cd799439011" } }`, keeps `id` as an opaque unknown typed value, and later serializes it back as `{ "id": { "$oid": "507f1f77bcf86cd799439011" } }`.
> **Note (non-normative)**
>
> Hosts whose JSON parser reads numbers as IEEE 754 doubles, such as ECMAScript `JSON.parse`, cannot preserve integers outside the range [-(2^53)+1, (2^53)-1] inside unknown tags ([RFC 8259, section 6](https://www.rfc-editor.org/rfc/rfc8259#section-6)). This is a limit of the host, not of ECSON.
## 8. Conformance and interoperability
### 8.1 Conformance levels
| Level | Requirements |
|---|---|
| **Structural** | All rules in sections 1, 2, 5, 6 and 7, with support for any subset of the core types |
| **Core** | Structural, plus every type in [section 3](#3-built-in-types) |
| **Type set** | Core, plus every type of one official extension type set ([section 4](#4-extension-type-sets)), for example "Core + BSON", "Core + References" or "Core + Error" |
> **Note (non-normative)**
>
> A structural implementation that knows no type at all still passes data through without changing it, because unknown typed values are preserved ([section 7](#7-unknown-tags)). This makes small implementations in other languages safe to use as intermediaries.
> **Note (non-normative)**
>
> The Structural level includes sections 5.4 and 5.5, which name ECMAScript mechanisms. Implementations in other languages meet them with the equivalent mechanisms of their language ([section 5](#5-type-definitions-and-processing)), and write and read the same forms, such as `$class` with `ctor` and `value`.
**Rule `CONFORMANCE_DECLARE`**: MUST
An implementation MUST state which conformance level it meets and, for the structural level, which core types it supports. An implementation in a host language other than ECMAScript MUST also state which mechanisms of its language stand for `toJSON`, the static `fromJSON` and the behavior of `JSON.stringify` ([section 5](#5-type-definitions-and-processing)).
### 8.2 JSON5 input
ECSON output is always standard JSON ([`OUTPUT_JSON`](#OUTPUT_JSON)). Input may also come from humans, for example in configuration files.
**Rule `JSON5_INPUT`**: SHOULD
Deserializers SHOULD accept [JSON5](https://spec.json5.org/) input. Typed value detection and escaping MUST work identically for JSON and JSON5 input.
> **Tip (non-normative): Example**
>
> ```json5
> {
> createdAt: { $date: "2024-01-15T00:00:00.000Z" }, // unquoted key, comment
> tags: { $set: ["a", "b",] }, // trailing comma
> }
> ```
### 8.3 Media type
**Rule `MEDIA_TYPE`**: SHOULD
ECSON content exchanged over protocols that carry media types (such as HTTP) SHOULD be labeled `application/vnd.ecson+json`.
> **Note (non-normative): Rationale**
>
> The `+json` structured syntax suffix ([RFC 6839](https://www.rfc-editor.org/rfc/rfc6839)) tells generic clients that the content is valid JSON. The vendor tree (`vnd.`) does not require standardization; if ECSON becomes an IETF specification, the media type may become `application/ecson+json`.
### 8.4 MongoDB Extended JSON
ECSON is not MongoDB Extended JSON, but they overlap:
- the core `$date` string form equals the MongoDB relaxed form for years 1970 to 9999;
- the BSON type set ([section 4.1](#41-bson-type-set)) uses the exact MongoDB canonical forms;
- MongoDB numeric wrappers (`$numberLong`, `$numberInt`, `$numberDouble`) are not ECSON tags and are preserved as unknown tags.
### 8.5 Versioning
**Rule `SPEC_SEMVER`**: MUST
This specification MUST be versioned independently of the other specifications of the LingoData family, following [Semantic Versioning 2.0.0](https://semver.org/).
> **Note (non-normative)**
>
> While this specification is in a `0.x` version, any release may contain incompatible changes, as allowed by Semantic Versioning. Version `1.0.0` is reserved for when the reference implementation and the conformance test suite validate the specification.
## 9. Non-goals
- **Binary encoding**: ECSON is text only. For binary efficiency, use formats such as [CBOR](https://www.rfc-editor.org/rfc/rfc8949) or [MessagePack](https://github.com/msgpack/msgpack/blob/master/spec.md).
- **References and cycles**: ECSON does not preserve shared or circular references; serializing a circular value fails ([`CIRCULAR_FAIL`](#CIRCULAR_FAIL)).
- **Schema validation**: ECSON validates only the serialized form of each type ([`TYPEDEF_VALIDATE`](#TYPEDEF_VALIDATE)). Validating the shape of documents is left to schema languages applied after deserialization.
- **Streaming**: ECSON does not define incremental serialization or parsing.
- **Functions**: ECSON never serializes functions ([`FUNCTION_NOT_SERIALIZED`](#FUNCTION_NOT_SERIALIZED)), because reading them back would mean evaluating code received in the data.
- **Storage format**: ECSON is a serialization for transport. Data stores keep values in their native types; ECSON does not define how they are stored.
## 10. References
### 10.1 Normative references
- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119): Key words for use in RFCs to Indicate Requirement Levels
- [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words
- [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259): The JavaScript Object Notation (JSON) Data Interchange Format
- [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339): Date and Time on the Internet: Timestamps
- [RFC 9557](https://www.rfc-editor.org/rfc/rfc9557): Date and Time on the Internet: Timestamps with Additional Information
- [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648): The Base16, Base32, and Base64 Data Encodings
- [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785): JSON Canonicalization Scheme (JCS)
- [RFC 6839](https://www.rfc-editor.org/rfc/rfc6839): Additional Media Type Structured Syntax Suffixes
- [ECMAScript Temporal](https://tc39.es/proposal-temporal/)
- [ECMAScript `Date.prototype.toISOString`](https://tc39.es/ecma262/#sec-date.prototype.toisostring) and the [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format), including expanded years
- [JSON5](https://spec.json5.org/)
- [Unicode Standard Annex #44, Unicode Character Database](https://www.unicode.org/reports/tr44/): the `White_Space` property and the `Cc` general category
- [MongoDB Extended JSON v2](https://github.com/mongodb/specifications/blob/master/source/extended-json/extended-json.md)
### 10.2 Informative references
- [Meteor EJSON](https://docs.meteor.com/api/ejson.html)
- [Superjson](https://github.com/ravionhq/superjson)
- [devalue](https://github.com/sveltejs/devalue)
- [BSON specification](https://bsonspec.org/spec.html)
---
# ESType: ECMAScript types for JSON Schema
Version: 0.1.0 · Status: draft · License: Apache-2.0
Source: lingodata/estype@0cbfb46
## 0. Introduction
ESType is a [JSON Schema](https://json-schema.org/draft/2020-12/json-schema-core) vocabulary that states the JavaScript (ECMAScript) type of a value. It is part of the **LingoData** family of specifications for data interoperability.
JSON Schema describes JSON documents, and JSON has no dates, big integers, sets, maps or binary data. The same date can travel as a plain JSON string or as an [ECSON](https://github.com/lingodata/ecson) typed value (`{ "$date": "..." }`). With ESType, a schema declares the type of the value once, accepts both forms, and lets libraries convert the value to the native type. ESType is unrelated to the `jstype` option of Protocol Buffers ([section 5.3](#53-informative-references)).
> **Tip (non-normative): Example**
>
> ```json
> { "type": "string", "format": "date-time", "estype": "date" }
> ```
> accepts, once compiled ([section 2](#2-compilation)), `"2026-11-13T10:00:00.000Z"` and `{ "$date": "2026-11-13T10:00:00.000Z" }`, and a library that reads it with the schema produces a `Date`.
### 0.1 Conventions
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)) when, and only when, they appear in all capitals, as shown here.
### 0.2 Terminology
- **ES type**: a type that ECSON serializes and that `estype` can name ([`ESTYPE_KEYWORD`](#ESTYPE_KEYWORD), [`ESTYPE_EXCLUDED`](#ESTYPE_EXCLUDED)), identified by its ECSON tag without `$` (for example `date` for `$date`).
- **ECSON form**: the typed value that ECSON uses to represent the value ([ECSON section 1](./ecson.md#1-typed-values)).
- **Plain JSON form**: the JSON value of a value without ECSON ([ECSON section 5.3](./ecson.md#53-plain-json-form)).
- **Native value**: the value in the native type of the host language (for example a JavaScript `Date`).
- **Declared schema**: the keywords of a subschema other than `estype`, as written by the author of the schema.
- **ECSON branch**, **plain branch** and **exclusion schema**: the parts of a compiled subschema ([`COMPILE_ECSON_BRANCH`](#COMPILE_ECSON_BRANCH), [`COMPILE_PLAIN_BRANCH`](#COMPILE_PLAIN_BRANCH)).
- **Default plain schema**: the schema of the table in [section 2.1](#21-default-plain-schemas) used for the plain branch when the declared schema has no keyword other than those of [`COMPILE_OUTSIDE_KEYWORDS`](#COMPILE_OUTSIDE_KEYWORDS) ([`COMPILE_PLAIN_BRANCH`](#COMPILE_PLAIN_BRANCH)).
- **Compiled subschema**: the result of compiling a subschema with `estype` ([`COMPILE_REWRITE`](#COMPILE_REWRITE)).
- **Converter**: an implementation that meets the Converter level ([section 5.1](#51-conformance)).
- **Path** of a value: the location of the value in the document, from its root.
### 0.3 Versioning
**Rule `SPEC_SEMVER`**: MUST
This specification MUST be versioned independently of the other specifications of the LingoData family, following [Semantic Versioning 2.0.0](https://semver.org/).
> **Note (non-normative)**
>
> While this specification is in a `0.x` version, any release may contain incompatible changes, as allowed by Semantic Versioning.
## 1. Vocabulary
**Rule `ESTYPE_KEYWORD`**: MUST
The value of the `estype` keyword MUST be a string naming one ES type: the tag, without the leading `$`, of a type of the ECSON core type set, of an official ECSON extension type set, or of an application type with a namespace ([ECSON section 6](./ecson.md#6-tag-ownership-and-namespaces)). For an application type, `$` followed by the value MUST follow [ECSON `TAG_GRAMMAR`](./ecson.md#TAG_GRAMMAR).
**Rule `ESTYPE_EXCLUDED`**: MUST NOT
`estype` MUST NOT be `undefined`, `minKey`, `maxKey` or `class`.
> **Note (non-normative): Rationale**
>
> The plain JSON form of `undefined`, `minKey` and `maxKey` is `null` or an omitted member ([ECSON section 5.3](./ecson.md#53-plain-json-form)), and `null` is never converted ([`CONVERT_NULL`](#CONVERT_NULL)), so these types could not be read from the plain JSON form. `class` is not a type: it is the generic form of application classes ([ECSON section 5.4](./ecson.md#54-application-classes)).
> **Tip (non-normative): Example**
>
> Valid values: `date`, `bigint`, `map`, `plaindate`, `error`, `oid`, `rel`, `acme.money`. Not valid: `acme.` and `a..b` (the tags `$acme.` and `$a..b` break [`TAG_GRAMMAR`](./ecson.md#TAG_GRAMMAR)).
**Rule `ESTYPE_VOCABULARY_URI`**: MUST
The vocabulary MUST be identified by the URI `https://lingodata.dev/estype/vocab/0.1`, declared with `$vocabulary` in meta-schemas that include it.
**Rule `ESTYPE_META_SCHEMA_URI`**: MUST
The meta-schema of the vocabulary MUST be identified by the URI `https://lingodata.dev/estype/meta/0.1`.
**Rule `ESTYPE_DIALECT_URI`**: MUST
The dialect that adds this vocabulary to JSON Schema 2020-12 MUST be identified by the URI `https://lingodata.dev/estype/schema/0.1`.
**Rule `ESTYPE_DIALECT_VOCABULARY`**: MUST
The meta-schema of the dialect MUST declare the vocabulary in `$vocabulary` with the value `false`.
> **Note (non-normative)**
>
> A schema may declare the dialect in `$schema`. With `false`, a validator that does not know the vocabulary still processes schemas of the dialect, and treats `estype` as an annotation ([JSON Schema Core, section 8.1.2](https://json-schema.org/draft/2020-12/json-schema-core#section-8.1.2)); with `true`, it would refuse them.
> **Caution (non-normative): Provisional**
>
> The vocabulary, meta-schema and dialect URIs and the URI of the definitions document ([section 3](#3-definitions-document)) are provisional until the publication domain of the LingoData family is defined. This version does not yet specify the content of the meta-schema and dialect documents, beyond the rules of this section.
**Rule `ESTYPE_SUBSCHEMA`**: MUST NOT
A schema object that has `estype` MUST NOT also have a `$ref` whose target, directly or through further `$ref`, has `estype`.
**Rule `ESTYPE_CONFLICT`**: MUST NOT
Two subschemas that apply to the same value MUST NOT have different `estype` values. The subschemas that apply to the same value as a subschema S are S itself and those reached from S through entries of `allOf` and through `$ref`, repeatedly and in any combination. The branches of `anyOf`, `oneOf` and `not` are not among them.
> **Tip (non-normative): Example**
>
> `{ "allOf": [{ "estype": "date" }, { "estype": "bigint" }] }` and `{ "estype": "date", "allOf": [{ "$ref": "#/$defs/n" }], "$defs": { "n": { "estype": "bigint" } } }` break the rule. `{ "anyOf": [{ "estype": "date" }, { "estype": "bigint" }] }` does not: its branches are alternatives.
> **Note (non-normative)**
>
> `estype` is a keyword of a schema object. JSON Schema recommends that implementations treat unknown keywords as annotations ([JSON Schema Core, section 6.5](https://json-schema.org/draft/2020-12/json-schema-core#section-6.5)). A generic validator that does not know ESType, including one that reads the dialect meta-schema ([`ESTYPE_DIALECT_VOCABULARY`](#ESTYPE_DIALECT_VOCABULARY)), validates only the declared schema; compiling the schema ([section 2](#2-compilation)) makes it accept the ECSON form too.
## 2. Compilation
Compiling a schema rewrites every subschema that has `estype` into a standard JSON Schema 2020-12 subschema that accepts the value in its ECSON form or in its plain JSON form, as described by the declared schema. A compiled schema accepts both forms in any validator that treats unknown keywords as annotations ([JSON Schema Core, section 6.5](https://json-schema.org/draft/2020-12/json-schema-core#section-6.5)), since `estype` stays in it ([`COMPILE_OUTSIDE_KEYWORDS`](#COMPILE_OUTSIDE_KEYWORDS)). A strict validator such as [Ajv](https://ajv.js.org/) must be configured to accept `estype` (for example with `ajv.addKeyword("estype")`).
**Rule `COMPILE_REWRITE`**: MUST
Compilation MUST replace each subschema S with `estype` T by a subschema with the keyword `oneOf` holding two subschemas, the ECSON branch ([`COMPILE_ECSON_BRANCH`](#COMPILE_ECSON_BRANCH)) and the plain branch ([`COMPILE_PLAIN_BRANCH`](#COMPILE_PLAIN_BRANCH)), plus the keywords of S that stay outside ([`COMPILE_OUTSIDE_KEYWORDS`](#COMPILE_OUTSIDE_KEYWORDS)).
**Rule `COMPILE_ECSON_BRANCH`**: MUST
The ECSON branch MUST be `{ "type": "object", "required": [TAG], "properties": { TAG: true }, "additionalProperties": false }`, where TAG is the tag of T with its leading `$`.
**Rule `COMPILE_PLAIN_BRANCH`**: MUST
The plain branch MUST be an `allOf` of two subschemas: the declared schema without the keywords that stay outside (or, when the declared schema has no keyword other than those of [`COMPILE_OUTSIDE_KEYWORDS`](#COMPILE_OUTSIDE_KEYWORDS), the default plain schema of T from the table below), and the exclusion schema `{ "not": E }`, where E is the ECSON branch.
**Rule `COMPILE_NO_DEFAULT`**: MUST
When T has no default plain schema in the table below (for example an application type) and the declared schema has no keyword other than those of [`COMPILE_OUTSIDE_KEYWORDS`](#COMPILE_OUTSIDE_KEYWORDS), compilation MUST fail.
> **Note (non-normative)**
>
> The default plain schema is used only when the declared schema has no keyword other than those of [`COMPILE_OUTSIDE_KEYWORDS`](#COMPILE_OUTSIDE_KEYWORDS) ([`COMPILE_PLAIN_BRANCH`](#COMPILE_PLAIN_BRANCH)): it is never merged with declared keywords. With `{ "estype": "bigint", "minimum": 0 }` the plain branch holds only `{ "minimum": 0 }`, which accepts any string, so authors who declare keywords should also declare `type`.
**Rule `COMPILE_INVALID_ESTYPE`**: MUST
Compilation MUST fail for a schema with an `estype` that breaks [`ESTYPE_KEYWORD`](#ESTYPE_KEYWORD), [`ESTYPE_EXCLUDED`](#ESTYPE_EXCLUDED), [`ESTYPE_SUBSCHEMA`](#ESTYPE_SUBSCHEMA) or [`ESTYPE_CONFLICT`](#ESTYPE_CONFLICT).
**Rule `COMPILE_OUTSIDE_KEYWORDS`**: MUST
The keywords `estype`, `$schema`, `$vocabulary`, `$id`, `$anchor`, `$dynamicAnchor`, `$defs`, `$comment` and the keywords of the Meta-Data vocabulary ([JSON Schema Validation, section 9](https://json-schema.org/draft/2020-12/json-schema-validation#section-9): `title`, `description`, `default`, `deprecated`, `readOnly`, `writeOnly`, `examples`) MUST stay outside the `oneOf`, in the compiled subschema.
**Rule `COMPILE_IDEMPOTENT`**: MUST
Compiling a compiled schema MUST NOT change it.
**Rule `COMPILE_DETECT`**: MUST
A subschema with `estype` T MUST be treated as compiled, and left as it is, when its only keywords are `oneOf` and keywords of [`COMPILE_OUTSIDE_KEYWORDS`](#COMPILE_OUTSIDE_KEYWORDS), and the `oneOf` holds exactly two subschemas: the first equal to the ECSON branch of T, and the second a schema whose only keyword is an `allOf` of a schema and `{ "not": E }`, where E is the ECSON branch of T.
> **Note (non-normative)**
>
> Any other `oneOf` written by the author belongs to the declared schema and moves into the plain branch.
> **Tip (non-normative): Example**
>
> ```json
> { "title": "Created at", "type": "string", "format": "date-time", "estype": "date" }
> ```
> compiles to
> ```json
> {
> "title": "Created at",
> "estype": "date",
> "oneOf": [
> { "type": "object", "required": ["$date"], "properties": { "$date": true }, "additionalProperties": false },
> { "allOf": [
> { "type": "string", "format": "date-time" },
> { "not": { "type": "object", "required": ["$date"], "properties": { "$date": true }, "additionalProperties": false } }
> ] }
> ]
> }
> ```
> **Note (non-normative): Rationale**
>
> In JSON Schema, all keywords of a schema object apply together. Keeping `"type": "string"` beside a `oneOf` would reject the ECSON form, which is an object, so the declared keywords move into the plain branch. A declared schema may accept objects, for example `{ "estype": "bigint", "minimum": 0 }` (validation keywords apply only to their own type) or the default plain schema of `rel`; without the exclusion schema, the ECSON form would match both branches and `oneOf` would reject it. The exclusion keeps the branches disjoint, so `oneOf` matches exactly one. The ECSON branch checks only the shape; the serialized form inside the tag is validated by ECSON ([ECSON `TYPEDEF_VALIDATE`](./ecson.md#TYPEDEF_VALIDATE)).
### 2.1 Default plain schemas
| ES type | Default plain schema |
|---|---|
| `date`, `instant` | `{ "type": "string", "format": "date-time" }` |
| `plaindate` | `{ "type": "string", "format": "date" }` |
| `zoneddatetime`, `plaindatetime`, `plaintime`, `plainyearmonth`, `plainmonthday`, `duration`, `regexp`, `symbol`, `oid`, `numberDecimal` | `{ "type": "string" }` |
| `bigint` | `{ "type": "integer" }` |
| `number` | `{ "type": "number" }` |
| `set`, `map` | `{ "type": "array" }` |
| `bytes`, `binary` | `{ "type": "string", "contentEncoding": "base64" }` |
| `error` | `{ "type": "object", "required": ["name", "message"] }` |
| `timestamp` | `{ "type": "object", "required": ["t", "i"] }` |
| `rel` | `{ "type": ["string", "object", "array"] }` |
> **Note (non-normative)**
>
> These schemas follow the plain JSON forms of ECSON ([ECSON section 5.3](./ecson.md#53-plain-json-form)) of valid values. The plain form `null` (an invalid date, `NaN` and the infinities of `number`, an empty `rel`) is accepted only when the declared schema allows it ([`CONVERT_NULL`](#CONVERT_NULL)).
>
> Formats are used when their syntax matches the plain JSON form of values with a year from 0000 to 9999. Plain forms with an expanded year ([ECSON section 5.3](./ecson.md#53-plain-json-form), for example `+275760-09-13T00:00:00.000Z`) do not match the `date-time` and `date` formats of RFC 3339, so a validator that asserts `format` rejects them. The RFC 3339 `time` format requires a UTC offset, which `Temporal.PlainTime` strings do not have, and the `duration` format forbids signs and fractions, which `Temporal.Duration` strings can have; so these types use no format.
>
> Generic validators treat `format` and `contentEncoding` as annotations by default ([JSON Schema Validation, sections 7.2.1 and 8.1](https://json-schema.org/draft/2020-12/json-schema-validation#section-7.2.1)): a malformed date string or Base64 string passes the compiled schema, and the converter rejects it (for example [ECSON `TYPE_BYTES_VALID`](./ecson.md#TYPE_BYTES_VALID)).
> **Caution (non-normative): References into declared schemas**
>
> Compilation moves the declared schema into the `oneOf`, so a `$ref` with a JSON Pointer into a subschema with `estype` (for example `#/properties/a/items`) no longer resolves after compilation. Use `$defs` or `$anchor` as targets of `$ref`: they stay outside the `oneOf` ([`COMPILE_OUTSIDE_KEYWORDS`](#COMPILE_OUTSIDE_KEYWORDS)).
## 3. Definitions document
The definitions document is a helper: a published schema with one compiled subschema per ES type, which schema authors reference with `$ref` instead of writing `estype` and compiling.
**Rule `DEFS_DOCUMENT`**: MUST
The definitions document MUST be a JSON Schema 2020-12 document with `$id` `https://lingodata.dev/estype/defs/0.1` and, in `$defs`, one subschema for each ES type of the table in [section 2.1](#21-default-plain-schemas), named by the ES type and equal to the compilation of `{ "estype": T }`.
**Rule `DEFS_EQUIVALENT`**: MUST
A subschema whose only keywords are a `$ref` to an entry of the definitions document and keywords of [`COMPILE_OUTSIDE_KEYWORDS`](#COMPILE_OUTSIDE_KEYWORDS) MUST be treated as equivalent to the compiled subschema with that `estype`, including for conversion ([section 4](#4-conversion-to-native-values)).
> **Tip (non-normative): Example**
>
> ```json
> { "properties": { "createdAt": { "$ref": "https://lingodata.dev/estype/defs/0.1#/$defs/date" } } }
> ```
> **Caution (non-normative): Keywords next to `$ref`**
>
> All keywords of a schema object apply together, including those next to `$ref`. Adding `"type": "string"` beside a `$ref` to a definition rejects the ECSON form. To narrow the plain form (for example with `minimum`), write `estype` and the declared schema and compile, instead of using `$ref`.
## 4. Conversion to native values
The rules of this section apply to each value whose subschema has `estype`, directly or through `$ref` ([`CONVERT_REF`](#CONVERT_REF)). A converter is an implementation at the Converter level ([section 5.1](#51-conformance)).
**Rule `CONVERT_PLAIN_SHOULD`**: SHOULD
A library that deserializes plain JSON with a schema, and does not claim the Converter level, SHOULD convert each value whose subschema has `estype` from its plain JSON form to the native value of that ES type.
**Rule `CONVERT_ACCEPTED_FORMS`**: MUST
A converter MUST accept, for each ES type, a value without a tag in its plain JSON form ([ECSON section 5.3](./ecson.md#53-plain-json-form)) and a value without a tag in the serialized form that ECSON writes inside the tag. For example, a `bigint` is accepted as `42` and as `"42"`, and a `date` as `"2024-01-15T00:00:00.000Z"` and as `1705276800000`.
> **Note (non-normative)**
>
> A declared schema may thus choose either form, for example `{ "estype": "bigint", "type": "string" }` for big integers sent as strings. The ECSON form, with the tag (`{ "$bigint": "42" }`), is accepted by [`CONVERT_ECSON_WITH_SCHEMA`](#CONVERT_ECSON_WITH_SCHEMA).
**Rule `CONVERT_PLAIN_READ`**: MUST
A converter MUST read a value without a tag by mapping it to the serialized form of the tag of its ES type, as the inverse of the plain JSON form of [ECSON section 5.3](./ecson.md#53-plain-json-form) (a value already in the serialized form stays as it is), and by deserializing that form by the rules of ECSON. A form that ECSON rejects fails [`CONVERT_FAIL`](#CONVERT_FAIL).
**Rule `CONVERT_PLAIN_LOSS`**: MUST
A converter MUST read the plain JSON form of a `symbol` (a string) as a new symbol with that description, which is not in the global symbol registry; the plain JSON form of `bytes` (a Base64 string) as a `Uint8Array`; and the plain JSON form of `binary` (a Base64 string) with the subtype `00`.
> **Note (non-normative): Forms with loss**
>
> These plain JSON forms do not keep the whole value: a registered symbol, the type of a typed array and the subtype of a `binary` are lost. Clients that need the exact value send the ECSON form.
**Rule `CONVERT_NULL`**: MUST
A plain JSON `null` MUST NOT be converted: it stays `null`, and is valid only when the declared schema accepts it. This does not apply to a `null` inside a tag, such as `{ "$date": null }` (an invalid date) or `{ "$rel": null }` (an empty reference), which is converted.
**Rule `CONVERT_NESTED`**: MUST
Subschemas nested in the declared schema MUST be applied to the members of the value after conversion, whether the value arrived in the ECSON form or in the plain JSON form. The declared schema sees a `set` as the array of its members and a `map` as the array of its `[key, value]` pairs, as in their plain JSON forms, so `items` (and, for a `map`, `prefixItems` inside `items`) describes the members in both forms.
> **Note (non-normative)**
>
> The compiled schema alone does not validate the members of the ECSON form: the ECSON branch checks only its shape ([`COMPILE_ECSON_BRANCH`](#COMPILE_ECSON_BRANCH)). Only the converter applies the nested subschemas to them.
> **Tip (non-normative): Example**
>
> With `{ "estype": "map", "type": "array", "items": { "type": "array", "prefixItems": [{ "type": "string" }, { "estype": "date" }] } }`, both `[["a", "2024-01-15T00:00:00.000Z"]]` and `{ "$map": [["a", "2024-01-15T00:00:00.000Z"]] }` give a `Map` whose value for `a` is a `Date`.
**Rule `CONVERT_ECSON_WITH_SCHEMA`**: MUST
A converter MUST, when deserializing with a schema, produce the native value of each value whose subschema has `estype`, whether the value is in the ECSON form or in the plain JSON form.
**Rule `CONVERT_REF`**: MUST
A value whose subschema reaches a subschema with `estype` through `$ref` MUST be converted as for that subschema. A `$ref` to an entry of the definitions document follows [`DEFS_EQUIVALENT`](#DEFS_EQUIVALENT).
**Rule `CONVERT_FAIL`**: MUST
A value whose subschema has `estype` T, that is not in the ECSON form of T and cannot be converted to T, MUST be reported as not valid against the schema, with the path of the value.
**Rule `CONVERT_PATH_POINTER`**: SHOULD
The path of a value in a report of [`CONVERT_FAIL`](#CONVERT_FAIL) or [`CONVERT_MALFORMED_ECSON`](#CONVERT_MALFORMED_ECSON) SHOULD be a JSON Pointer ([RFC 6901](https://www.rfc-editor.org/rfc/rfc6901)).
**Rule `CONVERT_FORM_PER_FIELD`**: MUST
A converter MUST determine the form of each value (ECSON form or plain JSON form) independently of the other values of the document.
> **Note (non-normative)**
>
> A document may thus mix both forms. The rest of the document, outside the values whose subschema has `estype`, is read by the rules of the format of the text: in an ECSON text, keys of plain objects are escaped ([ECSON `ESCAPE_DESERIALIZE`](./ecson.md#ESCAPE_DESERIALIZE)); in a plain JSON text, keys starting with `$` are plain keys ([ECSON `PLAIN_FORM_READ`](./ecson.md#PLAIN_FORM_READ)).
**Rule `CONVERT_MALFORMED_ECSON`**: MUST
A value in the ECSON form of its ES type whose serialized form is malformed MUST be reported as not valid against the schema, as a failure of the ECSON rule [`TYPEDEF_VALIDATE`](./ecson.md#TYPEDEF_VALIDATE), with the path of the value.
**Rule `CONVERT_MALFORMED_DETAIL`**: MAY
A converter MAY add the path inside the serialized form to the report of [`CONVERT_MALFORMED_ECSON`](#CONVERT_MALFORMED_ECSON), as extra information.
> **Tip (non-normative): Example**
>
> With a schema where `createdAt` and `paidAt` have `estype: date`, the document `{ "createdAt": { "$date": "2026-11-27T10:00:00.000Z" }, "paidAt": "2026-11-27T11:00:00.000Z" }` is valid and gives two `Date` values. `{ "createdAt": { "$date": "yesterday" } }` fails [`TYPEDEF_VALIDATE`](./ecson.md#TYPEDEF_VALIDATE) at `/createdAt`. `{ "createdAt": { "$bigint": "1" } }` is not the ECSON form of `date` and fails [`CONVERT_FAIL`](#CONVERT_FAIL) at `/createdAt`.
> **Tip (non-normative): Example**
>
> With the schema `{ "properties": { "total": { "estype": "bigint" } } }`, both `{ "total": 42 }` and `{ "total": { "$bigint": "42" } }` deserialize to `{ total: 42n }`.
## 5. Conformance and references
### 5.1 Conformance
| Level | Requirements |
|---|---|
| **Compiler** | Sections 1, 2 and 3: validates `estype` values, compiles schemas and recognizes references to the definitions document ([`DEFS_EQUIVALENT`](#DEFS_EQUIVALENT)) |
| **Converter** | Compiler, plus [section 4](#4-conversion-to-native-values) |
**Rule `CONFORMANCE_DECLARE`**: MUST
An implementation MUST state which conformance level it meets and which ES types it supports.
**Rule `CONFORMANCE_UNSUPPORTED`**: MUST
An implementation MUST fail, and MUST NOT ignore `estype`, for a schema or value with an ES type that it does not support.
### 5.2 Normative references
- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): requirement level key words (BCP 14)
- [JSON Schema 2020-12: Core](https://json-schema.org/draft/2020-12/json-schema-core) and [Validation](https://json-schema.org/draft/2020-12/json-schema-validation)
- [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339): date and time formats (`date-time`, `date`, `time`, `duration`)
- [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901): JSON Pointer
- [ECSON](https://github.com/lingodata/ecson) `0.2.x`: tags, type sets, plain JSON form ([ECSON section 5.3](./ecson.md#53-plain-json-form)) and tag namespaces ([ECSON section 6](./ecson.md#6-tag-ownership-and-namespaces))
- [Semantic Versioning 2.0.0](https://semver.org/)
### 5.3 Informative references
- [Ajv](https://ajv.js.org/): custom keywords, strict mode and schema compilation ([section 2](#2-compilation))
- [Protocol Buffers `jstype`](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto): a field option with a similar name and a different meaning (how 64-bit integers map to JavaScript numbers or strings)
---
# UnQuery: Universal Query String Filter Specification
Version: 0.1.0 · Status: draft · License: Apache-2.0
Source: lingodata/unquery@865de91
## 0. Introduction
UnQuery (Universal Query String Filter Specification) defines how to write search filters for documents, in URLs and in JSON, independently of the data source. It is part of the **LingoData** family of specifications for data interoperability.
A filter is defined once, as an abstract model ([section 1](#1-query-model)), and can be written in two syntaxes: JSON ([section 2](#2-json-syntax)) and a restricted SQL predicate syntax ([section 3](#3-sql-syntax)). [Section 4](#4-query-string-mapping) maps both to URL query strings. Implementations translate filters to each data source, such as MongoDB, PostgreSQL, MySQL, Notion or Airtable, and never pass filter text to a data source.
Within the family, UnQuery operands are [ECSON](https://github.com/lingodata/ecson) values, and UnQuery is the search query format recommended by the CRUD API Base Specification.
### 0.1 Conventions
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)) when, and only when, they appear in all capitals, as shown here.
Normative rules are identified by a code (for example [`NULL_NE`](#NULL_NE)). Notes, examples and rationales are informative.
### 0.2 Terminology
- **Filter**: a tree of conditions and logical combinations ([section 1](#1-query-model)).
- **Condition**: a field path, an operator and an operand.
- **Field path**: the dot-separated path to a field in a document.
- **Operator set**: a named group of operators; the core set is mandatory, the others are optional.
- **Control parameter**: a query string key starting with `@` ([section 4.2](#42-keys)).
- **Provider**: the component that translates filters to a specific data source.
## 1. Query model
UnQuery defines an abstract **filter**: a tree of conditions over the fields of a document. The JSON syntax ([section 2](#2-json-syntax)) and the SQL syntax ([section 3](#3-sql-syntax)) are two ways of writing the same filter. Implementations translate the filter to each data source; neither syntax is passed to a data source as text.
### 1.1 Filters and conditions
A filter is one of:
- a **condition**: a field path, an operator and an operand, such as `age` `gte` `18`;
- a **logical combination**: `and` or `or` over a list of filters, `nor` over a list of filters, or `not` over a single filter.
**Rule `MODEL_TRANSLATE`**: MUST
An implementation MUST translate every filter, in any syntax, into the abstract filter model before evaluating it or translating it to a data source.
### 1.2 Field paths
A field path is a sequence of **segments** separated by `.`, one segment per nesting level. Each segment is a field name, written either plain or between double quotes, optionally followed by array indexes.
```abnf
path = segment *( "." segment )
segment = name *index
name = plain / quoted
plain = 1*( %x20-21 / %x23-2D / %x2F-5A / %x5C / %x5E-D7FF / %xE000-10FFFF ) ; any Unicode scalar value from U+0020, except ".", DQUOTE, "[" and "]"
quoted = DQUOTE 1*( %x20-21 / %x23-D7FF / %xE000-10FFFF / DQUOTE DQUOTE ) DQUOTE ; any Unicode scalar value from U+0020
index = "[" ( "0" / %x31-39 *DIGIT ) "]" ; zero-based, no leading zeros
```
**Rule `PATH_DOT_NOTATION`**: MUST
A field path MUST follow the `path` grammar above. A plain name may contain any character from U+0020 except `.`, `"`, `[` and `]`; a quoted name may contain any character from U+0020, and represents a `"` as `""`. Control characters (U+0000 to U+001F) are not allowed in names.
**Rule `PATH_RESERVED_START`**: MUST NOT
A field name (the `name` of a segment, after removing the quotes of a quoted name, without its indexes) MUST NOT start with `$` or `@`, which are reserved in the LingoData family for ECSON typed values and for operators and control parameters.
**Rule `PATH_INDEX`**: MUST
An index `[n]`, after a field name or after another index, MUST select the element at the zero-based position `n` of the array at that point of the path. When the value at that point is not an array, or the array has no element at that position, the field MUST be treated as missing.
**Rule `PATH_NUMERIC_SEGMENT`**: MUST
A segment made only of digits, such as `0` in `items.0.price`, MUST be read as a field name, never as an array index.
**Rule `PATH_ARRAYS`**: MUST
When a segment of a field path resolves to an array and has no index, the rest of the path MUST be resolved in each element of the array, and the condition MUST match if it matches the value found in at least one element.
**Rule `PATH_ARRAY_NESTED`**: MUST
When the rest of the path is resolved in the elements of an array ([`PATH_ARRAYS`](#PATH_ARRAYS)), an element that is not a plain object, or that does not have the next field, MUST count as missing for that element. Arrays nested inside arrays MUST NOT be flattened.
**Rule `PATH_INDEX_AS_IS`**: MUST
A segment with an index MUST use the selected element as it is: when that element is an array, the next segment MUST NOT be resolved in its elements.
**Rule `PATH_ARRAY_VALUE`**: MUST
When the value at the end of the path is an array, a condition MUST match if it matches the whole array or at least one of its elements. This rule does not apply to the operators of the Array set ([section 1.5.2](#152-array-set)), which evaluate only the value at the end of the path.
**Rule `PATH_ARRAY_COMPLEMENTS`**: MUST
The complements `ne`, `nin`, `not` and `nor` MUST match exactly when the condition they negate does not match ([`NULL_NE`](#NULL_NE)). The array rules of this section apply to the negated condition, never to the complement itself: `items.price` with `nin [5]` does not match `{ "items": [{ "price": 5 }, { "price": 6 }] }`, because `in [5]` does.
**Rule `PATH_ARRAY_EMPTY`**: MUST
A path that continues past an empty array, such as `items.price` when `items` is `[]`, has no value and MUST be evaluated as a missing field ([section 1.3](#13-missing-fields-null-and-types)): `exists` with operand `false` and `eq` with operand `null` match, and conditions such as `gt` or `exists` with operand `true` do not. An empty array at the end of the path is a present value.
**Rule `PATH_ARRAY_CONDITIONS`**: MUST
A condition on a field path MUST be evaluated independently of the other conditions on the same path, so different conditions MAY be satisfied by different elements of an array.
> **Note (non-normative)**
>
> To require that one element matches several conditions, a filter can use `@elemMatch` ([section 1.5.2](#152-array-set), optional Array set).
> **Caution (non-normative): Brackets in field names and query strings**
>
> `[` and `]` are reserved in plain names; a field name that contains them is written as a quoted name, such as `"tags[]"`. In query strings, RFC 3986 requires `[` and `]` to be percent-encoded (`%5B`, `%5D`), as the note on percent-encoding in [section 4.3](#43-values) says, but browsers and the WHATWG URL parser also send and accept them unencoded; [`QS_DECODE`](#QS_DECODE) ([section 4.1](#41-decoding)) reads both forms as the same key. Some web frameworks parse keys with brackets into arrays and nested objects (for example, [qs](https://github.com/ljharb/qs) reads `items[0]` as an array); implementations decode the query string as [`QS_DECODE`](#QS_DECODE) defines, not as such frameworks do.
> **Note (non-normative)**
>
> Field names may contain spaces, dots and other characters, as is common in spreadsheets and in tools such as Notion and Airtable. Names made only of `A` to `Z`, `a` to `z`, `0` to `9`, `_` and `-` are unreserved characters in [RFC 3986, section 2.3](https://www.rfc-editor.org/rfc/rfc3986#section-2.3) and need no percent-encoding in URLs; other names are percent-encoded ([section 4.1](#41-decoding)). Dot notation is also the notation used by the [CRUD API Base Specification](./crud/base.md#312-fields) for nested Fields.
> **Tip (non-normative): Example**
>
> | Path | Field |
> |---|---|
> | `address.city` | `city` inside `address` |
> | `Customer name` | `Customer name` |
> | `"Total.value"` | `Total.value`, a single level |
> | `order."Total.value"` | `Total.value` inside `order` |
> | `items[0].price` | `price` of the first element of the array `items` |
> | `items.0` | a field named `0` inside `items` |
> | `address.` | invalid: an empty segment after the dot |
>
> `address.city` matches `{ "address": { "city": "Recife" } }`. `items.price` with `gt 100` matches `{ "items": [{ "price": 50 }, { "price": 150 }] }`, because one element matches. `tags` with `eq "a"` matches `{ "tags": ["a", "b"] }` (an element), and with `eq ["a", "b"]` matches it too (the whole array). `items.price` with `gt 10` and `lt 20` matches `{ "items": [{ "price": 5 }, { "price": 25 }] }`, because each condition is matched by a different element.
### 1.3 Missing fields, null and types
Filters use two-valued logic: a condition either matches a document or does not, and the result of the rules in this section never depends on the data source. Two optional sets are the exceptions: `@regex` follows the dialect of each data source ([section 1.5.3](#153-regex-set)), and geospatial results may differ near the edges of large polygons ([section 1.5.1](#151-geospatial-set)).
**Rule `NULL_EQ`**: MUST
`eq` with operand `null` MUST match documents where the field is `null` or missing.
**Rule `NULL_EXISTS`**: MUST
`exists` with operand `false` MUST match only documents where the field is missing; with operand `true`, only documents where the field is present, including when its value is `null`.
**Rule `NULL_UNDEFINED`**: MUST
A field whose value is `undefined` (ECSON `$undefined`) MUST be treated as missing.
**Rule `NULL_UNDEFINED_OPERAND`**: MUST
`eq` with the operand `undefined` MUST match exactly the documents where the field is missing ([`NULL_UNDEFINED`](#NULL_UNDEFINED)), and MUST NOT match a field whose value is `null` or an array with an `undefined` element ([`NULL_UNDEFINED_ELEMENT`](#NULL_UNDEFINED_ELEMENT)). On a path through an array, it follows [`PATH_ARRAYS`](#PATH_ARRAYS), like `eq null`: it matches when the field is missing in at least one element. `in` with `undefined` in its list MUST match missing fields too.
**Rule `NULL_UNDEFINED_IN_OPERAND`**: MUST
An `undefined` inside an array, object, `$set` or `$map` operand, such as `eq [1, undefined]`, MUST make the filter fail, except when it is itself an element of the list of `in` or `nin`.
**Rule `NULL_UNDEFINED_ELEMENT`**: MUST
An `undefined` element inside an array of a document MUST be treated as `null`. This rule does not apply to operands ([`NULL_UNDEFINED_IN_OPERAND`](#NULL_UNDEFINED_IN_OPERAND)).
> **Note (non-normative): Rationale**
>
> The plain JSON form of ECSON omits members whose value is `undefined` ([ECSON section 5.3](./ecson.md#53-plain-json-form)), so treating them as missing gives the same result whether the document travels in ECSON or in plain JSON. Inside arrays, the plain JSON form turns `undefined` into `null`, so an operand such as `[1, undefined]` would become `[1, null]` and the result would depend on the envelope of the filter; the filter fails instead.
**Rule `NULL_NE`**: MUST
`ne` MUST match every document where `eq` with the same operand does not match, including documents where the field is `null` or missing. `nin` MUST likewise match every document where `in` does not.
**Rule `NULL_RANGE`**: MUST
`gt`, `gte`, `lt`, `lte` and `like` MUST NOT match documents where the field is `null` or missing.
**Rule `NO_COERCION`**: MUST
Conditions MUST compare values without type conversion: a value matches only operands of the same type, and range operators MUST NOT match values of a different type than the operand.
> **Note (non-normative): For providers**
>
> Data sources disagree on these cases, so providers must translate them explicitly:
>
> | Filter | MongoDB | SQL (PostgreSQL) | Notion |
> |---|---|---|---|
> | `eq null` | `{ f: null }` (native: matches null and missing) | `f IS NULL` | property is empty |
> | `exists false` | `{ f: { $exists: false } }` | not expressible for columns that always exist: matches nothing; for JSON columns, `NOT (doc ? 'f')` | property not in the database: matches every row |
> | `ne v` | `{ f: { $ne: v } }` (native: matches null and missing) | `f IS DISTINCT FROM v` (plain `f <> v` would skip `NULL`) | property is empty or different from `v` |
> | `nin [a, b]` | `{ f: { $nin: [a, b] } }` | `f IS NULL OR f NOT IN (a, b)` | property is empty or not one of the values |
> | `gt v` | `{ f: { $gt: v } }` (native type bracketing) | `f > v`, with `v` bound to the column type; a type mismatch matches nothing | numeric or date property greater than `v` |
>
> SQL uses three-valued logic, where `f <> 'x'` is unknown, and therefore excluded, when `f` is `NULL`. UnQuery deliberately follows two-valued logic, so a filter with these operators returns the same documents from any provider.
**Rule `PROVIDER_EXACT_OR_FAIL`**: MUST
A provider MUST fail on a condition that it cannot translate with the semantics of this specification, and MUST NOT approximate it. A provider MAY rely on an assumption about the stored data, such as the type of a field, only when it documents that assumption.
> **Note (non-normative): For providers**
>
> Other differences that providers must handle:
>
> - **MongoDB numbers**: MongoDB compares 32-bit and 64-bit integers, doubles and Decimal128 as one numeric family, while UnQuery never compares different types ([`NO_COERCION`](#NO_COERCION)). A provider documents the assumption that each field holds a single numeric type, or checks the type explicitly.
> - **MongoDB objects**: MongoDB compares embedded documents by key order, while UnQuery ignores key order ([`EQUALITY_VALUES`](#EQUALITY_VALUES)). A provider that cannot compare objects without key order fails on object operands with more than one key ([`PROVIDER_EXACT_OR_FAIL`](#PROVIDER_EXACT_OR_FAIL)).
> - **Notion**: the Notion API does not document whether text conditions are case-sensitive, whether `does_not_equal` includes empty properties, or how a date without time compares with a property that has time. For complements, providers include empty properties explicitly, and fail on conditions they cannot translate exactly instead of approximating them ([`PROVIDER_EXACT_OR_FAIL`](#PROVIDER_EXACT_OR_FAIL)).
#### 1.3.1 Equality and order
**Rule `EQUALITY_VALUES`**: MUST
Equality MUST compare values by type and content: numbers by numeric value (`1` equals `1.0`), plain objects by their members without regard to order (a member whose value is `undefined` counts as missing, [`NULL_UNDEFINED`](#NULL_UNDEFINED)), and arrays element by element, in order. Values of different types, such as a JSON number and a `$bigint`, MUST NOT be equal.
**Rule `EQUALITY_NUMBERS`**: MUST
JSON numbers and ECSON `$number` values MUST be compared as one type, number. Negative zero MUST be equal to zero, and `NaN` MUST be equal to `NaN`.
**Rule `EQUALITY_ZONED`**: MUST
Two `$zoneddatetime` values MUST be equal only when their instant, time zone and calendar are equal.
> **Note (non-normative)**
>
> `$zoneddatetime` values are ordered by their instant alone ([`ORDER_TEMPORAL`](#ORDER_TEMPORAL)), so for this type `eq a` is not the same as `gte a` and `lte a`: the range also matches the same instant in other time zones. This follows `equals` and `compare` of `Temporal.ZonedDateTime`.
**Rule `EQUALITY_DECIMAL`**: MUST
Values of the BSON `$numberDecimal` type MUST be compared by numeric value, for equality and for order (`1.0` equals `1.00`), and only with other `$numberDecimal` values.
**Rule `ORDER_TYPES`**: MUST
The operand of a range operator (`gt`, `gte`, `lt`, `lte`) MUST be of an orderable type: a number (a JSON number or an ECSON `$number`), a string, a `$bigint`, a `$numberDecimal`, a `$date`, or a Temporal `$instant`, `$zoneddatetime`, `$plaindate`, `$plaindatetime`, `$plaintime`, `$plainyearmonth` or `$duration`. Any other operand, including `null`, booleans, arrays and objects, MUST make the filter fail. `-Infinity` and `Infinity` are the lowest and the highest numbers.
**Rule `ORDER_TEMPORAL`**: MUST
`$zoneddatetime` values MUST be ordered by their instant, whatever their time zone and calendar. `$duration` values MUST be ordered by their length, with days of 24 hours.
**Rule `ORDER_UNORDERABLE`**: MUST
A `$duration` with years, months or weeks, a `NaN` number or decimal and an invalid `$date` are not orderable: as the operand of a range operator they MUST make the filter fail ([`ORDER_TYPES`](#ORDER_TYPES)), and as a field value they MUST NOT match a range operator.
**Rule `TYPE_UNSUPPORTED_FAIL`**: MUST
An implementation that cannot compare values of a type as [section 1.3.1](#131-equality-and-order) requires MUST make the filter fail on a condition whose operand has that type, such as an implementation that reads `$numberDecimal` as an unknown tag ([ECSON section 7](./ecson.md#7-unknown-tags)) and cannot compare it by numeric value, or one that keeps Temporal values as opaque strings ([ECSON `TYPE_TEMPORAL_OPAQUE`](./ecson.md#TYPE_TEMPORAL_OPAQUE)) and cannot order them.
**Rule `ORDER_STRINGS`**: MUST
Range operators MUST order strings by Unicode code point, whatever the collation of the data source.
> **Note (non-normative)**
>
> Code point order is what MongoDB gives by default (binary comparison of UTF-8) and what PostgreSQL gives with the `"C"` collation in a `UTF8` database. Other data sources may need an explicit binary collation. It is not the alphabetical order of a language: `"Zé"` comes before `"Ágata"`.
> **Caution (non-normative): Strings in JavaScript**
>
> The JavaScript operators `<` and `>` compare strings by UTF-16 code units, not by code points: `"\u{1F600}" < "�"` is `true`, although U+1F600 is greater than U+FFFD. An implementation in JavaScript compares code points (for example, with `codePointAt`) to follow [`ORDER_STRINGS`](#ORDER_STRINGS) for characters above U+FFFF.
### 1.4 Core operators
**Rule `OPS_CORE`**: MUST
Every implementation MUST support the core operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`, `exists` and `like`, and the logical combinations `and`, `or`, `not` and `nor`.
| Operator | JSON syntax ([section 2](#2-json-syntax)) | Matches when the field value |
|---|---|---|
| `eq` | `@eq` | equals the operand |
| `ne` | `@ne` | does not equal the operand |
| `gt`, `gte`, `lt`, `lte` | `@gt`, `@gte`, `@lt`, `@lte` | is greater than, greater than or equal to, less than, less than or equal to the operand |
| `in` | `@in` | equals one of the values in the operand list; `in [a, b]` is equivalent to `eq a` or `eq b`, so a `null` in the list also matches missing fields ([`NULL_EQ`](#NULL_EQ)) |
| `nin` | `@nin` | equals none of the values in the operand list; the exact complement of `in` |
| `exists` | `@exists` | exists (operand `true`) or does not exist (operand `false`) |
| `like` | `@like` | is a string matching the operand pattern, where `%` matches any sequence of characters and `_` matches exactly one character, case-sensitive |
**Rule `LIKE_ESCAPE`**: MUST
In a `like` pattern, `\` followed by `%`, `_` or `\` MUST match that character literally. A `\` followed by any other character, or at the end of the pattern, MUST make the filter fail.
> **Tip (non-normative): Example**
>
> `50\%` matches the string `50%` only. In the JSON syntax, the backslash must also be escaped as JSON requires: `{ "discount": { "@like": "50\\%" } }`. In the SQL syntax: `discount LIKE '50\%'`.
### 1.5 Optional operator sets
**Rule `OPS_SETS`**: MAY
An implementation MAY support any optional operator set, in whole. Partial support of a set is not compliant with that set.
| Set | Operators |
|---|---|
| Array | `@all` (the field is an array that contains every value in the operand list), `@size` (the field is an array with exactly the operand number of elements; each nested array counts as one element), `@elemMatch` (at least one element of the array field matches the operand, [section 1.5.2](#152-array-set)) |
| Regex | `@regex` (the string field matches a regular expression, given as a string or as an ECSON `$regexp` value, [section 1.5.3](#153-regex-set)) |
| Geospatial | `@geoWithin`, `@geoIntersects`, `@near`, with [GeoJSON](https://www.rfc-editor.org/rfc/rfc7946) operands ([section 1.5.1](#151-geospatial-set)) |
**Rule `OPS_UNSUPPORTED_FAIL`**: MUST
An implementation MUST fail when a filter uses an operator it does not support, and MUST NOT ignore the condition.
> **Note (non-normative): Rationale**
>
> Some MongoDB query operators, such as `$expr`, `$mod` and `$type` with BSON type names, cannot be implemented in general by providers such as PostgreSQL, MySQL, Notion or Airtable. The core set is what every data source can evaluate; the rest are optional sets. Ignoring an unsupported condition would silently return or modify more documents than requested, so it must fail.
#### 1.5.1 Geospatial set
**Rule `GEO_GEOJSON`**: MUST
Operands of the geospatial set MUST be GeoJSON geometry objects ([RFC 7946](https://www.rfc-editor.org/rfc/rfc7946)), with positions in WGS 84 as longitude, then latitude. Distances MUST be in meters.
**Rule `GEO_GEOJSON_MEMBERS`**: MUST
Implementations MUST accept the `bbox` member and foreign members of GeoJSON objects and ignore them (RFC 7946, [section 5](https://www.rfc-editor.org/rfc/rfc7946#section-5) and [section 6.1](https://www.rfc-editor.org/rfc/rfc7946#section-6.1)).
**Rule `GEO_GEOJSON_EMPTY`**: MUST
A geometry whose `coordinates` is an empty array, or a `GeometryCollection` without geometries, MUST make the filter fail. A line with fewer than two positions or a ring with fewer than four is invalid GeoJSON ([`GEO_GEOJSON`](#GEO_GEOJSON)).
> **Note (non-normative)**
>
> [`GEO_GEOJSON_EMPTY`](#GEO_GEOJSON_EMPTY) is stricter than RFC 7946, which allows empty coordinates and empty `GeometryCollection` objects ([sections 3.1](https://www.rfc-editor.org/rfc/rfc7946#section-3.1) and [3.1.8](https://www.rfc-editor.org/rfc/rfc7946#section-3.1.8)): an empty geometry has no point to compare, so a condition on it would have no clear result.
**Rule `GEO_FIELD`**: MUST
A geospatial condition MUST match only documents whose field holds a GeoJSON geometry object. Missing fields, `null` and other values MUST NOT match.
| Operator | Operand | Matches when |
|---|---|---|
| `@geoWithin` | a `Polygon` or `MultiPolygon` | the geometry of the field lies entirely inside the operand |
| `@geoIntersects` | any geometry | the geometry of the field and the operand have at least one point in common |
| `@near` | `{ "point": , "maxDistance": , "minDistance": }`, with `maxDistance` required and `minDistance` optional (default `0`) | the distance between the geometry of the field and `point` is at least `minDistance` and at most `maxDistance` |
**Rule `GEO_OPERATORS`**: MUST
The geospatial operators MUST match as specified in the table above.
**Rule `GEO_NEAR_NO_SORT`**: MUST NOT
`@near` MUST NOT change the order of the results: like every condition, it only decides whether a document matches.
**Rule `GEO_DISTANCE`**: MUST
Distances MUST be measured on the surface of the Earth, on a sphere or on the WGS 84 spheroid.
> **Tip (non-normative): Example**
>
> `{ "location": { "@near": { "point": { "type": "Point", "coordinates": [-46.6333, -23.5505] }, "maxDistance": 2000 } } }` matches documents whose `location` is at most 2 km from the center of São Paulo.
> **Note (non-normative)**
>
> Data sources compute edges of polygons differently: GeoJSON defines a line between two positions as a straight Cartesian line ([RFC 7946, section 3.1.1](https://www.rfc-editor.org/rfc/rfc7946#section-3.1.1)), MongoDB uses spherical geometry and PostGIS `geography` uses geodesic lines. Results may differ for geometries near the edges of large polygons. Sorting by distance is out of the scope of this version.
#### 1.5.2 Array set
**Rule `ARRAY_SET_ARRAYS_ONLY`**: MUST
`@all`, `@size` and `@elemMatch` MUST NOT match a field that is missing, `null` or not an array.
**Rule `ELEM_MATCH`**: MUST
A field with `@elemMatch` MUST match when it holds an array with at least one element that matches the whole operand. When every key of the operand starts with `@`, the operand is a set of conditions applied to the element itself; otherwise the operand is a filter applied with the element as the document. [`ARRAY_SET_ARRAYS_ONLY`](#ARRAY_SET_ARRAYS_ONLY) covers fields that are not arrays.
**Rule `ELEM_MATCH_FORMS`**: MUST
In the form with only `@` keys, the operand is an operator object, as under a field path ([`JSON_OPERATOR_OBJECT`](#JSON_OPERATOR_OBJECT)): `@not` takes an operator object, and `@and`, `@or` and `@nor` MUST make the filter fail.
**Rule `ELEM_MATCH_EMPTY`**: MUST
The operand `{}` belongs to the form with only `@` keys and MUST match every array with at least one element.
**Rule `ELEM_MATCH_NON_OBJECT`**: MUST
In the filter form, an element that is not a plain object MUST be treated as an object with no fields.
**Rule `ELEM_MATCH_OPERAND`**: MUST
An operand of `@elemMatch` that is not an object MUST make the filter fail.
> **Tip (non-normative): Example**
>
> `{ "items": { "@elemMatch": { "price": { "@gt": 10, "@lt": 20 } } } }` matches `{ "items": [{ "price": 5 }, { "price": 15 }] }`, but not `{ "items": [{ "price": 5 }, { "price": 25 }] }`, because no single element has a price between 10 and 20. `{ "scores": { "@elemMatch": { "@gte": 80, "@lt": 85 } } }` matches `{ "scores": [82, 90] }`.
> **Note (non-normative)**
>
> The form depends only on the keys of the operand. `{ "@or": [...] }` has only `@` keys, so it is an operator object and fails; `{ "@or": [...], "x": 1 }` has a field key, so it is a filter ([`JSON_FILTER`](#JSON_FILTER)) and is valid. `@or` combines conditions on the fields of an element only in the filter form.
> **Note (non-normative)**
>
> `@elemMatch` follows the [MongoDB `$elemMatch` operator](https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/). Like the other operators of the Array set, it has no form in the SQL syntax.
#### 1.5.3 Regex set
**Rule `REGEX_DIALECT`**: MUST
An implementation that evaluates filters itself MUST interpret `@regex` patterns as ECMAScript regular expressions. A provider MUST apply the dialect of the regular expressions of its data source.
**Rule `REGEX_PROVIDER_PASSTHROUGH`**: MUST
A provider MUST pass the pattern to the regular expression engine of its data source unchanged, as a bound value.
**Rule `REGEX_UNSUPPORTED_FAIL`**: MUST
A provider MUST fail when its data source has no regular expressions, or cannot express a flag of the pattern that changes whether a string matches.
**Rule `REGEX_FLAGS`**: MUST
The flags `d` and `g` do not change whether a string matches and MUST be ignored: each string is matched from its start, as with `lastIndex` 0. The flag `y` MUST make the match start at the beginning of the string.
> **Tip (non-normative): Example**
>
> `/a/y` does not match `"ba"`, while `/a/` and `/a/g` do. A provider whose data source cannot anchor a pattern through an option fails on `y` ([`REGEX_UNSUPPORTED_FAIL`](#REGEX_UNSUPPORTED_FAIL)).
> **Caution (non-normative): Dialects differ**
>
> MongoDB uses [PCRE2](https://www.mongodb.com/docs/manual/reference/operator/query/regex/) (PCRE before version 6.1), PostgreSQL uses [POSIX regular expressions](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) and Notion has none. Simple patterns (literal ASCII text, `^`, `$`, `.`, `*`, `+`, `?` and bracket expressions such as `[a-z0-9]`) behave the same in strings without line breaks; patterns with other features, and any pattern on strings with line breaks, may match differently in each data source. For example, `$` in PCRE2 also matches before a final line feed, and `.` in PostgreSQL matches a line feed by default, while neither does in ECMAScript.
## 2. JSON syntax
The JSON syntax writes a filter as a JSON object. Its structure is inspired by MongoDB query documents, with one difference: operators start with `@` instead of `$`, because in the LingoData family `$` marks ECSON typed values.
### 2.1 Structure
**Rule `JSON_FILTER`**: MUST
A JSON filter MUST be a JSON object in which every key is either a field path (a condition on that field) or a logical operator: `@and`, `@or` and `@nor`, whose values are arrays of JSON filters, or `@not`, whose value is a JSON filter. Several keys in the same object are combined with `and`.
**Rule `JSON_EMPTY_LISTS`**: MUST
`@and`, `@or`, `@nor`, `@in`, `@nin` and `@all` with an empty array MUST make the filter fail.
**Rule `JSON_EMPTY_FILTER`**: MUST
The empty filter `{}` MUST match every document.
> **Note (non-normative): Rationale**
>
> An empty list is almost always a bug in the code that built the filter. Failing makes it visible instead of silently matching every document or none.
**Rule `JSON_OPERATOR_OBJECT`**: MUST
Under a field path, a JSON object whose keys all start with `@` MUST be interpreted as an operator object: each key is an operator applied to the field, and several operators are combined with `and`. `@not` under a field path takes an operator object and negates it. An object mixing keys that start with `@` and keys that do not MUST be rejected.
**Rule `JSON_IMPLICIT_EQ`**: MUST
Under a field path, any other value MUST be interpreted as the operand of `eq`.
**Rule `JSON_OPERANDS_ECSON`**: MUST
Operands MUST be decoded as ECSON values, so that typed values such as `{ "$date": "..." }` are compared as their types and escaped keys are restored.
**Rule `JSON_OPERANDS_IN_MODEL`**: MUST
An operand that is a value outside the ECSON model ([ECSON section 5.5](./ecson.md#55-values-outside-the-model)), such as a function, MUST make the filter fail, whether the filter is evaluated, translated or converted to another representation. It MUST NOT be replaced by `null` or omitted.
> **Note (non-normative): Rationale**
>
> Replacing such an operand with `null` would change the filter silently: `@eq null` matches missing fields, so the filter would return or modify more documents than requested. This differs from ECSON, which serializes values outside its model as `JSON.stringify` does ([`OUT_OF_MODEL_JSON`](./ecson.md#OUT_OF_MODEL_JSON)): an UnQuery implementation that uses an ECSON library checks operands before serializing them, and does not use that fallback.
> **Tip (non-normative): Example**
>
> ```json
> {
> "status": { "@in": ["paid", "shipped"] },
> "total": { "@gte": 100, "@lt": 1000 },
> "createdAt": { "@gte": { "$date": "2024-01-01T00:00:00.000Z" } },
> "address.city": "Recife",
> "@or": [
> { "coupon": { "@exists": true } },
> { "customer.vip": true }
> ]
> }
> ```
> This filter matches paid or shipped orders, with a total from 100 to less than 1000, created since 2024, delivered in Recife, and either with a coupon or from a VIP customer.
> **Tip (non-normative): Example: field names with spaces and dots**
>
> `{ "Customer name": "Ana", "\"Total.value\"": { "@gt": 10 } }`: the first key is a plain name with a space; the second is a quoted name, so its dot is part of the name.
> **Tip (non-normative): Example: comparing with an object**
>
> `{ "shipping": { "carrier": "acme" } }` compares the whole `shipping` field with the object `{ "carrier": "acme" }`. To compare with an object whose keys start with `@`, use an explicit operator: `{ "shipping": { "@eq": { "@id": 1 } } }`.
> **Note (non-normative): Rationale**
>
> MongoDB uses `$` for operator names. In the LingoData family, `$` already marks ECSON typed values (and ECSON must keep `$` to stay identical to MongoDB Extended JSON in its BSON type set). With `@` for operators, a reader can tell at a glance what is an operation and what is a type: in `{ "@gte": { "$date": "..." } }`, `@gte` is the operator and `$date` is the type of the operand. `@` plays the same role of reserved keyword in JSON-LD (`@id`, `@type`). MongoDB queries need `$` replaced by `@` to be reused as UnQuery filters.
## 3. SQL syntax
The SQL syntax lets filters be written as SQL `WHERE` predicates, which are compact and readable in URLs. It is a restricted grammar, not SQL: implementations parse it into the filter model ([section 1](#1-query-model)) and never send it to a database.
**Rule `SQL_PARSE`**: MUST
An implementation MUST parse SQL syntax with the grammar in this section and translate it into the filter model.
**Rule `SQL_NO_PASSTHROUGH`**: MUST NOT
An implementation MUST NOT pass SQL syntax text, in whole or in part, to a data source.
**Rule `SQL_REJECT`**: MUST
An implementation MUST fail on any input that does not match the grammar, including subqueries, function calls, comments and statements other than predicates.
### 3.1 Grammar
The grammar uses ABNF ([RFC 5234](https://www.rfc-editor.org/rfc/rfc5234)). Keywords are case-insensitive. Optional whitespace (`ws`: one or more spaces, tabs, carriage returns and line feeds) is allowed between tokens; the grammar shows `ws` only where it is required. Inside strings, `''` represents one `'`.
**Rule `SQL_KEYWORD_BOUNDARY`**: MUST NOT
A keyword MUST NOT be immediately preceded or followed by a letter, a digit, `_` or `-`: `a=1ORb=2` is invalid, while `a='x'OR b=2` is valid.
**Rule `SQL_QUOTED_NAMES`**: MUST
Field paths follow [`PATH_DOT_NOTATION`](#PATH_DOT_NOTATION) ([section 1.2](#12-field-paths)), except that a field name (the `name` of a segment, not counting its indexes) that contains characters other than letters, digits, `_` and `-`, or that is equal to a keyword (such as `AND` or `IN`), MUST be quoted: `"Customer name" = 'Ana'`, `items[0].price > 10`.
```abnf
filter = or-expr
or-expr = and-expr *( "OR" and-expr )
and-expr = not-expr *( "AND" not-expr )
not-expr = "NOT" not-expr / primary
primary = "(" filter ")" / predicate
predicate = field tail
tail = comp-op literal
/ [ "NOT" ] "IN" "(" literal *( "," literal ) ")"
/ [ "NOT" ] "BETWEEN" literal "AND" literal
/ [ "NOT" ] "LIKE" string
/ "IS" [ "NOT" ] "NULL"
comp-op = "=" / "!=" / "<>" / ">=" / ">" / "<=" / "<"
field = sql-segment *( "." sql-segment )
sql-segment = ( 1*( ALPHA / DIGIT / "_" / "-" ) / quoted ) *index ; quoted, index: section 1.2
literal = string / number / "TRUE" / "FALSE" / "NULL"
/ "TIMESTAMP" ws string / "DATE" ws string
string = "'" *( %x20-26 / %x28-7E / "''" / non-ascii ) "'"
number = [ "-" ] 1*DIGIT [ "." 1*DIGIT ] [ ( "e" / "E" ) [ "+" / "-" ] 1*DIGIT ]
non-ascii = %x80-D7FF / %xE000-10FFFF ; Unicode scalar values, encoded as UTF-8
ws = 1*( WSP / CR / LF )
```
### 3.2 Mapping to the filter model
| SQL syntax | Filter model |
|---|---|
| `f = v`, `f != v`, `f <> v` | `eq`, `ne` |
| `f > v`, `f >= v`, `f < v`, `f <= v` | `gt`, `gte`, `lt`, `lte` |
| `f IN (a, b)`, `f NOT IN (a, b)` | `in`, `nin` |
| `f BETWEEN a AND b` | `and` of `gte a` and `lte b` |
| `f NOT BETWEEN a AND b` | `not` of the above |
| `f LIKE p`, `f NOT LIKE p` | `like`, `not` of `like` |
| `f IS NULL`, `f IS NOT NULL` | `eq null`, `ne null` |
| `f = NULL`, `f != NULL`, `f <> NULL` | `eq null`, `ne null` |
| `f > NULL` and other ranges with `NULL` | invalid ([`ORDER_TYPES`](#ORDER_TYPES)) |
| `AND`, `OR`, `NOT` | `and`, `or`, `not` |
### 3.3 Typed literals
**Rule `SQL_TYPED_LITERALS`**: MUST
`TIMESTAMP ''` MUST be interpreted as an ECSON `$date` whose string form is `` (RFC 3339), and `DATE ''` as an ECSON `$plaindate` whose string form is ``.
**Rule `SQL_TYPED_LITERAL_INVALID`**: MUST
A typed literal whose value does not satisfy the ECSON type definition ([ECSON `TYPEDEF_VALIDATE`](./ecson.md#TYPEDEF_VALIDATE), with [`TYPE_DATE_READ_STRICT`](./ecson.md#TYPE_DATE_READ_STRICT) for `$date`) MUST make the filter fail.
> **Tip (non-normative): Example**
>
> `createdAt >= TIMESTAMP '2024-01-15T00:00:00.000Z'` compares dates; `createdAt >= '2024-01-15'` compares strings and, under [`NO_COERCION`](#NO_COERCION), does not match date values.
> **Tip (non-normative): Example**
>
> `status IN ('paid', 'shipped') AND total >= 100` is the filter `and( in(status, ["paid", "shipped"]), gte(total, 100) )`.
> **Note (non-normative): Rationale**
>
> Passing SQL expressions "as-is" to a database and protecting it against SQL injection cannot both hold, and operators such as `EXISTS`, `ANY`, `ALL` and `SOME` need subqueries. A closed grammar keeps the convenience of SQL predicates in URLs and removes injection by design, because no input text reaches a database.
## 4. Query string mapping
In a URL query string, keys starting with `@` are control parameters, and every other key is a condition on one field: the key is the field path and the value is the condition.
### 4.1 Decoding
**Rule `QS_DECODE`**: MUST
Keys and values MUST be interpreted after decoding the query string with the `application/x-www-form-urlencoded` parser of the [WHATWG URL Standard](https://url.spec.whatwg.org/#application/x-www-form-urlencoded), so that `%40sort` and `@sort` are the same key and `+` is a space.
### 4.2 Keys
**Rule `QS_CONTROL_PREFIX`**: MUST
A key starting with `@` MUST be interpreted as a control parameter, never as a field condition. Control parameters are defined by this specification (`@q`) or by the specification of the protocol that uses UnQuery.
**Rule `QS_CONTROL_UNKNOWN`**: MUST
A key starting with `@` that is not a defined control parameter MUST NOT be interpreted as a condition. An implementation MUST report it as an error, unless the protocol specification that uses UnQuery defines another handling, such as reporting it as a warning.
**Rule `QS_KEY_PATH`**: MUST
Any other key MUST be a field path as defined in [`PATH_DOT_NOTATION`](#PATH_DOT_NOTATION), and an implementation MUST fail on keys that are not, except for keys in its ignore list ([`QS_IGNORE_LIST`](#QS_IGNORE_LIST)).
**Rule `QS_IGNORE_LIST`**: MAY
An implementation MAY exclude keys from filtering, either because it is configured with a list of keys to ignore (such as `utm_source`) or because the protocol specification that uses UnQuery assigns them another meaning (such as the parameters of a saved query). Excluded keys are neither conditions nor errors.
> **Note (non-normative): Rationale**
>
> Field paths never start with `@` ([`PATH_DOT_NOTATION`](#PATH_DOT_NOTATION)), so control parameters cannot collide with fields, without any list of reserved names. The same convention is used by the JSON syntax, where `@` marks operators, and across the LingoData family, where `@` marks operations and control and `$` marks types. OData follows the same pattern with `$` (`$filter`, `$orderby`). Reporting unknown `@` keys turns typos such as `@srot` into errors (or warnings, when the protocol prefers) instead of silently ignored parameters.
> **Tip (non-normative): Example**
>
> ```
> /orders?status=paid&total=>100&@sort=-createdAt&@limit=20
> ```
> `status` and `total` are conditions; `@sort` and `@limit` are control parameters defined by the protocol (for example, the CRUD API HTTP protocol).
### 4.3 Values
Values are interpreted by trying each syntax in order, so that common cases need no extra characters.
**Rule `QS_VALUE_ORDER`**: MUST
A query string value MUST be interpreted as the first of the following that parses successfully: (1) a JSON text (RFC 8259); (2) a SQL syntax predicate tail, that is, the `tail` rule of [section 3.1](#31-grammar) with the key as the field; (3) otherwise, a string literal. Forms (1) and (3) are conditions with the `eq` operator, unless the JSON text is an operator object ([section 2](#2-json-syntax)).
**Rule `QS_VALUE_COMMITTED`**: MUST
Once a value parses as a JSON text, or as a SQL syntax predicate tail, any later error, such as a mixed operator object, an unknown operator, an invalid ECSON value or an invalid typed literal, MUST make the filter fail. The value MUST NOT fall back to the next form.
> **Note (non-normative): Rationale**
>
> Falling back to a string literal would turn a mistyped condition into an equality with a text that matches nothing, or with something other than intended, without any error.
| Query string | Condition |
|---|---|
| `?age=30` | `eq(age, 30)`, a number |
| `?active=true` | `eq(active, true)`, a boolean |
| `?name=Ana` | `eq(name, "Ana")`, a string |
| `?zip="01234"` | `eq(zip, "01234")`, a string (quoted JSON) |
| `?zip=01234` | `eq(zip, "01234")`, a string (not valid JSON, not SQL) |
| `?age=BETWEEN 18 AND 30` | `and(gte(age, 18), lte(age, 30))` |
| `?status=IN ('paid', 'shipped')` | `in(status, ["paid", "shipped"])` |
| `?total={"@gte":100}` | `gte(total, 100)`, an operator object ([section 2](#2-json-syntax)) |
| `?deletedAt=null` | `eq(deletedAt, null)`: null or missing |
| `?address.city=Recife` | `eq(address.city, "Recife")` |
| `?Customer%20name=Ana` | `eq("Customer name", "Ana")` |
| `?%22Total.value%22=%3E10` | `gt("Total.value", 10)` |
> **Note (non-normative): Percent-encoding**
>
> `@` and `$` are allowed in query strings by RFC 3986, as are field names made of letters, digits, `_`, `-` and `.`. Characters such as spaces, `"`, `[`, `]`, `{` and `}` are not, so clients MUST percent-encode keys and values as required by [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986): `?total={"@gte":100}` is sent as `?total=%7B%22@gte%22:100%7D`, `?Customer name=Ana` as `?Customer%20name=Ana`, and `?"Total.value"=>10` as `?%22Total.value%22=%3E10`.
> **Caution (non-normative): Typed values from strings**
>
> Because JSON is tried first, `?zip=12345` is the number `12345`, while `?zip=01234` is the string `"01234"`. Under [`NO_COERCION`](#NO_COERCION), the number does not match a string stored as `"12345"`. Clients SHOULD quote values that must be strings and look like JSON scalars (numbers, `true`, `false`, `null`): `?zip="12345"`, `?name="null"`.
> **Note (non-normative): Rationale**
>
> Writing `?age=30` for a number is easier than any explicit marker. The cost is the case above, which only affects strings that look like numbers, booleans or `null`, and has an explicit solution (quoting). Typos that stop a value from parsing as JSON or as a SQL predicate tail fall back to a string literal; the failure mode is a filter that matches fewer documents, never more. Once a value parses, any later error fails the filter ([`QS_VALUE_COMMITTED`](#QS_VALUE_COMMITTED)).
### 4.4 Combining conditions
**Rule `QS_COMBINE_AND`**: MUST
All conditions in a query string, including repeated keys and the filter in `@q`, MUST be combined with `and`.
> **Tip (non-normative): Example**
>
> `?age=>18&age=<30` is `and(gt(age, 18), lt(age, 30))`. Alternatives are written with `@in`, `IN` or `@or`, never with repeated keys.
> **Note (non-normative)**
>
> An empty value is a string literal: `?nickname=` is `eq(nickname, "")`.
### 4.5 Control parameter `@q`
`@q` carries a complete filter, for conditions that per-key parameters cannot express, such as `or` across fields, or fields whose names would need escaping.
**Rule `QS_Q_FILTER`**: MUST
The value of `@q` MUST be interpreted as the first of the following that parses successfully: (1) a JSON filter ([section 2](#2-json-syntax)); (2) a SQL syntax filter (the `filter` rule of [section 3.1](#31-grammar)). An implementation MUST fail if neither parses.
> **Tip (non-normative): Example**
>
> ```
> /orders?@q=status = 'paid' OR total > 100&createdAt=>= TIMESTAMP '2024-01-01T00:00:00.000Z'
> /orders?@q={"@or":[{"status":"paid"},{"total":{"@gt":100}}]}
> ```
> Both filters are combined with the other conditions with `and`.
> **Note (non-normative): Rationale**
>
> If `@q` took precedence over the other keys, they would be silently ignored and responses could include more documents than requested. Combining with `and` makes `@q` composable. Unlike per-key values, `@q` has no string-literal fallback, because a bare string is not a complete filter.
## 5. Security
Filters come from clients and must be treated as untrusted input.
### 5.1 Translation to data sources
**Rule `SEC_BOUND_PARAMETERS`**: MUST
When translating a filter to a query language, a provider MUST pass operands as bound parameters (or the equivalent mechanism of the data source) and MUST NOT concatenate operands into query text.
**Rule `SEC_QUOTE_FIELDS`**: MUST
A provider MUST validate field paths with [`PATH_DOT_NOTATION`](#PATH_DOT_NOTATION) and quote them as identifiers of the target query language.
> **Tip (non-normative): Example**
>
> `eq(status, "paid")` becomes `WHERE "status" = $1` with `$1 = 'paid'` in PostgreSQL, never `WHERE status = 'paid'` built as text.
### 5.2 Resource limits
**Rule `SEC_LIMITS`**: MAY
An implementation MAY limit the nesting depth of filters, the number of conditions, the size of `@in` and `@nin` lists and the complexity of regular expressions, measured for example by the length of the pattern or by nested quantifiers.
**Rule `SEC_LIMITS_FAIL`**: MUST
When a limit is exceeded, the implementation MUST fail and MUST NOT truncate or simplify the filter.
> **Note (non-normative): Rationale**
>
> Regular expressions with nested quantifiers can take exponential time to evaluate (ReDoS), and very large or deep filters can exhaust a data source. Truncating a filter would silently return documents that the client did not ask for.
### 5.3 Access to fields
**Rule `SEC_HIDDEN_FIELDS`**: SHOULD
A server SHOULD reject conditions on fields that the client is not allowed to read.
> **Note (non-normative): Rationale**
>
> Filtering reveals information even when a field is not returned: by counting the results of `salary > 10000`, `salary > 20000` and so on, a client can infer a hidden salary. Filters narrow results; they do not replace the access control of the server, which applies its own restrictions independently.
## 6. Conformance and media types
### 6.1 Conformance
| Level | Requirements |
|---|---|
| **Core** | All rules in sections 1 to 5, the JSON and SQL syntaxes, the query string mapping and the core operators |
| **Operator set** | Core, plus every operator of one optional set ([section 1.5](#15-optional-operator-sets)), for example "Core + Array" |
**Rule `CONFORMANCE_DECLARE`**: MUST
An implementation MUST state that it meets the core level and which optional operator sets it supports.
### 6.2 Media types
Protocols that negotiate the search query format, such as the CRUD API, identify UnQuery filters with these media types.
**Rule `MEDIA_TYPES`**: SHOULD
UnQuery filters exchanged over protocols that carry media types SHOULD be labeled `application/vnd.unquery+json` when written in the JSON syntax and `text/vnd.unquery.sql` when written in the SQL syntax.
> **Note (non-normative)**
>
> The `+json` suffix ([RFC 6839](https://www.rfc-editor.org/rfc/rfc6839)) tells generic clients that the content is JSON. The vendor tree (`vnd.`) does not require standardization.
### 6.3 Versioning
**Rule `SPEC_SEMVER`**: MUST
This specification MUST be versioned independently of the other specifications of the LingoData family, following [Semantic Versioning 2.0.0](https://semver.org/).
> **Note (non-normative)**
>
> While this specification is in a `0.x` version, any release may contain incompatible changes, as allowed by Semantic Versioning. Version `1.0.0` is reserved for when the reference implementation and the conformance test suite validate the specification.
## 7. References
### 7.1 Normative references
- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): requirement level key words (BCP 14)
- [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339): Date and Time on the Internet: Timestamps
- [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986): Uniform Resource Identifier (URI): Generic Syntax
- [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259): The JavaScript Object Notation (JSON) Data Interchange Format
- [RFC 5234](https://www.rfc-editor.org/rfc/rfc5234): Augmented BNF for Syntax Specifications (ABNF)
- [RFC 7946](https://www.rfc-editor.org/rfc/rfc7946): The GeoJSON Format
- [RFC 6839](https://www.rfc-editor.org/rfc/rfc6839): Additional Media Type Structured Syntax Suffixes
- [WHATWG URL Standard](https://url.spec.whatwg.org/): `application/x-www-form-urlencoded` parsing
- [ECSON](https://github.com/lingodata/ecson): ECMAScript Object Notation (LingoData)
- [ECMA-262](https://tc39.es/ecma262/): ECMAScript Language Specification, for regular expressions ([section 1.5.3](#153-regex-set))
- [The Unicode Standard](https://www.unicode.org/versions/latest/): code points and scalar values
### 7.2 Informative references
- [MongoDB query operators](https://www.mongodb.com/docs/manual/reference/operator/query/)
- [PCRE2 pattern syntax](https://www.pcre.org/current/doc/html/pcre2pattern.html) and [PostgreSQL POSIX regular expressions](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP): regular expression dialects of data sources
- [ISO/IEC 9075](https://www.iso.org/standard/63555.html): SQL
- [OData URL conventions](https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html): system query options with a reserved prefix
- [MongoDB geospatial query operators](https://www.mongodb.com/docs/manual/reference/operator/query-geospatial/) and [PostGIS `ST_DWithin`](https://postgis.net/docs/ST_DWithin.html): geospatial filters in data sources
- [MongoDB `$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/): conditions on one array element
- [qs](https://github.com/ljharb/qs): a query string parser that reads bracket keys as arrays and nested objects
---
# CRUD API Base Specification
Version: 0.2.0 · Status: draft · License: Apache-2.0
Source: lingodata/crud@bc225ba
## 1. Overview
The **CRUD API Base Specification** establishes a foundation for APIs that manage Resources through Create, Retrieve, Update and Delete operations. It defines operations, rules and a universal architecture independent of the protocol and of the data source.
The Base Specification is part of the **LingoData** family of specifications for data interoperability. It is derived into protocol specifications, such as HTTP and MCP, and complemented by optional extensions, such as asynchronous operations, Resource metadata and relationships. Within the family, Resources are represented in [ECSON](https://github.com/lingodata/ecson) and searched with [UnQuery](https://github.com/lingodata/unquery).
This specification consolidates rules and conventions from existing standards, common enterprise patterns and public APIs, while introducing some opinionated conventions to create a single source of truth (see [section 5](#5-origins-and-references)).
Although this document follows the IETF style, it is not an Internet Standards Track document (RFC), and it is not affiliated with any standards organization yet, including IETF, IANA, WHATWG, IEEE or ISO.
### 1.1 Conventions
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)) when, and only when, they appear in all capitals, as shown here.
Normative rules are identified by a code (for example [`ID_KEY`](#ID_KEY)). Notes, examples and rationales are informative.
### 1.2 Versioning
**Rule `SPEC_SEMVER`**: MUST
This specification and every extension and protocol specification derived from it MUST be versioned independently, following [Semantic Versioning 2.0.0](https://semver.org/).
**Rule `SPEC_BASE_RANGE`**: MUST
Every extension and protocol specification MUST declare the range of Base Specification versions it supports, as a SemVer range (for example `^0.2.0`).
> **Note (non-normative)**
>
> While a specification is in a `0.x` version, any release may contain incompatible changes, as allowed by Semantic Versioning. Version `1.0.0` is reserved for when the reference implementation and the conformance test suite validate the specification.
## 2. Terminology
### 2.1 CRUD Definition
**"CRUD"** is an acronym popularized in the early 1980s that encompasses two kinds of operations applied to Resources:
1. **Read operations**, such as querying, extracting and aggregating Resources;
2. **Write operations**, which change the current state of Resources.
### 2.2 Anatomy and behavior of a CRUD operation
A **CRUD operation** is made of:
```mermaid
classDiagram
direction LR
class Input
Input : Subject
Input : Parameters
Input : Metadata
class Output
Output : Result
Output : Metadata
Input --> Output : produces
```
- **Input:** data used to perform the operation, broken down into:
- **Subject:** the data the operation requires, such as Resources, Search Queries or Resource IDs;
- **Parameters:** optional data that changes the behavior of the operation, such as sorting, projection and pagination; and
- **Metadata:** data about the exchange itself, such as content negotiation (content type, encoding, serialization), operation metadata and Client and Server capabilities.
- **Output:** data returned by the operation, made of:
- **Result:** the result data, whether Resources, an error or nothing; and
- **Metadata:** the same kinds of metadata as the Input.
A CRUD operation involves the following **Participants**:
```mermaid
sequenceDiagram
Client->>Protocol: sends Input via
activate Protocol
Protocol-->>Server: requests to
Server->>Data source: performs operation in (through a Provider)
activate Server
Data source->>Server: returns Result
deactivate Server
Server-->>Protocol: responds using
Protocol->>Client: returns Output to
deactivate Protocol
```
- **Client**: the Participant that initiates the operation with standardized Input, for example a web server writing to a database or a mobile app requesting data from a web API.
- **Protocol**: the protocol that carries the Input to the Server and the Output back to the Client, such as HTTP or MCP, as defined by a protocol specification.
- **Server**: the Participant that performs the operation and returns the standardized Output, for example a web API or a database library that complies with this specification.
- **Data source**: where the Resources live and the operation is performed, such as a database, a file system or another API.
- **Provider**: the component of the Server that translates operations to a specific Data source.
### 2.3 The CRUD verbs
This specification defines a set of verbs that goes beyond the traditional CRUD acronym, as HTTP methods already do. "Retrieve" and "Update" are ambiguous and are split into distinct actions: `get` and `list`, `patch` and `replace`.
Given a Collection, the **CRUD verbs** are:
| Verb | Type | Description |
|---|---|---|
| `get` | Read | Retrieves a single Resource |
| `list` | Read | Lists Resources, optionally filtered by a Search Query (extensions, such as Views, may combine and process the result data) |
| `create` | Write | Creates one or many Resources |
| `patch` | Write | Updates Fields of one or many Resources |
| `replace` | Write | Fully replaces one or many Resources, with upsert capability |
| `delete` | Write | Removes one or many Resources |
### 2.4 The CRUD operations
Each verb is executed differently depending on the **Subject**, so the verbs are derived into the following **operations**, suffixed with the Subject type when a verb has more than one:
| Operation | Verb | Subject |
|---|---|---|
| `get` | `get` | The Resource ID |
| `list` | `list` | Nothing; or a Search Query |
| `create` | `create` | One or many Resources |
| `clone` | `create` | The Resource ID of a source Resource (+ an optional patch) |
| `patchById` | `patch` | The Resource ID + a patch |
| `patchByQuery` | `patch` | A Search Query + a patch |
| `replaceById` | `replace` | The Resource ID + a Resource |
| `replaceByQuery` | `replace` | A Search Query + a Resource |
| `deleteById` | `delete` | The Resource ID |
| `deleteByQuery` | `delete` | A Search Query |
| `listByView` | `list` | A View name ([Views extension](./crud/views.md#14-execution-operation-listbyview)) |
### 2.5 Resources
Each term below is used consistently in this specification. Synonyms used by other tools are listed so readers can map them; they are not used in the rules.
- **Resource**: a data object uniquely identified within a Collection. Also called document, record, row, item or object.
- **Collection**: a set of Resources, identified by a Slug. A Collection does not imply a schema: Resources in the same Collection may have different Fields. Also called resource type, entity, table or database.
- **Field**: a key-value pair of a Resource. Also called property, attribute or column.
- **Resource ID**: the value, made of one or more Fields, that uniquely identifies a Resource within its Collection ([section 3.1.3](#313-resource-ids)).
- **Resource Representation**: the format, encoding and serialization used to transport a Resource during an operation, which may differ from how it is stored ([section 3.1.4](#314-resource-representation)).
> **Note (non-normative): Rationale**
>
> "Resource" follows [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110), which distinguishes a resource from its representation.
### 2.6 General terminology
In addition to the terms above, this specification uses:
- **Slug**: An alphanumeric string in the format `^[a-zA-Z0-9_-]+$`, preferably lowercase.
- **`uuid-hex`**: A UUID represented in its **standard string format ([RFC 9562, section 4](https://www.rfc-editor.org/rfc/rfc9562#section-4))** (hexadecimal, lowercase, hyphens).
- **`uuid-base64url`**: A UUID byte array represented as a base64url-encoded string ([RFC 4648, section 5](https://www.rfc-editor.org/rfc/rfc4648#section-5)). Note that `base64url` replaces the 62nd and 63rd characters with `-` and `_` to make the encoding URL and filename safe.
## 3. General rules and definitions
This section defines rules and definitions that apply to many or all CRUD operations.
### 3.1 Resources
Resources, Collections, Fields, Resource IDs and Resource Representations are defined in [section 2.5](#25-resources).
#### 3.1.1 Collections
**Rule `COLLECTION_SLUG`**: MUST
Collections in the same CRUD API MUST be uniquely identified by [Slugs](#26-general-terminology), regardless of language-specific typing or naming.
**Rule `COLLECTION_NOT_FOUND`**: MUST
An operation on a Collection that does not exist MUST fail with the [`NOT_FOUND`](#NOT_FOUND) error, except as allowed by [`COLLECTION_CREATE_IMPLICIT`](#COLLECTION_CREATE_IMPLICIT).
**Rule `COLLECTION_CREATE_IMPLICIT`**: MAY
A Server MAY create a Collection implicitly on the first `create` operation on it. A Server that does so MUST declare it.
> **Note (non-normative)**
>
> Schemaless Data sources, such as MongoDB, create collections on the first insert; others, such as relational databases, Notion or Airtable, cannot.
> **Note (non-normative)**
>
> This specification does not define schemas nor the discovery of Collections. Both are defined by the optional [Schema extension](./crud/schema.md#1-schemas), which no other specification depends on.
#### 3.1.2 Fields
**Rule `FIELDS_CAMEL_CASE`**: SHOULD
Fields in the same Collection SHOULD be formatted in camelCase.
**Rule `FIELDS_NAMES`**: MUST
A Field name MUST be a non-empty string. It MAY contain any character, including spaces and `.`, subject to [`FIELDS_NO_PREFIXES`](#FIELDS_NO_PREFIXES); nested Fields are addressed with the field path syntax of [UnQuery](https://github.com/lingodata/unquery) ([`PATH_DOT_NOTATION`](./unquery.md#PATH_DOT_NOTATION)), which defines how names with special characters are quoted.
> **Note (non-normative): Rationale**
>
> Data sources such as spreadsheets, Notion and Airtable often use names like `Customer name` or `Total.value`. Accepting them lets Providers expose existing data without renaming Fields; [`FIELDS_CAMEL_CASE`](#FIELDS_CAMEL_CASE) still recommends simple names for new APIs.
**Rule `FIELDS_NO_PREFIXES`**: MUST NOT
Field names MUST NOT start with `$` or `@`. In the LingoData family, `$` marks ECSON typed values and `@` marks operators and control parameters.
**Rule `FIELDS_RESERVED`**: MUST
Fields defined by this specification or by an extension, such as `_id`, are reserved and MUST be used only with the meaning defined for them. Other Field names MAY start with `_`.
**Rule `FIELDS_EXTENSION_RESERVED`**: SHOULD
Extensions that define reserved Fields SHOULD name them with a leading `_`, and MUST list them explicitly.
> **Note (non-normative): Rationale**
>
> With the ECSON escape convention, a Field named `$x` travels as `$$x`, and a Resource with a single Field `$meta` would read as a typed value. Metadata is carried by each Protocol (for example, HTTP headers and the MCP `_meta` object) and relationships use the ECSON `$rel` type, so Fields need no `$`. Many systems and libraries use `_` for their own Fields, so only the Fields explicitly defined by the specifications are reserved.
#### 3.1.3 Resource IDs
**Rule `ID_KEY`**: MUST
The `_id` field MUST be used to uniquely identify a Resource following the [Section 3.1.3 Resource IDs specs](#313-resource-ids) below, except when it is a composite key.
**Rule `ID_SLUG`**: MUST
A Resource ID MUST be represented as a [Slug](#26-general-terminology), except when it is a composite key.
> **Tip (non-normative): Example**
>
> Valid Resource IDs: `0190a5f2-7c3e-7b1a-9f4e-2d8c6b1e4a90` (a UUIDv7 in `uuid-hex`), `AZCl8nw-exqfTi2MaxXkqQ` (the same UUID in `uuid-base64url`), `pt-br`, `order_1042`. Invalid: `order 1042` (space), `josé` (non-ASCII letter), `@views` (starts with `@`).
**Rule `ID_UUID`**: SHOULD
A Resource ID SHOULD be a UUID version 7 ([RFC 9562, section 5.7](https://www.rfc-editor.org/rfc/rfc9562#section-5.7)), represented in the `uuid-hex` format.
**Rule `ID_UUID_BASE64URL`**: MAY
A UUID Resource ID MAY be represented in the [`uuid-base64url`](#26-general-terminology) format instead.
> **Note (non-normative): Rationale**
>
> UUIDv7 starts with a millisecond timestamp, so IDs are ordered by creation time, which keeps database indexes compact; RFC 9562 itself recommends it over versions 1 and 6. The `uuid-hex` format keeps that order when IDs are compared as strings, which is how many data sources store them; `uuid-base64url` is shorter (22 characters instead of 36) but its alphabet does not follow ASCII order, so string order no longer matches creation order.
**Rule `ID_COMP_KEY_URLENCODED`**: MUST
Resource IDs made of many Fields (a.k.a. “composite keys”) MUST be represented in the format [`application/x-www-form-urlencoded`](https://url.spec.whatwg.org/#application/x-www-form-urlencoded).
#### 3.1.4 Resource representation
**Rule `REPR_JSON`**: MUST
A Resource Representation MUST be valid JSON ([RFC 8259](https://www.rfc-editor.org/rfc/rfc8259)). Servers SHOULD accept [JSON5](https://spec.json5.org/) input, as [recommended by ECSON](./ecson.md#82-json5-input).
**Rule `REPR_ECSON`**: SHOULD
Resources SHOULD be represented in [ECSON](https://github.com/lingodata/ecson) (`application/vnd.ecson+json`), to preserve types between Client and Server.
**Rule `REPR_ECSON_CUSTOM_TYPES`**: MAY
Servers MAY use application-defined ECSON types, following the [ECSON tag namespace rules](./ecson.md#6-tag-ownership-and-namespaces).
Resources are made of values of the types defined by ECSON (dates, big integers, references and others). ECSON is how those values travel without loss; it is not how they are stored ([ECSON section 5.2](./ecson.md#52-processing-limits)).
**Rule `REPR_PLAIN_JSON`**: MUST
When the negotiated Resource Representation is plain JSON, the Server MUST send values in their plain JSON form ([ECSON section 5.3](./ecson.md#53-plain-json-form)) and MUST read request bodies as plain JSON ([ECSON `PLAIN_FORM_READ`](./ecson.md#PLAIN_FORM_READ)).
**Rule `REPR_NO_CONVERSION`**: MUST NOT
The Server MUST NOT convert values read as plain JSON to other types, unless an extension defines the conversion (for example, the [Schema extension](./crud/schema.md#1-schemas)).
**Rule `REPR_NATIVE_STORAGE`**: MUST
Providers MUST store values in the native types of the Data source, and MUST NOT store their ECSON serialization.
**Rule `REPR_DOWNGRADE`**: MUST
When the Data source has no native type for a value, the Provider MUST store its plain JSON form, and the Server MUST report the [`TYPE_DOWNGRADED`](#TYPE_DOWNGRADED) Warning, with the `field`.
> **Tip (non-normative): Example**
>
> A date is stored as a `Date` in MongoDB, a `timestamptz` in PostgreSQL, a `DATETIME` in MySQL and a date property in Notion or a date field in Airtable. A `$set` sent to a Notion number property has no native equivalent: it is stored in its plain JSON form, with the [`TYPE_DOWNGRADED`](#TYPE_DOWNGRADED) Warning.
**Rule `REPR_NO_ENVELOPES`**: MUST
Resources MUST NOT be wrapped in envelopes such as `data`, `result`, `response`, or similar constructs. Operation Inputs and Outputs MUST always directly reflect Resources, optional Parameters (as defined by the Protocol), or errors.
### 3.2 Search queries
#### 3.2.1 Definition and representation
A "**Search Query**" is a filter that selects Resources in some operations, written in a format negotiated between Client and Server.
**Rule `SEARCH_QUERY_UNQUERY`**: SHOULD
Servers SHOULD support Search Queries in the [UnQuery](https://github.com/lingodata/unquery) format, in both its JSON (`application/vnd.unquery+json`) and SQL (`text/vnd.unquery.sql`) syntaxes.
**Rule `SEARCH_QUERY_FORMATS`**: MAY
Servers MAY support other Search Query formats, such as the native query language of a Data source, identified by media types and negotiated as specified in [section 3.4.1](#341-content-negotiation).
> **Caution (non-normative): Native query languages**
>
> A Server that accepts the native query language of its Data source ties its Clients to that Data source and must protect it against injection itself. UnQuery avoids both by translating filters instead of passing text to the Data source.
> **Note (non-normative): Rationale**
>
> UnQuery is recommended, not required, so that Servers can adopt the Base Specification with other query formats.
> **Note (non-normative)**
>
> Saved queries (Views) are defined by the Views extension.
### 3.3 Parameters
This section defines Parameters that apply to several operations. Parameters specific to one operation are defined in [section 4](#4-operation-rules). Each Protocol defines how Parameters are sent.
#### 3.3.1 Field lists
Projection and sorting Parameters take a **field list**: an ordered list of field paths, each with a modifier (omit, for projection; descending, for sorting).
**Rule `FIELD_LIST_PATHS`**: MUST
Each item of a field list MUST be a field path as defined by [UnQuery](https://github.com/lingodata/unquery) ([`PATH_DOT_NOTATION`](./unquery.md#PATH_DOT_NOTATION)), so that nested Fields use dot notation and names with special characters are quoted.
**Rule `FIELD_LIST_NO_INDEX`**: MUST
This specification does not define array indexes ([UnQuery `PATH_INDEX`](./unquery.md#PATH_INDEX)) in field lists. The Server MUST fail with the [`INVALID_INPUT`](#INVALID_INPUT) error for a field list with an item that has an index.
**Rule `FIELD_LIST_TEXT`**: MUST
When a field list is written as text, items MUST be separated by `,` and the modifier MUST be a `-` before the path; segments that contain `,` or start with `-` MUST be quoted. Protocols MAY use other forms, such as JSON arrays, with the same meaning.
> **Tip (non-normative): Example**
>
> `name,-"Total.value",address.city` lists `name`, `Total.value` (with the modifier) and `city` inside `address`.
#### 3.3.2 Projection parameter
A "**Projection Parameter**" selects which Fields are returned in the Result.
**Rule `PROJECTION_FIELD_LIST`**: MUST
A Projection Parameter MUST be a field list, where the `-` modifier omits a Field.
**Rule `PROJECTION_INCLUDE_DEFAULT`**: MUST
When a Projection Parameter has no omitted Fields, only the listed Fields MUST be returned.
**Rule `PROJECTION_EXCLUDE`**: MUST
When a Projection Parameter has only omitted Fields, every other Field MUST be returned.
**Rule `PROJECTION_HYPHEN_OMITS`**: MUST
When a Projection Parameter has both listed and omitted Fields, the Server MUST first select the listed Fields and then remove the omitted ones.
**Rule `PROJECTION_ID`**: MUST
The Resource ID MUST always be returned, unless the Projection Parameter omits it explicitly (for example `-_id`).
> **Tip (non-normative): Example**
>
> | Projection | Returned Fields |
> |---|---|
> | `name,address` | `_id`, `name`, `address` |
> | `-password` | every Field except `password` |
> | `address,-address.zip` | `_id` and `address` without `zip` |
> | `name,-_id` | `name` only |
#### 3.3.3 Custom parameters
A "**Custom Parameter**" is a Parameter defined by a Server and not by this specification.
**Rule `PARAM_CUSTOM_DECLARE`**: SHOULD
A Server SHOULD declare the Custom Parameters it accepts and the operations they apply to.
**Rule `PARAM_CUSTOM_UNKNOWN`**: MUST
When a Client sends a Parameter that the Server does not recognize, the Server MUST ignore it and report the [`PARAM_IGNORED`](#PARAM_IGNORED) Warning. If the Client asked for Warnings to be treated as errors ([`META_WARN_PREFERENCE`](#META_WARN_PREFERENCE)), the operation MUST fail.
> **Note (non-normative): Rationale**
>
> Failing on every unknown Parameter would break Clients whenever a Server removes a Custom Parameter; ignoring them silently would hide typos. Reporting them as Warnings keeps operations working and lets strict Clients opt in to failures.
### 3.4 Metadata
Operation "**Metadata**" is data exchanged between Client and Server about the operation itself: content negotiation, specification versions, counts, correlation and warnings. Each Protocol defines how Metadata is carried (for example, HTTP headers or the MCP `_meta` object).
#### 3.4.1 Content negotiation
"**Content negotiation**" is the exchange of Metadata in which Client and Server agree on the formats of the Input and the Output: the Resource Representation and the Search Query format.
**Rule `META_RES_PREFERENCE`**: SHOULD
The Client SHOULD declare the Resource Representations and Search Query formats it accepts. The Server MUST either use one of them or fail the operation with the [`NEGOTIATION`](#NEGOTIATION) error.
**Rule `META_RES_FALLBACK`**: MUST
When the Client declares no Resource Representation, the Server MUST respond in ECSON if it supports ECSON, and in JSON otherwise. When the Client declares no Search Query format, the Server MUST interpret Search Queries as UnQuery if it supports UnQuery.
**Rule `META_RES_TIE`**: MUST
When the Client accepts both ECSON and plain JSON with the same preference, including a declaration that accepts any format, the Server MUST respond in ECSON if it supports ECSON. The Server MUST respond in plain JSON only when the Client does not accept ECSON, or prefers plain JSON to ECSON.
> **Note (non-normative): Rationale**
>
> ECSON is the default because it keeps every value exact, and it is still valid JSON: a Client that does not know ECSON can parse the response and sees typed values as small objects, such as `{ "$date": "..." }`. A Client that needs plain values says so explicitly, by not accepting ECSON or by preferring plain JSON.
> **Caution (non-normative)**
>
> The Resource Representation of the Output and that of the Input are chosen separately. Accepting ECSON in the Output does not make the Server read the Input as ECSON: each Protocol labels the Input format (for example, the HTTP `Content-Type` header field), and an Input labeled as plain JSON is read as plain JSON ([`REPR_PLAIN_JSON`](#REPR_PLAIN_JSON)).
**Rule `META_PREFER_REPRESENTATION`**: MAY
The Client MAY declare a return preference: `representation`, to receive the Resources affected by the operation, or `minimal`, to receive only the operation status.
**Rule `META_RES_DEFAULT`**: MUST
Without a return preference, the Server MUST behave as if the Client declared `representation`.
**Rule `META_PREFER_STATUS`**: MUST
With the `minimal` return preference, the Server MUST NOT send Resources when the operation succeeds, and MUST send only the error data ([section 3.4.4](#344-error-handling)) when it fails.
> **Note (non-normative)**
>
> The return preference follows the `return` preference of the HTTP `Prefer` header ([RFC 7240](https://www.rfc-editor.org/rfc/rfc7240)), defined here independently of HTTP. ECSON output is valid JSON, so the fallback to ECSON is readable by JSON-only Clients.
#### 3.4.2 Specification versions
**Rule `META_CRUD_SPECS`**: MUST
The Server MUST declare the specifications it implements, the Base Specification and each extension, with the versions it supports for each, as [Semantic Versioning](https://semver.org/) versions, for example `base@0.2.0, async@0.1.0`.
**Rule `META_CRUD_REQUIRE`**: MAY
The Client MAY declare the specifications it requires, each with a version range in the syntax of [node-semver ranges](https://github.com/npm/node-semver#ranges), for example `base@^0.2.0, async@~0.1.0`.
**Rule `META_CRUD_RANGE_MATCH`**: MUST
When the Client declares required specifications, the Server MUST select, for each one, the highest version it supports that satisfies the range, and MUST declare the selected versions in the Output. If any required specification is not supported, or no supported version satisfies its range, the operation MUST fail with the [`NEGOTIATION`](#NEGOTIATION) error, listing the supported versions.
> **Tip (non-normative): Example**
>
> A Server supports `base@0.2.0`, `base@0.3.1` and `async@0.1.0`. A Client requiring `base@^0.2.0, async@^0.1.0` gets `base@0.2.0` and `async@0.1.0` (under node-semver, `^0.2.0` means `>=0.2.0 <0.3.0`). A Client requiring `relationships@^0.1.0` gets the [`NEGOTIATION`](#NEGOTIATION) error.
> **Note (non-normative): Rationale**
>
> Each specification has its own version, so the Server declares the specifications it supports, and Clients negotiate versions with ranges only when they need to.
#### 3.4.3 General metadata
**Rule `META_MATCHED_COUNT`**: SHOULD
Operations that take a Search Query SHOULD include a "Matched Count" Metadata field with the total number of Resources matched by the Search Query, regardless of pagination.
**Rule `META_MODIFIED_COUNT`**: SHOULD
Write operations SHOULD include a "Modified Count" Metadata field with the number of Resources modified by the operation.
**Rule `META_CORRELATION_ID`**: SHOULD
The Client SHOULD send a "Correlation ID" Metadata field with a new UUIDv7 in `uuid-hex` format. If the Client sends one, the Server MUST return the same value; otherwise, the Server SHOULD generate one and return it.
> **Note (non-normative)**
>
> The Correlation ID lets Clients, Servers and intermediaries relate logs and traces of the same operation.
#### 3.4.4 Error handling
When an operation fails, the Server reports one of the error codes below. Each Protocol specification maps these codes to its own (for example, HTTP status codes or JSON-RPC error codes), so that Clients handle errors the same way over any Protocol.
| Code | Condition |
|---|---|
| `INVALID_INPUT` | The Subject or a Parameter is malformed, such as an invalid Search Query or field list, or combined pagination Parameters |
| `INVALID_PATCH` | A patch is malformed or cannot be applied |
| `NOT_FOUND` | The Resource or Collection does not exist (extensions may add targets, such as `view` or `operation`) |
| `CONFLICT` | A Resource ID sent by the Client already exists |
| `EXPECT_MISMATCH` | The number of matched Resources differs from the expected count sent by the Client |
| `UPSERT_DENIED` | The Resource does not exist and the Client denied its creation |
| `NEGOTIATION` | The Server does not accept the requested format, specification version or Resource ID type |
| `UNSUPPORTED` | The Server does not implement the requested operation, operator or feature |
| `STRICT_WARNINGS` | The Client declared the strict preference and the operation produced Warnings |
| `ACCESS_DENIED` | The Client is not allowed to perform the operation |
| `INTERNAL` | The Server or the Data source failed |
**Rule `RES_ERROR_DATA`**: MUST
When an operation fails, the Server MUST send error data in the negotiated representation, with at least the error code from the table above (or from an extension) and a human-readable message (the `detail` member, in a Problem Details object). For [`NOT_FOUND`](#NOT_FOUND), the error data SHOULD also include a `target` with the kind of missing element: `resource` or `collection`, or a target defined by an extension.
**Rule `ERROR_PROBLEM_DETAILS`**: SHOULD
Error data SHOULD be a Problem Details object ([RFC 9457](https://www.rfc-editor.org/rfc/rfc9457)), with the error code in a `code` member and, for [`NOT_FOUND`](#NOT_FOUND), the target in a `target` member. The `status` member SHOULD be present only when the Protocol has numeric status codes, such as HTTP.
**Rule `ERROR_PROTOCOL_MAPPING`**: MUST
Every Protocol specification MUST map each error code of this specification and of the extensions it supports to an error of the Protocol, and MUST carry the error code of this specification in the error data.
**Rule `ERROR_EXTENSION_CODES`**: MAY
Extensions MAY define additional error codes, which MUST NOT reuse the codes of this specification.
**Rule `ERROR_CUSTOM_CODES`**: MAY
Servers MAY define their own error codes, which MUST be prefixed with a namespace and a `.` (for example `acme.QUOTA_EXCEEDED`).
**Rule `RES_ERROR_MORE_DATA`**: MAY
Error data MAY include additional Fields, such as documentation URLs or tracing information.
> **Tip (non-normative): Example**
>
> Over HTTP, a missing Resource is reported with the status `404 Not Found` and the error data `{ "type": "about:blank", "title": "Not Found", "status": 404, "detail": "Order 0190a5f2-... not found", "code": "NOT_FOUND", "target": "resource" }`; over MCP, with a JSON-RPC error whose data carries the same object, without `status`.
> **Note (non-normative): Rationale**
>
> Protocols have their own error codes, but a generic CRUD Client, such as a user interface or an AI agent, needs the same codes regardless of the Protocol. The Base Specification defines the conditions and their codes; each Protocol specification maps them.
#### 3.4.5 Warnings
**Rule `META_WARN`**: MAY
The Server MAY report Warnings: conditions that do not prevent the operation, such as deprecations, quotas, ignored Parameters or reduced limits. Each Warning MUST have a code and a human-readable message.
**Rule `META_WARN_PREFERENCE`**: MUST
The Client MAY declare a strict preference. When it does, the Server MUST fail any operation that would produce Warnings with the [`STRICT_WARNINGS`](#STRICT_WARNINGS) error, reporting the Warnings in the error data. Without it, Warnings MUST NOT make an operation fail.
**Rule `META_WARN_PREFERENCE_EXCEPT`**: MAY
The strict preference MAY list Warning codes that remain Warnings. When it does, the Server MUST report Warnings with a listed code without failing, and MUST fail with the [`STRICT_WARNINGS`](#STRICT_WARNINGS) error any operation that would produce a Warning with another code. A Server that does not support the list MUST apply the strict preference to every Warning.
> **Tip (non-normative): Example**
>
> A Client that accepts reduced limits, but no other Warning, declares the strict preference with the list [`LIMIT_REDUCED`](#LIMIT_REDUCED): a [`LIMIT_REDUCED`](#LIMIT_REDUCED) Warning is reported and the operation succeeds, while any other Warning, such as [`SCHEMA_VIOLATION`](./crud/schema.md#SCHEMA_VIOLATION), makes it fail.
**Rule `WARN_DATA`**: MAY
Besides the code and the message, a Warning MAY include the members `parameter` (the name of a Parameter), `field` (a field path), `id` (a Resource ID) and `error` (an error code), as specified for each Warning code, and other members, such as documentation URLs.
| Code | Condition | Members |
|---|---|---|
| `PARAM_IGNORED` | A Parameter the Server does not recognize was ignored ([`PARAM_CUSTOM_UNKNOWN`](#PARAM_CUSTOM_UNKNOWN)) | `parameter` |
| `LIMIT_REDUCED` | The Server reduced the `limit` sent by the Client ([`PAGINATION_LIMIT_MAX`](#PAGINATION_LIMIT_MAX)) | `parameter` |
| `ORDER_NOT_PRESERVED` | The Result is not in the order of the Subject ([`RES_DETERMINISTIC_WRITES`](#RES_DETERMINISTIC_WRITES)) | |
| `ID_IGNORED` | A Resource ID in a replacement Resource was ignored ([`SUB_NO_ID`](#SUB_NO_ID)) | `id` |
| `WRITE_FAILED` | A Resource was not written in a partial write ([`WRITE_PARTIAL`](#WRITE_PARTIAL)) | `error`, `id` when known |
| `TYPE_DOWNGRADED` | A value was stored in its plain JSON form ([`REPR_DOWNGRADE`](#REPR_DOWNGRADE)) | `field` |
| `DEPRECATED` | The operation used a Parameter, format or feature that the Server will remove | `parameter` when it applies |
**Rule `WARN_STANDARD_CODES`**: MUST
For the conditions in the table above, the Server MUST use the Warning codes and members of the table.
**Rule `WARN_EXTENSION_CODES`**: MAY
Extensions and Protocol specifications MAY define additional Warning codes, and MUST NOT reuse the codes of this specification.
**Rule `WARN_CUSTOM_CODES`**: MAY
Servers MAY define their own Warning codes, which MUST be prefixed with a namespace and a `.` (for example `acme.QUOTA_LOW`).
**Rule `WARN_UNKNOWN_CODES`**: MUST
Clients MUST accept Warnings with codes they do not know, and treat them as generic Warnings.
> **Note (non-normative)**
>
> Quotas and other conditions that depend on each Server use custom codes ([`WARN_CUSTOM_CODES`](#WARN_CUSTOM_CODES)). A Client may keep some Warning codes as Warnings while every other code fails ([`META_WARN_PREFERENCE_EXCEPT`](#META_WARN_PREFERENCE_EXCEPT)).
> **Note (non-normative)**
>
> The strict preference follows the `handling=strict` preference of the HTTP `Prefer` header ([RFC 7240](https://www.rfc-editor.org/rfc/rfc7240)).
## 4. Operation rules
### 4.1 Get
#### 4.1.1 Operation `get`
**Rule `SUB_ID`**: MUST
Client MUST send a single Resource ID in the Subject.
**Rule `RES_RESOURCES_FOUND`**: MUST
Server MUST return the Resources matched by the Subject.
**Rule `RES_MATCHING_REQUIRED`**: MUST
If no Resource matches the Resource ID, the Server MUST fail the operation with the [`NOT_FOUND`](#NOT_FOUND) error.
**Rule `PARAM_PROJECTION`**: MAY
Client MAY send a [Projection Parameter](#332-projection-parameter).
### 4.2 List
#### 4.2.1 Operation `list`
**Rule `SUB_SEARCH_QUERY`**: MUST
If the Client specifies a Subject, it MUST be a Search Query as defined in [Section 3.2.1 Definition and representation](#321-definition-and-representation). CRUD Participants MUST negotiate the Search Query format as specified in [3.4.1 Content negotiation](#341-content-negotiation).
**Rule `SUB_EMPTY`**: MAY
The Client MAY omit the Subject. In this case, every Resource of the Collection matches, subject to pagination.
**See rule [`RES_RESOURCES_FOUND`](#RES_RESOURCES_FOUND)** (MUST, section 4.1.1)
**Rule `RES_NO_RESULTS`**: MUST
If no Resource matches the Search Query, the Server MUST NOT fail the operation: read operations return an empty list and write operations modify nothing, with a Modified Count of 0.
**Rule `PARAM_PAGINATION`**: MAY
Client MAY send a [Pagination Parameter](#424-pagination-parameters).
**Rule `PARAM_CUSTOM`**: MAY
Client MAY send a [Custom Parameter](#425-custom-parameters).
**See rule [`PARAM_PROJECTION`](#PARAM_PROJECTION)** (MAY, section 4.1.1)
**Rule `PARAM_SORTING`**: MAY
Client MAY send a [Sorting Parameter](#423-sorting-parameter).
#### 4.2.3 Sorting Parameter
A "**Sorting Parameter**" determines the order of the Results of `list` operations.
**Rule `SORTING_FIELD_LIST`**: MUST
A Sorting Parameter MUST be a field list ([section 3.3.1](#331-field-lists)), where the `-` modifier means descending order and Fields without it are sorted in ascending order. The Server MUST sort by each Field in the order of the list.
**Rule `SORTING_NULLS`**: MUST
`null` and missing Fields MUST be sorted as lower than any other value, so they come first in ascending order and last in descending order.
**Rule `SORTING_DEFAULT`**: SHOULD
Without a Sorting Parameter, the Server SHOULD sort by Resource ID, and it SHOULD add the Resource ID as the last sorting key, so that pages are stable.
> **Note (non-normative)**
>
> The order between values of different types is implementation-defined. With UUIDv7 Resource IDs in `uuid-hex` format ([`ID_UUID`](#ID_UUID)), sorting by Resource ID is equivalent to sorting by creation time. Providers for SQL Data sources implement [`SORTING_NULLS`](#SORTING_NULLS) with `NULLS FIRST` (ascending) and `NULLS LAST` (descending).
#### 4.2.4 Pagination Parameters
"**Pagination Parameters**" split the Results of `list` operations into pages. There are three ways to paginate, all with a `limit`, the maximum number of Resources per page.
| Way | Parameters | Best for |
|---|---|---|
| Page | `page` (starting at 1) and `limit` | screens and charts that jump to a page |
| Offset | `offset` (number of Resources to skip, starting at 0, also called skip) and `limit` | clients that compute positions |
| Cursor | `cursor` (an opaque token returned by the previous page) and `limit` | large Collections, where skipping many Resources is slow |
**Rule `PAGINATION_PAGE`**: SHOULD
A Server that paginates SHOULD support the `page` and `limit` Parameters.
**Rule `PAGINATION_OFFSET`**: MAY
A Server MAY support the `offset` and `limit` Parameters.
**Rule `PAGINATION_CURSOR`**: MAY
A Server MAY support cursor pagination. When it does, the Result metadata MUST include the cursor of the next page, or indicate that there is no next page, and the cursor MUST be opaque to the Client.
**Rule `PAGINATION_EXCLUSIVE`**: MUST
`page`, `offset` and `cursor` MUST NOT be combined in the same operation; the Server MUST fail if they are.
**Rule `PAGINATION_LIMIT_MAX`**: MAY
A Server MAY cap `limit` and MAY apply a default `limit` when the Client sends none. When it reduces the `limit` sent by the Client, it MUST report the [`LIMIT_REDUCED`](#LIMIT_REDUCED) Warning.
> **Note (non-normative)**
>
> The total number of matching Resources is reported by [`META_MATCHED_COUNT`](#META_MATCHED_COUNT).
#### 4.2.5 Custom Parameters
Custom Parameters are defined in [section 3.3.3](#333-custom-parameters).
### 4.3 Create
#### 4.3.1 Operation `create`
**Rule `SUB_RESOURCES_CREATE`**: MUST
Client MUST send either a single Resource or a list of multiple Resources.
**Rule `SUB_WITH_IDS`**: MAY
The Client MAY send Resources with Resource IDs, in a type the Server accepts for the Collection.
**Rule `RES_RESOURCES_WRITTEN`**: MUST
Server MUST return the Resource(s) that were the subject of the operation (created, modified, or replaced).
**Rule `RES_WITH_IDS`**: MUST
Resource IDs MUST be returned with their Resources
**Rule `RES_NO_IDS`**: MUST
If the Server cannot create Resources with the Resource IDs sent by the Client, the operation MUST fail with the [`NEGOTIATION`](#NEGOTIATION) error.
**Rule `RES_CONFLICT`**: MUST
If a Resource ID sent by the Client already exists in the Collection, the Server MUST fail the operation with the [`CONFLICT`](#CONFLICT) error.
**Rule `RES_DETERMINISTIC_WRITES`**: SHOULD
When the Subject has several Resources, the Server SHOULD return the Result in the same order as the Subject. If it cannot, it MUST report the [`ORDER_NOT_PRESERVED`](#ORDER_NOT_PRESERVED) Warning.
**Rule `PARAM_PROJECTION_WRITE`**: MAY
Client MAY send a Projection Parameter in order to reduce redundancy of Resources returned in the Result.
#### 4.3.2 Operation `clone`
`clone` is a shorthand for creating a copy of an existing Resource with a new Resource ID.
**Rule `SUB_CLONE`**: MUST
The Client MUST send the Resource ID of the source Resource. The Client MAY also send a patch (as in [`SUB_JSON_PATCH`](#SUB_JSON_PATCH) and [`SUB_MERGE_PATCH`](#SUB_MERGE_PATCH)) to apply to the copy, and MAY send the Resource ID of the copy.
**Rule `RES_CLONE`**: MUST
The Server MUST create a new Resource in the same Collection with the Fields of the source Resource, apply the patch if one was sent, and assign it a new Resource ID (or the one sent by the Client). Reserved Fields defined by extensions follow the rules of each extension.
**See rule [`RES_MATCHING_REQUIRED`](#RES_MATCHING_REQUIRED)** (MUST, section 4.1.1)
**See rule [`RES_RESOURCES_WRITTEN`](#RES_RESOURCES_WRITTEN)** (MUST, section 4.3.1)
**See rule [`RES_CONFLICT`](#RES_CONFLICT)** (MUST, section 4.3.1)
**See rule [`PARAM_PROJECTION_WRITE`](#PARAM_PROJECTION_WRITE)** (MAY, section 4.3.1)
> **Note (non-normative)**
>
> Without `clone`, a Client would need a `get` followed by a `create`, which is two round trips and can copy a stale version. The Metadata extension records the source Resource as the ancestor of the copy.
### 4.4 Patch
#### 4.4.1 Operation `patchById`
**See rule [`SUB_ID`](#SUB_ID)** (MUST, section 4.1.1)
**Rule `SUB_JSON_PATCH`**: MUST
The Client MUST send the patch as a JSON Patch ([RFC 6902](https://www.rfc-editor.org/rfc/rfc6902)) document. If the patch is malformed or cannot be applied, the Server MUST fail the operation with the [`INVALID_PATCH`](#INVALID_PATCH) error.
**Rule `SUB_MERGE_PATCH`**: MAY
The Server MAY also accept the patch as a JSON Merge Patch ([RFC 7396](https://www.rfc-editor.org/rfc/rfc7396)) document, negotiated with the `application/merge-patch+json` media type.
> **Note (non-normative)**
>
> A JSON Merge Patch is a partial Resource with the new values, for example `{ "name": "Ana", "nickname": null }`. In a Merge Patch, `null` removes the Field, so a Field cannot be set to `null`; a JSON Patch with a `replace` operation can.
**See rule [`RES_RESOURCES_WRITTEN`](#RES_RESOURCES_WRITTEN)** (MUST, section 4.3.1)
**See rule [`RES_MATCHING_REQUIRED`](#RES_MATCHING_REQUIRED)** (MUST, section 4.1.1)
**See rule [`PARAM_PROJECTION_WRITE`](#PARAM_PROJECTION_WRITE)** (MAY, section 4.3.1)
#### 4.4.2 Operation `patchByQuery`
**Rule `SUB_SEARCH_QUERY_WRITE`**: MUST
Client MUST send a Search Query as defined in [Section 3.2.1 Definition and representation](#321-definition-and-representation) in the Subject. CRUD Participants MUST negotiate the Search Query format as specified in [3.4.1 Content negotiation](#341-content-negotiation).
**See rule [`SUB_JSON_PATCH`](#SUB_JSON_PATCH)** (MUST, section 4.4.1)
**See rule [`SUB_MERGE_PATCH`](#SUB_MERGE_PATCH)** (MAY, section 4.4.1)
**See rule [`RES_RESOURCES_WRITTEN`](#RES_RESOURCES_WRITTEN)** (MUST, section 4.3.1)
**See rule [`RES_NO_RESULTS`](#RES_NO_RESULTS)** (MUST, section 4.2.1)
**See rule [`PARAM_PROJECTION_WRITE`](#PARAM_PROJECTION_WRITE)** (MAY, section 4.3.1)
**Rule `PARAM_EXPECT_MATCH`**: MAY
The Client MAY send an "Expect Match" Parameter with the number of Resources the Search Query is expected to match. The Server MUST check it before writing anything and, if the matched count differs, MUST fail the operation with the [`EXPECT_MISMATCH`](#EXPECT_MISMATCH) error without modifying any Resource.
### 4.5 Replace
#### 4.5.1 Operation `replaceById`
**Rule `SUB_ID_REPLACE`**: MUST
The Subject MUST contain the Resource ID of the Resource to replace, inside the replacement Resource or separately. If both are present and differ, the Server MUST fail the operation with the [`INVALID_INPUT`](#INVALID_INPUT) error.
**Rule `SUB_RESOURCE_REPLACE`**: MUST
Client MUST send a new Resource to replace the original Resource(s) matched
**See rule [`RES_RESOURCES_WRITTEN`](#RES_RESOURCES_WRITTEN)** (MUST, section 4.3.1)
**Rule `RES_UPSERT_PREVENTED`**: MUST
If no Resource has the Resource ID and the Client denied upserts ([`PARAM_DENY_UPSERT`](#PARAM_DENY_UPSERT)), the Server MUST fail the operation with the [`UPSERT_DENIED`](#UPSERT_DENIED) error.
**See rule [`PARAM_PROJECTION_WRITE`](#PARAM_PROJECTION_WRITE)** (MAY, section 4.3.1)
**Rule `PARAM_DENY_UPSERT`**: MAY
Client MAY send a “Deny Upsert” Parameter to explicitly indicate that the Server MUST NOT create a new Resource if the Resource ID is not found in the Collection.
**Rule `META_UPSERTED`**: MUST
If the Resource ID is not found during the operation and the Server creates the Resource, the Server MUST send an “Upserted” Metadata indicating the Resource was created instead of replaced.
#### 4.5.2 Operation `replaceByQuery`
**See rule [`SUB_SEARCH_QUERY_WRITE`](#SUB_SEARCH_QUERY_WRITE)** (MUST, section 4.4.2)
**See rule [`SUB_RESOURCE_REPLACE`](#SUB_RESOURCE_REPLACE)** (MUST, section 4.5.1)
**Rule `REPLACE_QUERY_EACH`**: MUST
The Server MUST replace each Resource matched by the Search Query with the replacement Resource, keeping the Resource ID of each one, and MUST NOT create Resources (no upsert).
**Rule `SUB_NO_ID`**: SHOULD
The replacement Resource SHOULD NOT include a Resource ID. If it does, the Server MUST ignore it, keep the Resource ID of each matched Resource, and report the [`ID_IGNORED`](#ID_IGNORED) Warning.
**See rule [`RES_RESOURCES_WRITTEN`](#RES_RESOURCES_WRITTEN)** (MUST, section 4.3.1)
**See rule [`RES_NO_RESULTS`](#RES_NO_RESULTS)** (MUST, section 4.2.1)
**See rule [`PARAM_PROJECTION_WRITE`](#PARAM_PROJECTION_WRITE)** (MAY, section 4.3.1)
**See rule [`PARAM_EXPECT_MATCH`](#PARAM_EXPECT_MATCH)** (MAY, section 4.4.2)
> **Tip (non-normative)**
>
> To replace exactly one Resource found by a Search Query, send an "Expect Match" Parameter of `1`: the Server fails with [`EXPECT_MISMATCH`](#EXPECT_MISMATCH), without writing, if the Search Query matches any other number of Resources.
### 4.6 Delete
#### 4.6.1 Operation `deleteById`
**See rule [`SUB_ID`](#SUB_ID)** (MUST, section 4.1.1)
**Rule `RES_EMPTY`**: MUST
Delete operations MUST behave as if the Client declared the `minimal` return preference when it declares none: the Server returns no Resources. When the Client declares `representation`, the Server MUST return the deleted Resources.
**See rule [`RES_MATCHING_REQUIRED`](#RES_MATCHING_REQUIRED)** (MUST, section 4.1.1)
#### 4.6.2 Operation `deleteByQuery`
**See rule [`SUB_SEARCH_QUERY_WRITE`](#SUB_SEARCH_QUERY_WRITE)** (MUST, section 4.4.2)
**See rule [`RES_EMPTY`](#RES_EMPTY)** (MUST, section 4.6.1)
**See rule [`RES_NO_RESULTS`](#RES_NO_RESULTS)** (MUST, section 4.2.1)
**See rule [`PARAM_EXPECT_MATCH`](#PARAM_EXPECT_MATCH)** (MAY, section 4.4.2)
### 4.7 Writes on several Resources
A write operation may affect several Resources: `create` with a list, and the `ByQuery` operations. This section defines what happens when some of them fail.
**Rule `WRITE_MODIFIED_COUNT`**: MUST
A write operation on several Resources MUST always report the Modified Count ([`META_MODIFIED_COUNT`](#META_MODIFIED_COUNT)), whether it succeeds or fails.
**Rule `WRITE_ATOMIC_STRICT`**: MUST
When the Client declared the strict preference ([`META_WARN_PREFERENCE`](#META_WARN_PREFERENCE)), a write operation on several Resources MUST be atomic: either every Resource is written or none is. A Server that cannot guarantee atomicity for the Collection MUST fail with the [`UNSUPPORTED`](#UNSUPPORTED) error before writing anything.
**Rule `WRITE_ATOMIC_TRANSACTIONAL`**: MUST
When the Data source supports transactions, a write operation on several Resources MUST be atomic: if any Resource cannot be written, the operation MUST fail and no Resource is written.
**Rule `WRITE_PARTIAL`**: MAY
Otherwise, a write operation on several Resources MAY be partial: the Server writes the Resources it can, returns them in the Result, and reports each Resource it could not write as a [`WRITE_FAILED`](#WRITE_FAILED) Warning, with the error code and, when known, the Resource ID.
**Rule `WRITE_ATOMICITY_DECLARE`**: SHOULD
A Server SHOULD declare, for each Collection, whether writes on several Resources are atomic.
| Data source | Strict preference | Behavior |
|---|---|---|
| Transactional (PostgreSQL) | any | atomic: any failure fails the operation, nothing is written |
| Not transactional (Notion, Airtable) | strict | [`UNSUPPORTED`](#UNSUPPORTED), nothing is written |
| Not transactional (Notion, Airtable) | not strict | partial: written Resources in the Result, failures as Warnings |
> **Note (non-normative): Rationale**
>
> Partial failures follow the same model as other Warnings: Clients that need all-or-nothing behavior declare the strict preference, which turns any Warning into an error, and therefore requires a transaction.
## 5. Origins and references
### 5.1 Origins
This specification grew out of years of building CRUD APIs over different data sources. Its rules consolidate patterns from:
- **Existing standards**: [HTTP semantics](https://www.rfc-editor.org/rfc/rfc9110), the [`Prefer` header](https://www.rfc-editor.org/rfc/rfc7240), [JSON Patch](https://www.rfc-editor.org/rfc/rfc6902), [Web Linking](https://www.rfc-editor.org/rfc/rfc8288) and [UUIDs](https://www.rfc-editor.org/rfc/rfc9562) (see 5.2).
- **API conventions**: [JSON:API](https://jsonapi.org/format/), [OData](https://www.odata.org/documentation/) and the [REST architectural style](https://ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm).
- **Public APIs**: [Salesforce](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_rest.htm), [GitHub](https://docs.github.com/en/rest), [Notion](https://developers.notion.com/reference/intro) and [WordPress](https://developer.wordpress.org/rest-api/), whose parameters, endpoint structures and response conventions informed the operations and parameters.
- **Data formats**: [MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) and [Meteor EJSON](https://docs.meteor.com/api/ejson.html), whose limitations led to [ECSON](https://github.com/lingodata/ecson).
### 5.2 Normative references
- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): requirement level key words (BCP 14)
- [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648): The Base16, Base32, and Base64 Data Encodings
- [RFC 6902](https://www.rfc-editor.org/rfc/rfc6902): JavaScript Object Notation (JSON) Patch
- [RFC 7396](https://www.rfc-editor.org/rfc/rfc7396): JSON Merge Patch
- [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259): The JavaScript Object Notation (JSON) Data Interchange Format
- [RFC 9562](https://www.rfc-editor.org/rfc/rfc9562): Universally Unique IDentifiers (UUIDs)
- [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457): Problem Details for HTTP APIs
- [Semantic Versioning 2.0.0](https://semver.org/)
- [node-semver ranges](https://github.com/npm/node-semver#ranges): version range syntax used in specification negotiation
- [ECSON](https://github.com/lingodata/ecson): ECMAScript Object Notation (LingoData)
- [UnQuery](https://github.com/lingodata/unquery): Universal Query String Filter Specification (LingoData)
### 5.3 Informative references
- [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110): HTTP Semantics
- [RFC 5789](https://www.rfc-editor.org/rfc/rfc5789): PATCH Method for HTTP
- [RFC 7240](https://www.rfc-editor.org/rfc/rfc7240): Prefer Header for HTTP
- [RFC 8288](https://www.rfc-editor.org/rfc/rfc8288): Web Linking
- [JSON:API](https://jsonapi.org/format/)
- [OData](https://www.odata.org/documentation/)
- [MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/)
- [Meteor EJSON](https://docs.meteor.com/api/ejson.html)
- [JSON5](https://spec.json5.org/)
### 5.4 References used by the extensions
| Reference | Used by |
|---|---|
| [Standard Webhooks](https://www.standardwebhooks.com/) | Asynchronous operations: signing and delivery of callbacks |
| [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986): URI Generic Syntax | Relationships: URI references (through ECSON `$rel`) |
| [RFC 8288](https://www.rfc-editor.org/rfc/rfc8288): Web Linking | Relationships: Link header references (through ECSON `$rel`) |
| [RFC 9264](https://www.rfc-editor.org/rfc/rfc9264): Linkset | Relationships: link objects (through ECSON `$rel`) |
| [IANA Link Relations](https://www.iana.org/assignments/link-relations/link-relations.xhtml) | Relationships: registered relation types |
| [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785): JSON Canonicalization Scheme (JCS) | Metadata: content hash (through ECSON canonical mode) |
> **Note (non-normative)**
>
> Protocol-specific references (HTTP status codes and headers, JSON-RPC and MCP) belong to each Protocol specification.
---
# CRUD API Asynchronous Operations Extension
Version: 0.1.0 · Status: draft · License: Apache-2.0
Source: lingodata/crud@bc225ba
## 1. Asynchronous operations
The **Asynchronous operations** extension lets Client and Server agree that an operation runs in the background: the Server accepts it, returns an Operation ID, and the Client retrieves the outcome later, by polling or through a callback. It is optional: Servers that do not implement it are not required to follow any rule in this document. By default, every operation is synchronous.
This extension requires the Base Specification `^0.2.0`.
### 1.1 Negotiation
Neither Participant is required to declare its abilities. A Client that declares nothing is treated as a synchronous-only Client, and a Server that declares nothing is treated according to how it responds.
**Rule `ASYNC_CLIENT_PREFER`**: MAY
A Client that supports both modes MAY declare a preference for asynchronous processing.
**Rule `ASYNC_CLIENT_REQUIRE`**: MAY
A Client that supports only asynchronous processing MAY declare that it requires it.
**Rule `ASYNC_CLIENT_DEFAULT`**: MUST
A Client that declares neither a preference nor a requirement MUST be treated as supporting only synchronous processing.
**Rule `ASYNC_SERVER_MATRIX`**: MUST
The Server MUST respond according to the table below. A preference MUST NOT make an operation fail: when the Server cannot run the operation asynchronously, it MUST run it synchronously.
| | Client declares nothing | Client prefers async | Client requires async |
|---|---|---|---|
| **Server supports sync only** | sync | sync | [`NEGOTIATION`](./crud/base.md#NEGOTIATION) error |
| **Server supports async only** | [`NEGOTIATION`](./crud/base.md#NEGOTIATION) error | async | async |
| **Server supports both** | sync | async | async |
> **Note (non-normative): Rationale**
>
> The absence of a declaration is the inference: no declaration means synchronous only, so no Participant has to guess the abilities of the other.
### 1.2 Accepting an operation
**Rule `ASYNC_OPERATION_ID`**: MUST
When the Server runs an operation asynchronously, it MUST respond immediately that the operation was accepted, with an Operation ID: a UUIDv7 in `uuid-hex` format that identifies the operation.
**Rule `ASYNC_PROTOCOL_LOOKUP`**: MUST
Each Protocol specification MUST define how a Client retrieves the state of an operation from its Operation ID.
> **Note (non-normative)**
>
> For example, HTTP can return the URL of the operation in the `Location` header, and MCP can define a method that takes the Operation ID.
### 1.3 Operation state
The state of an operation is one of **pending** (still running), **succeeded** or **failed**.
**Rule `ASYNC_POLL_PENDING`**: MUST
While the operation runs, retrieving its state MUST indicate that it is pending.
**Rule `ASYNC_PROGRESS`**: MAY
A pending state MAY include progress, as the number of items done and, when known, the total. Each Protocol specification MAY define how progress is pushed to the Client as it happens.
**Rule `ASYNC_POLL_SUCCESS`**: MUST
When the operation has succeeded, retrieving its state MUST return the Result and the Metadata (such as counts, Warnings and specification versions) that a synchronous execution of the same operation would have returned.
**Rule `ASYNC_POLL_FAILURE`**: MUST
When the operation has failed, retrieving its state MUST return the error data ([Base section 3.4.4](./crud/base.md#344-error-handling)) that a synchronous execution would have returned.
**Rule `ASYNC_RETENTION`**: SHOULD
The Server SHOULD declare how long it keeps the state of completed operations. After that, retrieving the state MUST fail with the [`NOT_FOUND`](./crud/base.md#NOT_FOUND) error, with the `operation` target.
> **Tip (non-normative): Example**
>
> A `deleteByQuery` that matches 50,000 Resources is accepted with the Operation ID `0190a5f2-9a00-7c00-8000-00000000abcd`. While it runs, its state is `{ "status": "pending", "progress": { "done": 12000, "total": 50000 } }`. When it succeeds, its state carries what the synchronous response would have carried: no Resources ([`RES_EMPTY`](./crud/base.md#RES_EMPTY)) and the Modified Count `50000`.
### 1.4 Callbacks
**Rule `ASYNC_CALLBACK_URL`**: MAY
The Client MAY send a callback URL. When the operation completes, the Server MUST send its final state ([`ASYNC_POLL_SUCCESS`](#ASYNC_POLL_SUCCESS) or [`ASYNC_POLL_FAILURE`](#ASYNC_POLL_FAILURE)) to that URL.
**Rule `ASYNC_CALLBACK_ERROR_URL`**: MAY
The Client MAY send a separate callback URL for failures. When it does, the Server MUST send failed states to it instead of the callback URL.
**Rule `ASYNC_CALLBACK_SIGNATURE`**: SHOULD
Callbacks SHOULD be sent and signed as defined by [Standard Webhooks](https://www.standardwebhooks.com/), so that Clients can verify that they come from the Server.
**Rule `ASYNC_CALLBACK_POLL_FALLBACK`**: MUST
Even when the Client sends a callback URL, the Server MUST keep the state of the operation retrievable by its Operation ID.
> **Caution (non-normative): Security**
>
> A callback URL makes the Server send requests to an address chosen by the Client, which can be abused to reach internal networks (server-side request forgery). Servers MAY restrict the hosts accepted as callback URLs.
---
# CRUD API Resource Metadata Extension
Version: 0.1.0 · Status: draft · License: Apache-2.0
Source: lingodata/crud@bc225ba
## 1. Resource metadata
The **Metadata** extension defines Resource-level metadata: version, content hash, events, status and provenance. It is optional: Servers that do not implement it are not required to follow any rule in this document.
This extension requires the Base Specification `^0.2.0` and [ECSON](https://github.com/lingodata/ecson), including its canonical mode and its References type set.
> **Tip (non-normative): Example**
>
> ```json
> {
> "_id": "0190a5f2-7c3e-7b1a-9f4e-2d8c6b1e4a90",
> "name": "Ana",
> "_meta": {
> "version": 4,
> "hash": "5fWJ6A",
> "status": "published",
> "events": {
> "created": { "timestamp": { "$date": "2026-11-01T10:00:00.000Z" }, "author": "gustavo@example.com" },
> "updated": { "timestamp": { "$date": "2026-11-04T15:30:00.000Z" }, "author": "thamirys@example.com", "comments": "Fix name" },
> "published": { "timestamp": { "$date": "2026-11-02T09:00:00.000Z" }, "author": "gustavo@example.com" }
> },
> "ancestor": { "$rel": { "collection": "customers", "id": "0190a5f2-0000-7000-8000-00000000000a" } },
> "origin": { "$rel": "https://pipedrive.com/contacts/123" }
> }
> }
> ```
### 1.1 The `_meta` Field
**Rule `META_FIELD`**: MUST
Resource metadata MUST be represented in a reserved Field named `_meta` in each Resource, as allowed by [Base `FIELDS_EXTENSION_RESERVED`](./crud/base.md#FIELDS_EXTENSION_RESERVED).
**Rule `META_SERVER_MANAGED`**: MUST
The Server MUST manage `_meta`. On write operations, the Server MUST ignore values sent by the Client for `_meta`, except for the members this extension declares as writable (`status`, `ancestor`, `origin`, and `reason` and `comments` of the current event), and MUST report each ignored member as a [`META_IGNORED`](#META_IGNORED) Warning, with its `field`.
**Rule `META_PROTOCOL_MIRROR`**: MAY
Protocol specifications MAY also carry members of `_meta` in Protocol metadata, such as the HTTP `ETag` and `Last-Modified` headers for operations on a single Resource.
> **Note (non-normative): Rationale**
>
> Operation metadata (for example, HTTP headers) cannot describe each Resource of a `list`. A reserved Field travels with each Resource in every operation and Protocol.
### 1.2 Version and content hash
**Rule `META_DOC_VERSION`**: MUST
`_meta.version` MUST be an integer that is `1` when the Resource is created and is incremented by 1 on every write that changes the Resource.
**Rule `META_DOC_HASH`**: SHOULD
`_meta.hash` SHOULD be a hash of the content of the Resource: the CRC-32 (the polynomial used by ISO-HDLC, zlib and gzip) of the ECSON canonical serialization ([ECSON `CANONICAL_JCS`](./ecson.md#CANONICAL_JCS)), computed by the Server whatever the negotiated Resource Representation, of the Resource without the `_id` and `_meta` Fields, encoded as the 4 bytes in big-endian order in base64url without padding.
> **Tip (non-normative): Example**
>
> The Resource `{ "_id": "...", "name": "Ana", "total": 10 }` has the canonical content `{"name":"Ana","total":10}`, whose CRC-32 is `3858074088`, and the hash `5fWJ6A`.
> **Note (non-normative): Rationale**
>
> The hash is meant to compare contents: two Resources, or two versions of one Resource, have the same hash when they have the same content, regardless of their Resource IDs, which also makes clones comparable with their ancestors. The canonical form makes the hash identical across implementations and languages. CRC-32 is fast and enough to detect changes, but it is not a cryptographic hash and must not be used to detect deliberate tampering.
**Rule `META_DOC_CONDITIONAL`**: SHOULD
The Server SHOULD accept an expected hash or version in write operations. If it does not match the current Resource, the Server MUST fail the operation with the [`PRECONDITION_FAILED`](#PRECONDITION_FAILED) error, without writing.
### 1.3 Events
Events record when and by whom something happened to a Resource. `_meta.events` is an object whose keys are event names and whose values have the following structure:
| Field | Type | Requirement | Description |
|---|---|---|---|
| `timestamp` | a date (ECSON `$date`) | MUST | When the event occurred |
| `author` | string | SHOULD | Who performed it, such as an e-mail or user ID |
| `reason` | string | MAY | Context provided by the system |
| `comments` | string | MAY | Notes provided by the user |
**Rule `META_EVENT_CREATED`**: MUST
The Server MUST record a `created` event when the Resource is created, and MUST NOT change it afterwards.
**Rule `META_EVENT_UPDATED`**: MUST
The Server MUST record an `updated` event on every write that changes the Resource, replacing the previous `updated` event.
**Rule `META_EVENT_AUTHOR`**: SHOULD
The `author` of an event SHOULD default to the identity of the authenticated Client.
**Rule `META_EVENT_COMMENTS`**: MAY
The Client MAY send `reason` and `comments` for the event produced by a write operation.
### 1.4 Status
**Rule `META_STATUS`**: MAY
A Resource MAY have a status in `_meta.status`: a string whose possible values are defined by each application or by other extensions. The Client MAY set it on `create` and change it with `patch`.
**Rule `META_STATUS_EVENT`**: MUST
When `_meta.status` changes, the Server MUST record an event named after the new status (for example `published`), with the structure of [section 1.3](#13-events), replacing any previous event with that name.
> **Note (non-normative)**
>
> This extension does not filter operations by status: a `list` returns Resources in every status, and Clients filter with a Search Query on `_meta.status`. Status sets and their transitions (for example `draft`, `published`, `archived`) belong to each domain, and may be defined by a future extension based on an open ontology.
> **Note (non-normative): Rationale**
>
> Statuses are domain-specific, so this extension only defines where the status is stored and how its changes are recorded.
### 1.5 Provenance
**Rule `META_ANCESTOR`**: MUST
When a Resource is created by the `clone` operation, the Server MUST set `_meta.ancestor` to a reference ([ECSON collection object](./ecson.md#42-references-type-set)) to the source Resource. On `create`, the Client MAY set `_meta.ancestor` itself.
**Rule `META_ORIGIN`**: MAY
On `create`, the Client MAY set `_meta.origin` to a reference ([ECSON `$rel`](./ecson.md#42-references-type-set)) (a URI, Link header or link object) identifying the external source the Resource was imported or copied from.
### 1.6 Errors and Warnings
This extension adds the following error code to those of the Base Specification ([Base `ERROR_EXTENSION_CODES`](./crud/base.md#ERROR_EXTENSION_CODES)):
| Code | Condition |
|---|---|
| `PRECONDITION_FAILED` | The expected hash or version sent by the Client does not match the current Resource ([`META_DOC_CONDITIONAL`](#META_DOC_CONDITIONAL)) |
It also defines the following Warning code ([Base `WARN_EXTENSION_CODES`](./crud/base.md#WARN_EXTENSION_CODES)):
| Code | Condition | Members |
|---|---|---|
| `META_IGNORED` | A member of `_meta` sent by the Client was ignored ([`META_SERVER_MANAGED`](#META_SERVER_MANAGED)) | `field` |
---
# CRUD API Relationships Extension
Version: 0.1.0 · Status: draft · License: Apache-2.0
Source: lingodata/crud@bc225ba
## 1. Relationships
The **Relationships** extension defines how Resources reference other Resources and external resources. It is optional: Servers that do not implement it are not required to follow any rule in this document.
This extension requires the Base Specification `^0.2.0` and the References type set of [ECSON](https://github.com/lingodata/ecson) ([ECSON section 4.2](./ecson.md#42-references-type-set)), which defines the `$rel` typed value.
> **Tip (non-normative): Example**
>
> ```json
> {
> "_id": "0190a5f2-7c3e-7b1a-9f4e-2d8c6b1e4a90",
> "title": "Hello World",
> "author": { "$rel": { "collection": "users", "id": "0190a5f2-1111-7000-8000-000000000001" } },
> "tags": { "$rel": { "collection": "tags", "ids": ["promo", "delivery"] } },
> "customer": { "$rel": "https://api.example.com/customers/42" },
> "reviewers": { "$rel": "; rel=\"author\", ; rel=\"editor\"" },
> "related": { "$rel": [{ "collection": "products", "id": "p1" }, { "href": "https://example.com/b", "rel": "related" }] }
> }
> ```
### 1.1 Relationship Fields
**Rule `REL_FIELD`**: MUST
A relationship is a Field whose value is a reference ([ECSON `$rel`](./ecson.md#42-references-type-set)). Servers MUST store references in the native form of the Data source ([Base `REPR_NATIVE_STORAGE`](./crud/base.md#REPR_NATIVE_STORAGE)), return them as references, and MUST NOT convert other values into relationships.
> **Note (non-normative)**
>
> In the plain JSON Representation, a reference travels in its plain JSON form ([ECSON section 5.3](./ecson.md#53-plain-json-form)), such as a plain collection object or a URI string, and a value read as plain JSON is never a reference ([Base `REPR_NO_CONVERSION`](./crud/base.md#REPR_NO_CONVERSION)). Clients that create relationships use ECSON, or a schema with `refCollection` (Schema extension).
**Rule `REL_WRITE_REFERENCE`**: MUST
On write operations, Servers MUST store only the reference: the `data` member of collection objects ([ECSON `REF_COLLECTION_DATA`](./ecson.md#REF_COLLECTION_DATA)) MUST be ignored.
> **Note (non-normative): Rationale**
>
> Recognizing relationships by the shape of a Field would require knowing which Fields are relationships, which is a schema. With the ECSON `$rel` type, a relationship is recognized by its value alone, and denormalized data, when needed, goes in regular Fields (for example `authorName`).
### 1.2 Targets
**Rule `REL_INTERNAL`**: MUST
A relationship to Resources in the same Data source MUST use the [ECSON collection object](./ecson.md#42-references-type-set) form, with the Collection Slug in `collection`.
**Rule `REL_EXTERNAL`**: MUST
A relationship to anything else, including Resources of another Data source in the same API, MUST use the URI, Link header ([RFC 8288](https://www.rfc-editor.org/rfc/rfc8288)) or link object ([RFC 9264](https://www.rfc-editor.org/rfc/rfc9264)) forms, alone or combined in arrays.
**Rule `REL_EXTERNAL_NO_RESOLVE`**: MUST NOT
Servers MUST NOT resolve or validate external relationships: they are opaque references for Clients to resolve.
### 1.3 Cardinality
| Cardinality | Form | Empty |
|---|---|---|
| One | collection object with `id`, a URI, a link object, or a Link header with one link | `{ "$rel": null }` |
| Many | collection object with `ids`, a Link header with several links, or an array | `{ "$rel": { "collection": "tags", "ids": [] } }` or `{ "$rel": [] }` |
**Rule `REL_CARDINALITY`**: MUST
Servers MUST preserve the cardinality chosen by the Client: a relationship written with a single reference MUST be returned with a single reference, and one written with several references (`ids`, an array or a Link header with several links) MUST be returned in the same form, in the same order.
### 1.4 Integrity
**Rule `REL_VALIDATE`**: MAY
Servers MAY check that internal relationships refer to existing Resources, and fail write operations with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error when they do not.
> **Note (non-normative)**
>
> This extension does not define what happens to relationships when a referenced Resource is deleted (cascade, nullify or nothing); each Server decides and SHOULD document it.
### 1.5 Expansion
The **Expand Parameter** asks the Server to include the referenced Resources in the Result, inside the relationship values.
**Rule `REL_EXPAND`**: MAY
Servers MAY support an Expand Parameter in read operations: a field list ([Base section 3.3.1](./crud/base.md#331-field-lists)) of relationship Fields. For each listed Field with an internal relationship, the Server MUST include the referenced Resources in the `data` member of the collection object.
**Rule `REL_EXPAND_MISSING`**: MUST
When an expanded reference does not exist, its `data` MUST be `null` (or a `null` element, for `ids`), and the Server MUST report the [`REFERENCE_NOT_FOUND`](#REFERENCE_NOT_FOUND) Warning, with the `field` and the `id`.
**Rule `REL_EXPAND_EXTERNAL`**: MUST
External relationships MUST NOT be expanded; listing them in the Expand Parameter MUST be reported as an [`EXPAND_IGNORED`](#EXPAND_IGNORED) Warning, with the `field`.
**Rule `REL_EXPAND_NESTED`**: MAY
Servers MAY support nested expansion with field paths through expanded Resources (for example `author.company`), and MAY limit its depth, reporting the [`EXPAND_DEPTH_LIMITED`](#EXPAND_DEPTH_LIMITED) Warning, with the `field`.
> **Tip (non-normative): Example**
>
> `list` on `posts` with the Expand Parameter `author` returns:
>
> ```json
> {
> "_id": "0190a5f2-7c3e-7b1a-9f4e-2d8c6b1e4a90",
> "title": "Hello World",
> "author": { "$rel": {
> "collection": "users",
> "id": "0190a5f2-1111-7000-8000-000000000001",
> "data": { "_id": "0190a5f2-1111-7000-8000-000000000001", "name": "Ana" }
> } }
> }
> ```
> The relationship keeps its reference, so the Resource can be written back unchanged: `data` is ignored on writes ([`REL_WRITE_REFERENCE`](#REL_WRITE_REFERENCE)).
> **Note (non-normative): Rationale**
>
> The Base Specification forbids envelopes ([Base `REPR_NO_ENVELOPES`](./crud/base.md#REPR_NO_ENVELOPES)), so expanded Resources cannot go in a separate `included` list, as in [JSON:API](https://jsonapi.org/format/#fetching-includes). Placing them in `data`, inside the reference, keeps the relationship explicit and the Resource round-trippable.
### 1.6 Filtering
> **Note (non-normative)**
>
> Relationships can be filtered with UnQuery, whose operands are read as ECSON: `{ "author": { "$rel": { "collection": "users", "id": "0190a5f2-..." } } }` matches Resources whose `author` is that reference. No additional rule is needed.
### 1.7 Warnings
This extension defines the following Warning codes ([Base `WARN_EXTENSION_CODES`](./crud/base.md#WARN_EXTENSION_CODES)):
| Code | Condition | Members |
|---|---|---|
| `REFERENCE_NOT_FOUND` | An expanded reference points to a Resource that does not exist ([`REL_EXPAND_MISSING`](#REL_EXPAND_MISSING)) | `field`, `id` |
| `EXPAND_IGNORED` | An external relationship was listed in the Expand Parameter ([`REL_EXPAND_EXTERNAL`](#REL_EXPAND_EXTERNAL)) | `field` |
| `EXPAND_DEPTH_LIMITED` | Nested expansion stopped at the depth limit of the Server ([`REL_EXPAND_NESTED`](#REL_EXPAND_NESTED)) | `field` |
---
# CRUD API Schema Extension
Version: 0.1.0 · Status: draft · License: Apache-2.0
Source: lingodata/crud@bc225ba
## 1. Schemas
The **Schema** extension lets Clients register, read and change the schema of each Collection, and lets them discover which Collections an API exposes. It is optional: Servers that do not implement it are not required to follow any rule in this document.
This extension requires the Base Specification `^0.2.0` and the Metadata extension `^0.1.0`. Schemas are written in [JSON Schema 2020-12](https://json-schema.org/draft/2020-12/json-schema-core).
Schemas are managed as a "CRUD inside the CRUD": each schema is a Resource of a reserved Collection, and the operations of the Base Specification read and write it.
> **Note (non-normative): Rationale**
>
> The Base Specification does not depend on schemas: a Collection does not imply a schema ([Base section 2.5](./crud/base.md#25-resources)), and no rule of the Base Specification, of the other extensions or of the Protocols requires one. This extension adds schemas for the Servers and Clients that want them, without changing how the other specifications work.
### 1.1 The `@schema` Collection
**Rule `SCHEMA_COLLECTION`**: MUST
The Server MUST expose schemas as Resources of a reserved Collection named `@schema`, with one Resource per Collection of the API, whose Resource ID is the Slug of the described Collection. Every operation of the Base Specification that the Server supports MUST apply to `@schema`, as specified in this document.
> **Note (non-normative)**
>
> Slugs never contain `@` ([Base `COLLECTION_SLUG`](./crud/base.md#COLLECTION_SLUG)), so `@schema` cannot be the name of another Collection.
**Rule `SCHEMA_LIST_ALL`**: MUST
`list` on `@schema` MUST return a schema Resource for every Collection of the API, including the Collections without a registered schema ([`SCHEMA_NULL`](#SCHEMA_NULL)).
**Rule `SCHEMA_LIST_CACHE`**: MAY
The Server MAY cache the enumeration of the Collections of the Data source.
> **Tip (non-normative)**
>
> To discover the Collections of an API, a Client lists `@schema` with a projection of `_id` only ([Base `PROJECTION_FIELD_LIST`](./crud/base.md#PROJECTION_FIELD_LIST)).
### 1.2 Schema Resources
> **Tip (non-normative): Example**
>
> ```json
> {
> "_id": "customers",
> "validation": "strict",
> "schema": {
> "type": "object",
> "properties": {
> "name": { "type": "string", "dbType": "varchar(120)" },
> "birthday": { "type": "string", "format": "date", "estype": "plaindate" },
> "company": { "type": "object", "estype": "rel", "refCollection": "companies" }
> },
> "required": ["name"]
> },
> "_meta": { "version": 3 }
> }
> ```
**Rule `SCHEMA_RESOURCE_FIELDS`**: MUST
A schema Resource MUST have the Fields `_id`, with the Slug of the described Collection; `validation`, with `strict` or `lenient` ([section 1.6](#16-validation-of-resources)); and `schema`, with a JSON Schema (an object or a boolean) that describes each Resource of the Collection.
**Rule `SCHEMA_VALIDATION_DEFAULT`**: MUST
When the Client does not send `validation`, the Server MUST store `lenient`, unless it forces strict validation ([`SCHEMA_FORCED_STRICT`](#SCHEMA_FORCED_STRICT)).
**Rule `SCHEMA_NULL`**: MUST
A Collection without a registered schema MUST be represented by a schema Resource with `_id` and `schema: null`, without `validation` and `_meta`. The Server MUST NOT store anything for it.
**Rule `SCHEMA_VERSION`**: MUST
The version of a schema is the `_meta.version` of its Resource ([Metadata `META_DOC_VERSION`](./crud/metadata.md#META_DOC_VERSION)). The Server MUST increment it on every change of `schema` or `validation`.
> **Note (non-normative)**
>
> Migrations of existing Resources between schema versions are out of the scope of this version.
### 1.3 Writing schemas
**Rule `SCHEMA_CREATE_ID`**: MUST
`create` on `@schema` MUST receive the `_id` of each schema Resource. The Server MUST NOT generate it, and MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error when it is missing.
**Rule `SCHEMA_CREATE_NULL`**: MUST
`create` on `@schema` MUST be accepted for a Collection represented by [`SCHEMA_NULL`](#SCHEMA_NULL), and MUST fail with the [`CONFLICT`](./crud/base.md#CONFLICT) error only when the Collection already has a registered schema.
**Rule `SCHEMA_CLONE_ID`**: MUST
`clone` on `@schema` MUST receive the `_id` of the copy, the Slug of the target Collection. The Server MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error when it is missing.
**Rule `SCHEMA_COLLECTION_MISSING`**: MUST
Writing a schema for a Collection that does not exist MUST fail with the [`NOT_FOUND`](./crud/base.md#NOT_FOUND) error, with target `collection`, unless the Server creates the Collection as allowed by [`SCHEMA_COLLECTION_CREATE`](#SCHEMA_COLLECTION_CREATE).
**Rule `SCHEMA_COLLECTION_CREATE`**: MAY
A Server MAY create the Collection when a schema is written for a Collection that does not exist. A Server that does so MUST declare it.
**Rule `SCHEMA_DELETE`**: MUST
Deleting a schema MUST NOT delete the Collection or its Resources, and MUST NOT store any schema in its place. After the deletion, the Collection MUST be represented as specified in [`SCHEMA_NULL`](#SCHEMA_NULL). Data sources with their own schema follow [`SCHEMA_SOURCE_DELETE`](#SCHEMA_SOURCE_DELETE) instead.
**Rule `SCHEMA_META_SCHEMA`**: MUST
The Server MUST validate every written `schema` against the meta-schema of its dialect, the vocabulary of this extension and the ESType vocabulary ([section 1.4](#14-vocabulary)), and MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error when it is invalid.
**Rule `SCHEMA_DIALECT`**: MUST
A `schema` without the `$schema` keyword MUST be interpreted as JSON Schema 2020-12. A schema in another dialect MUST declare it with `$schema`. Servers MUST accept the ESType dialect ([ESType section 1](./estype.md#1-vocabulary)), which is JSON Schema 2020-12 with the ESType vocabulary ([`SCHEMA_VOCABULARY`](#SCHEMA_VOCABULARY)). Servers MAY support other dialects, and MUST fail with the [`NEGOTIATION`](./crud/base.md#NEGOTIATION) error for a dialect they do not support.
**Rule `SCHEMA_ID_FIELD`**: MUST
A `schema` MUST describe the `_id` Field with an explicit type, even when the Resource IDs follow the defaults of the Base Specification ([Base section 3.1.3](./crud/base.md#313-resource-ids)). The Server MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error when a written `schema` does not describe `_id`.
**Rule `SCHEMA_NO_META_FIELD`**: MUST NOT
A `schema` MUST NOT describe the `_meta` Field. The Server MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error when it does.
#### 1.3.1 Derivation
A Server may build the schema from the Data source, for example from the catalog of a relational database, the properties of a Notion data source or the fields of an Airtable table, or a sample of MongoDB documents. Derivation only happens when the Client asks for it.
**Rule `SCHEMA_DERIVE`**: MAY
The Server MAY derive the schema of a Collection from the Data source when the Client sends the "Derive" Parameter in `create` or `replace` on `@schema`. The derived schema MUST be stored and returned as any written schema.
**Rule `SCHEMA_DERIVE_EXPLICIT`**: MUST NOT
The Server MUST NOT derive a schema without the "Derive" Parameter: the `schema` sent by the Client MUST be stored as sent, except for the `dbType` values inferred as specified in [`SCHEMA_DB_TYPE_INFER`](#SCHEMA_DB_TYPE_INFER).
**Rule `SCHEMA_DERIVE_NO_SCHEMA`**: MUST
A request with the "Derive" Parameter MUST NOT include `schema`, and MAY include `validation`. The Server MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error when it includes `schema`.
**Rule `SCHEMA_DERIVE_UNSUPPORTED`**: MUST
A Server that cannot derive the schema of the Collection MUST fail with the [`UNSUPPORTED`](./crud/base.md#UNSUPPORTED) error.
### 1.4 Vocabulary
ECSON is a serialization for transport: Resources are not stored as ECSON, so a schema describes values, not their serialization. Schemas may use the [ESType](https://github.com/lingodata/estype) vocabulary, whose `estype` keyword states the ES type of a Field ([ESType section 0.2](./estype.md#02-terminology), for example `date` or `bigint`) and accepts the value in its plain JSON form and in its ECSON form. This extension adds the keywords below.
| Keyword | Value | Meaning |
|---|---|---|
| `refCollection` | a Collection Slug | with `estype: rel`, the Collection that internal references point to |
| `dbType` | a string, in the dialect of the Data source (for example `varchar(120)`, `timestamptz`, `select`) | the native type of the Field in the Data source |
**Rule `SCHEMA_VOCABULARY`**: MUST
Servers MUST support the keywords of the table above, identified by the vocabulary URI `https://lingodata.dev/crud/schema/vocab/0.1`, and the `estype` keyword of the [ESType](https://github.com/lingodata/estype) vocabulary `^0.1.0`.
> **Caution (non-normative): Provisional**
>
> The vocabulary URI and the URI of its meta-schema are provisional until the publication domain of the LingoData family is defined.
**Rule `SCHEMA_ESTYPE`**: MAY
A Field MAY have `estype`.
**Rule `SCHEMA_ESTYPE_VALIDATE`**: MUST
When a Field has `estype`, the Server MUST validate its written values, as received, against the schema compiled as specified by ESType ([ESType section 2](./estype.md#2-compilation)).
**Rule `SCHEMA_ESTYPE_TYPE`**: SHOULD
A Field with `estype` and `refCollection` or `dbType` SHOULD also have `type`.
> **Note (non-normative): Rationale**
>
> For ESType, `refCollection` and `dbType` are declared keywords like any other, so the plain branch of the compiled schema holds the declared schema instead of the default plain schema of the type ([ESType `COMPILE_PLAIN_BRANCH`](./estype.md#COMPILE_PLAIN_BRANCH)). Without `type`, `{ "estype": "rel", "refCollection": "companies" }` accepts any plain JSON value, such as `123`. For an application type, which has no default plain schema, these keywords also keep compilation from failing ([ESType `COMPILE_NO_DEFAULT`](./estype.md#COMPILE_NO_DEFAULT)), and the Field accepts any plain JSON value.
**Rule `SCHEMA_VALUE_CONVERSION`**: MUST
When a Field has `estype`, the Server MUST deserialize each written value to the native value of that type, from its ECSON form or from its plain JSON form ([ESType `CONVERT_ECSON_WITH_SCHEMA`](./estype.md#CONVERT_ECSON_WITH_SCHEMA)), after validating it ([`SCHEMA_ESTYPE_VALIDATE`](#SCHEMA_ESTYPE_VALIDATE)) and before storing it, and MUST treat a value it cannot convert as not conforming to the schema ([section 1.6](#16-validation-of-resources)).
**Rule `SCHEMA_VALUE_NO_ESTYPE`**: MUST
When a Field has no `estype` but has `dbType`, the Provider MUST convert the JSON value directly to that type of the Data source. When a Field has neither, the value MUST NOT be converted: the Provider stores it in the native type of the Data source for the value as read ([Base `REPR_NO_CONVERSION`](./crud/base.md#REPR_NO_CONVERSION), [`REPR_NATIVE_STORAGE`](./crud/base.md#REPR_NATIVE_STORAGE)).
> **Note (non-normative)**
>
> JSON Schema validates JSON values, and the compiled schema accepts both forms of each value, so validation comes first, on the value as the Client sent it, and conversion to the native value comes after.
> **Note (non-normative): Rationale**
>
> `estype` is optional: a schema made only of standard JSON Schema keywords still works, and the Provider converts JSON values to the `dbType` of each Field that has one. With `estype`, the value already arrives as a native JavaScript value, whichever form the Client sent, so Clients that send plain JSON, such as AI agents reading an MCP `inputSchema`, get the same result as Clients that send ECSON.
**Rule `SCHEMA_REF_COLLECTION`**: MUST
`refCollection` MUST be used only with `estype: rel`. The Server MUST validate that every internal reference (ECSON collection object) in the Field points to that Collection. Checking that the referenced Resource exists is out of the scope of this keyword.
**Rule `SCHEMA_DB_TYPE_INFER`**: MUST
When the Data source has its own schema and the Client does not send `dbType` for a Field, the Provider MUST infer it from `type`, `format` and `estype`, and the Server MUST store and return the inferred value in the schema.
**Rule `SCHEMA_DB_TYPE_CLIENT`**: MUST
When the Client sends `dbType`, the Provider MUST apply it, or the Server MUST fail with the [`SCHEMA_INCOMPATIBLE`](#SCHEMA_INCOMPATIBLE) error when the Data source does not accept it.
> **Note (non-normative)**
>
> In any Data source, `dbType` is a hint for the Provider and its driver, which may change how values are converted and stored: for example `decimal` in MongoDB, `select`, `multi_select` and `people` in Notion, or `singleSelect` and `multipleRecordLinks` in Airtable.
### 1.5 Data sources with their own schema
Some Data sources enforce their own schema: relational databases, such as PostgreSQL and MySQL, have tables with typed columns, and Notion data sources and Airtable tables have typed properties and fields.
**Rule `SCHEMA_SOURCE_APPLY`**: MUST
When the Data source has its own schema, writing a schema MUST change the schema of the Data source accordingly. Both changes MUST happen, or neither.
**Rule `SCHEMA_SOURCE_INCOMPATIBLE`**: MUST
A change that the Data source cannot apply, such as changing the type of a Field whose existing values cannot be converted, MUST fail with the [`SCHEMA_INCOMPATIBLE`](#SCHEMA_INCOMPATIBLE) error, without changing the schema or the Data source.
**Rule `SCHEMA_SOURCE_DELETE`**: MUST
When the Data source has its own schema, deleting the schema of a Collection MUST fail with the [`UNSUPPORTED`](./crud/base.md#UNSUPPORTED) error.
> **Note (non-normative): Rationale**
>
> The Data source would still enforce its schema, so the Collection would keep being validated after the deletion.
**Rule `SCHEMA_FORCED_STRICT`**: MAY
The Server MAY force strict validation, for example when the Data source enforces its own schema. When the Client sends `validation: lenient` for such a Collection, the Server MUST store `strict` and report the [`VALIDATION_FORCED`](#VALIDATION_FORCED) Warning.
### 1.6 Validation of Resources
The `validation` Field of a schema, chosen by whoever registers the schema, defines what happens to Resources that do not conform to it.
**Rule `SCHEMA_VALIDATE_WRITES`**: MUST
When a Collection has a registered schema, the Server MUST validate every Resource that results from `create`, `clone`, `patch` and `replace` operations on it (after the patch is applied, for `patch`), without the `_meta` Field.
**Rule `SCHEMA_NO_READ_VALIDATION`**: MUST NOT
The Server MUST NOT validate Resources on read operations.
**Rule `SCHEMA_STRICT`**: MUST
With `validation: strict`, a Resource that does not conform to the schema MUST NOT be written, and the operation MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error. Writes on several Resources follow [Base section 4.7](./crud/base.md#47-writes-on-several-resources).
**Rule `SCHEMA_LENIENT`**: MUST
With `validation: lenient`, a Resource that does not conform to the schema MUST be written, and the Server MUST report a [`SCHEMA_VIOLATION`](#SCHEMA_VIOLATION) Warning for each violation.
> **Note (non-normative)**
>
> With the strict preference of the Client ([Base `META_WARN_PREFERENCE`](./crud/base.md#META_WARN_PREFERENCE)), the [`SCHEMA_VIOLATION`](#SCHEMA_VIOLATION) Warnings make the operation fail with the [`STRICT_WARNINGS`](./crud/base.md#STRICT_WARNINGS) error. This is how a Client requires strict validation on a `lenient` schema.
**Rule `SCHEMA_VIOLATION_DETAILS`**: SHOULD
The error data of [`SCHEMA_STRICT`](#SCHEMA_STRICT) and each [`SCHEMA_VIOLATION`](#SCHEMA_VIOLATION) Warning SHOULD describe the violations as output units of the [`basic` output format](https://json-schema.org/draft/2020-12/json-schema-core#section-12.4.2) of JSON Schema, with `instanceLocation`, `keywordLocation` and `error`. `keywordLocation` refers to the schema used for validation, compiled as specified by ESType ([`SCHEMA_ESTYPE_VALIDATE`](#SCHEMA_ESTYPE_VALIDATE)).
> **Note (non-normative)**
>
> Protocols publish the compiled schema (for example [HTTP `HTTP_SCHEMA_RAW`](./crud/http.md#HTTP_SCHEMA_RAW)), so Clients can follow `keywordLocation` in it.
**Rule `SCHEMA_NO_REVALIDATION`**: MUST NOT
Changing a schema MUST NOT validate or change the existing Resources of the Collection, except for the changes required by [`SCHEMA_SOURCE_APPLY`](#SCHEMA_SOURCE_APPLY).
### 1.7 Errors and Warnings
**Rule `SCHEMA_NOT_FOUND_TARGET`**: MUST
When a Protocol lets Clients request the JSON Schema of a Collection alone, without its schema Resource, the request for a Collection without a registered schema ([`SCHEMA_NULL`](#SCHEMA_NULL)) MUST fail with the [`NOT_FOUND`](./crud/base.md#NOT_FOUND) error, with target `schema` ([Base `RES_ERROR_DATA`](./crud/base.md#RES_ERROR_DATA)).
This extension adds the following error code to those of the Base Specification ([Base `ERROR_EXTENSION_CODES`](./crud/base.md#ERROR_EXTENSION_CODES)):
| Code | Condition |
|---|---|
| `SCHEMA_INCOMPATIBLE` | The Data source cannot apply the schema change or the `dbType` sent by the Client ([`SCHEMA_DB_TYPE_CLIENT`](#SCHEMA_DB_TYPE_CLIENT), [`SCHEMA_SOURCE_INCOMPATIBLE`](#SCHEMA_SOURCE_INCOMPATIBLE)) |
It also defines the following Warning codes ([Base `WARN_EXTENSION_CODES`](./crud/base.md#WARN_EXTENSION_CODES)):
| Code | Condition |
|---|---|
| `SCHEMA_VIOLATION` | A Resource written to a `lenient` schema does not conform to it ([`SCHEMA_LENIENT`](#SCHEMA_LENIENT)) |
| `VALIDATION_FORCED` | The Client sent `validation: lenient` and the Server stored `strict` ([`SCHEMA_FORCED_STRICT`](#SCHEMA_FORCED_STRICT)) |
### 1.8 Out of scope
The following topics are left to future versions or extensions: migrations of Resources between schema versions, translation of schemas between Data sources, mapping of schemas to user interface components (a future `@ui` extension), and open schema ontologies.
## 2. References
### 2.1 Normative references
- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): requirement level key words (BCP 14)
- [JSON Schema 2020-12: Core](https://json-schema.org/draft/2020-12/json-schema-core) (sections 6.5, extending JSON Schema; 8.1.2, `$vocabulary`; 12, output formatting) and [Validation](https://json-schema.org/draft/2020-12/json-schema-validation)
- [CRUD API Base Specification](./crud/base.md#1-overview) `^0.2.0` and [Resource Metadata Extension](./crud/metadata.md#1-resource-metadata) `^0.1.0`
- [ECSON](https://github.com/lingodata/ecson) `^0.2.0`, including its References type set
- [ESType](https://github.com/lingodata/estype) `^0.1.0`: the `estype` keyword and schema compilation
### 2.2 Informative references
- [`draft-ietf-jsonschema-json-schema`](https://datatracker.ietf.org/doc/draft-ietf-jsonschema-json-schema/), the IETF work to publish JSON Schema as a standard
- [MongoDB schema validation](https://www.mongodb.com/docs/manual/core/schema-validation/) (`$jsonSchema`, `validationAction`), an example of optional validation per collection
- [OData CSDL JSON 4.01](https://docs.oasis-open.org/odata/odata-csdl-json/v4.01/odata-csdl-json-v4.01.html) (`$metadata`), [OpenAPI 3.2](https://spec.openapis.org/oas/v3.2.1.html), [PostgREST OpenAPI](https://docs.postgrest.org/en/stable/references/api/openapi.html), [Airtable base schema](https://airtable.com/developers/web/api/get-base-schema) and [Notion data sources](https://developers.notion.com/reference/retrieve-a-data-source): other ways APIs expose the schema of their data
---
# CRUD API Views Extension
Version: 0.1.0 · Status: draft · License: Apache-2.0
Source: lingodata/crud@bc225ba
## 1. Views
The **Views** extension defines Views (also called saved queries): named queries stored on the Server and executed by Clients. It is optional: Servers that do not implement it are not required to follow any rule in this document.
This extension requires the Base Specification `^0.2.0` and the Schema extension `^0.1.0` (and, through it, the Metadata extension `^0.1.0`).
A View is a "CRUD inside the CRUD": it has an identifier (its name), content (its definition) and a lifecycle of its own (created, modified and deleted). Views are managed with the operations of the Base Specification, as Resources of a reserved Collection, and executed with the `listByView` operation.
### 1.1 The `@views` Collections
**Rule `VIEW_COLLECTION`**: MUST
For each Collection, the Server MUST expose its Views as Resources of a reserved Collection named `@views`, attached to that Collection, whose Resource IDs are the View names. Every operation of the Base Specification that the Server supports on Views MUST apply to `@views`, as specified in this document.
> **Note (non-normative)**
>
> Each Protocol defines how the `@views` Collection of a Collection is addressed, for example `/orders/@views` in HTTP. Slugs never contain `@` ([Base `COLLECTION_SLUG`](./crud/base.md#COLLECTION_SLUG)), so `@views` cannot be the name of another Collection.
**Rule `VIEW_SLUG`**: MUST
Views of the same Collection MUST be uniquely identified by [Slugs](./crud/base.md#26-general-terminology).
**Rule `VIEW_ID_CONFLICT`**: MUST
A View name MUST NOT be equal to a Resource ID of the same Collection. The Server MUST fail with the [`CONFLICT`](./crud/base.md#CONFLICT) error when creating a View whose name is an existing Resource ID, or a Resource whose Resource ID is an existing View name.
> **Note (non-normative): Rationale**
>
> Protocols may address Views and Resources with the same path pattern (for example, HTTP `GET /users/active`, where `active` is a View). Forbidding equal names keeps every Resource reachable. With UUIDv7 Resource IDs, collisions are practically impossible.
**Rule `VIEW_READ`**: MUST
The Server MUST support `get` and `list` on `@views`.
**Rule `VIEW_WRITE_UNSUPPORTED`**: MUST
A write operation on `@views` that the Server cannot perform, for example on a View defined in its configuration, MUST fail with the [`UNSUPPORTED`](./crud/base.md#UNSUPPORTED) error.
> **Note (non-normative)**
>
> A Provider may store Views in the Data source itself, when the Data source has views of its own: for example a PostgreSQL view (`CREATE VIEW`) or a MongoDB view (`db.createView`) for a View without parameters.
### 1.2 View Resources
> **Tip (non-normative): Example**
>
> ```json
> {
> "_id": "sales-by-month",
> "description": "Paid orders per month of a year, optionally of one month",
> "queryFormat": "application/sql",
> "query": "SELECT date_trunc('month', created_at) AS month, count(*) AS orders, sum(total) AS total FROM orders WHERE status = 'paid' AND extract(year FROM created_at) = {{year}}{{#month}} AND extract(month FROM created_at) = {{month}}{{/month}} GROUP BY 1",
> "sort": "month",
> "params": {
> "type": "object",
> "properties": {
> "year": { "type": "integer" },
> "month": { "type": "integer", "minimum": 1, "maximum": 12 }
> },
> "required": ["year"]
> },
> "schema": {
> "type": "object",
> "properties": {
> "month": { "type": "string", "format": "date-time", "estype": "date" },
> "orders": { "type": "integer" },
> "total": { "type": "number" }
> }
> },
> "_meta": { "version": 2 }
> }
> ```
**Rule `VIEW_RESOURCE_FIELDS`**: MUST
A View Resource MUST have the Field `_id`, with the View name, and MAY have the Fields `description`, `query`, `queryFormat`, `sort`, `fields`, `params` and `schema`, as specified in this section, besides `_meta` (Metadata extension).
**Rule `VIEW_QUERY`**: MUST
`query` MUST be a Search Query in a format that `list` accepts ([Base `SEARCH_QUERY_UNQUERY`](./crud/base.md#SEARCH_QUERY_UNQUERY) and [`SEARCH_QUERY_FORMATS`](./crud/base.md#SEARCH_QUERY_FORMATS)), including the native query language of the Data source, written as a template ([section 1.3](#13-templates)). A View without `query` matches every Resource of the Collection, as `list` without a Search Query.
**Rule `VIEW_QUERY_FORMAT`**: MUST
`queryFormat` MUST be the media type of the format of `query`. It MUST be present when `query` is a string, and defaults to the UnQuery JSON syntax (`application/vnd.unquery+json`) when `query` is an object. The Server MUST fail with the [`NEGOTIATION`](./crud/base.md#NEGOTIATION) error when it does not support the format.
**Rule `VIEW_SORT_FIELDS`**: MUST
`sort` and `fields` MUST be field lists ([Base section 3.3.1](./crud/base.md#331-field-lists)), applied as the Sorting and Projection Parameters of `list`.
**Rule `VIEW_PARAMS`**: MUST
`params` MUST be a JSON Schema of type `object`, in the format of the Schema extension ([Schema `SCHEMA_DIALECT`](./crud/schema.md#SCHEMA_DIALECT) and [section 1.4](#14-execution-operation-listbyview)), with one property per parameter. Parameter names MUST be [Slugs](./crud/base.md#26-general-terminology). `required` lists the required parameters, and `default` gives the value of an omitted parameter.
**Rule `VIEW_SCHEMA`**: MAY
`schema` MAY describe each item of the Result of the View, as a JSON Schema in the format of the Schema extension. It is a hint for Clients: the Server MUST NOT fail an execution because an item does not conform to it.
> **Note (non-normative): Rationale**
>
> A View may return items with other Fields than the Resources of its Collection, such as totals, so it has its own schema. The schema of the Collection (Schema extension) describes its Resources, not the Result of its Views.
**Rule `VIEW_DEFINITION_VALIDATE`**: MUST
When a View is written, the Server MUST validate `params` and `schema` against the meta-schema of their dialect and the vocabulary of the Schema extension ([Schema `SCHEMA_META_SCHEMA`](./crud/schema.md#SCHEMA_META_SCHEMA)), and MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error when they are invalid.
### 1.3 Templates
A View is executed with the values of its parameters, which the Server inserts into `query` before running it. Templates follow [Mustache](https://github.com/mustache/spec), as specified by the Mustache specification, with one difference: values are encoded for the query format instead of being escaped as HTML.
**Rule `VIEW_TEMPLATE`**: MUST
When `query` is a string, it MUST be a Mustache template, which the Server MUST render with the parameter values as data before executing the query.
**Rule `VIEW_TEMPLATE_ENCODING`**: MUST
Every interpolation tag, including the unescaped forms `{{{name}}}` and `{{&name}}`, MUST insert the value encoded for `queryFormat` instead of HTML-escaped: as a JSON value for the UnQuery JSON syntax, as a literal for the UnQuery SQL syntax, and as a parameter bound by the Data source when it supports bound parameters. The Server MUST NOT insert a value as raw text.
> **Caution (non-normative): Injection**
>
> Parameter values come from Clients. Encoding them for the query format, or binding them as parameters of the Data source, is what prevents them from changing the query. Mustache libraries let implementations replace the HTML escape function for non-HTML formats.
**Rule `VIEW_TEMPLATE_OBJECT`**: MUST
When `query` is an object (UnQuery JSON syntax), each string that is exactly an interpolation tag, such as `"{{year}}"`, MUST be replaced by the parameter value with its type. Other strings MUST NOT be treated as templates.
> **Tip (non-normative): Example**
>
> | `query` | With `year: 2026` and without `month` |
> |---|---|
> | `{ "year": "{{year}}", "status": "paid" }` | `{ "year": 2026, "status": "paid" }` |
> | `"year = {{year}}{{#month}} AND month = {{month}}{{/month}}"` (UnQuery SQL) | `year = 2026` |
> **Note (non-normative)**
>
> Sections (`{{#name}}...{{/name}}`) include their content only when the parameter is set and not false, and repeat it for each item of a list; inverted sections (`{{^name}}...{{/name}}`) include their content only when the parameter is missing or false. Partials have no source in a View: as the Mustache specification defines, a missing partial renders as an empty string.
### 1.4 Execution: operation `listByView`
`listByView` is an operation of the `list` verb whose Subject is a View name.
**Rule `SUB_VIEW`**: MUST
The Subject MUST include a View name as specified in [section 1.1](#11-the-views-collections).
**Rule `SUB_SEARCH_QUERY_COMBO`**: MAY
The Subject MAY also include a Search Query, combined with the View as specified in [`VIEW_COMBO_QUERY`](#VIEW_COMBO_QUERY), and the values of the View parameters.
**Rule `RES_VIEW_NOT_FOUND`**: MUST
If the View does not exist, the Server MUST fail the operation with the [`NOT_FOUND`](./crud/base.md#NOT_FOUND) error, with the `view` target.
**Rule `VIEW_PARAMS_VALIDATE`**: MUST
The Server MUST validate the parameter values against `params`, after applying the `default` values, and MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error when the Client supplies a parameter the View does not declare, omits a required parameter, or supplies an invalid value.
**Rule `VIEW_PARAMS_CONVERT`**: MUST
Parameter values MUST be converted as specified by [Schema `SCHEMA_VALUE_CONVERSION`](./crud/schema.md#SCHEMA_VALUE_CONVERSION) and [`SCHEMA_VALUE_NO_ESTYPE`](./crud/schema.md#SCHEMA_VALUE_NO_ESTYPE), using the `params` schema.
The Result follows the Base rules for `list` ([`RES_RESOURCES_FOUND`](./crud/base.md#RES_RESOURCES_FOUND), [`RES_NO_RESULTS`](./crud/base.md#RES_NO_RESULTS)), and accepts the pagination, projection, sorting and custom Parameters of `list`, combined with the View as follows.
**Rule `VIEW_COMBO_QUERY`**: MAY
A View MAY be combined with a Search Query. When combined, the Server MUST apply the Search Query to the items that the View returns, so that it only narrows the Result of the View.
**Rule `VIEW_COMBO_FIELDS`**: MUST
A Projection Parameter sent by the Client MUST only narrow the `fields` of the View: the Result has the Fields present in both.
**Rule `VIEW_COMBO_SORT`**: MUST
A Sorting Parameter sent by the Client MUST be applied after the `sort` of the View, to order items that the View considers equal.
**Rule `VIEW_COMBO_UNSUPPORTED`**: MUST
A Server that cannot combine a Search Query, a Projection or a Sorting Parameter with a View MUST fail with the [`UNSUPPORTED`](./crud/base.md#UNSUPPORTED) error.
> **Note (non-normative)**
>
> Pagination applies to the items after the combination. When the query of the View aggregates, a Search Query sent by the Client filters the aggregated items, as `HAVING` does in SQL.
### 1.5 Aggregated results
**Rule `VIEW_AGGREGATED`**: MAY
The query of a View MAY aggregate, when its format allows it, and return items computed from Resources, such as totals grouped by month, which are not Resources. Rules that apply to Resources and Resource IDs (such as [`RES_WITH_IDS`](./crud/base.md#RES_WITH_IDS)) do not apply to items without a Resource ID.
> **Tip (non-normative): Example**
>
> The View `sales-by-month` of [section 1.2](#12-view-resources), with the parameter `year: 2026`, returns items such as `{ "month": { "$date": "2026-11-01T00:00:00.000Z" }, "orders": 412, "total": 15230.0 }`, ready to feed a chart.
> **Note (non-normative): Rationale**
>
> This extension defines no aggregation model: aggregation is written in the query itself, in the language of the Data source, such as `GROUP BY` with `date_trunc` in PostgreSQL or `$group` with `$dateTrunc` in MongoDB. This keeps Views independent of the Data source without imposing a new format. UnQuery only filters, so aggregated Views use a native query format.
### 1.6 Errors
This extension adds the `view` target to the [`NOT_FOUND`](./crud/base.md#NOT_FOUND) error code of the Base Specification, and reports invalid View definitions and parameters with its [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error code.
> **Note (non-normative): Rationale**
>
> Views are a CRUD inside the CRUD, with their own identity, content and lifecycle, which not every Server needs, so they are an extension.
### 1.7 Out of scope
Materialized Views (stored results) and the presentation of Views (table, board, calendar, chart and other types of user interface) are left to future versions or extensions, such as a future `@ui` extension.
## 2. References
### 2.1 Normative references
- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): requirement level key words (BCP 14)
- [CRUD API Base Specification](./crud/base.md#1-overview) `^0.2.0`, [Schema extension](./crud/schema.md#1-schemas) `^0.1.0` and [Resource Metadata extension](./crud/metadata.md#1-resource-metadata) `^0.1.0`
- [Mustache specification](https://github.com/mustache/spec): templates (interpolation, sections, inverted sections, partials)
- [JSON Schema 2020-12](https://json-schema.org/draft/2020-12/json-schema-core), through the Schema extension
- [UnQuery](https://github.com/lingodata/unquery) and [ECSON](https://github.com/lingodata/ecson)
### 2.2 Informative references
- [RFC 6922](https://www.rfc-editor.org/rfc/rfc6922): the `application/sql` media type, used in examples
- [PostgreSQL `CREATE VIEW`](https://www.postgresql.org/docs/current/sql-createview.html) and [`date_trunc`](https://www.postgresql.org/docs/current/functions-datetime.html); [MongoDB views](https://www.mongodb.com/docs/manual/core/views/) and [`$dateTrunc`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateTrunc/): native views and aggregation in Data sources
- [Notion views API](https://developers.notion.com/reference/list-views), [Airtable views](https://airtable.com/developers/web/api/list-views) and [NocoDB views](https://nocodb.com/apis/v2/meta): saved views in other APIs
- [OData Data Aggregation 4.0](https://docs.oasis-open.org/odata/odata-data-aggregation-ext/v4.0/odata-data-aggregation-ext-v4.0.html) and [OData parameter aliases](https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html): aggregation and named parameters in URLs
- [mustache.js](https://github.com/janl/mustache.js): replacing the escape function for non-HTML formats
---
# CRUD API HTTP Protocol
Version: 0.2.0 · Status: draft · License: Apache-2.0
Source: lingodata/crud@bc225ba
## 1. Overview
This Protocol specification maps the [CRUD API Base Specification](./crud/base.md#1-overview) and its extensions to HTTP ([RFC 9110](https://www.rfc-editor.org/rfc/rfc9110)). It is part of the **LingoData** family.
| Concept | HTTP |
|---|---|
| Operations | methods on URL paths ([section 2](#2-endpoints)) |
| Search Queries and Parameters | query string, following UnQuery, and the `QUERY` method body ([section 3](#3-query-string)) |
| Metadata and content negotiation | header fields ([section 4](#4-headers-and-metadata)) |
| Errors | status codes and Problem Details bodies ([section 5](#5-errors)) |
| Asynchronous operations | `202`, operation URLs, Server-Sent Events and Standard Webhooks callbacks ([section 6](#6-asynchronous-operations)) |
| Schemas | the `/@schema` Collection, `describedby` links and `application/schema+json` ([section 7](#7-schemas)) |
### 1.1 Conventions
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)) when, and only when, they appear in all capitals, as shown here.
### 1.2 Supported specifications
**Rule `HTTP_SPEC_RANGES`**: MUST
This specification supports the Base Specification `^0.2.0` and the extensions Asynchronous operations `^0.1.0`, Metadata `^0.1.0`, Relationships `^0.1.0` and Views `^0.1.0`.
**Rule `HTTP_EXTENSION_SECTIONS`**: MUST
Rules that map an extension apply only to Servers that support that extension, and are marked as such. A Server that does not support an extension MUST ignore the rules that map it.
| Rules | Extension |
|---|---|
| `listByView` endpoint, View management and View parameters (sections 2, 2.5 and 3.3) | Views |
| `@expand` ([section 3.1](#31-control-parameters)) | Relationships |
| `ETag`, `Last-Modified`, `If-Match`, `If-None-Match` ([section 4.6](#46-resource-metadata)) | Metadata |
| [Section 6](#6-asynchronous-operations) | Asynchronous operations |
## 2. Endpoints
Each operation of the Base Specification and of the extensions is an HTTP method on a URL path, relative to the base URL of the API.
| Operation | Method and path | Specification |
|---|---|---|
| `get` | `GET /:collection/:id` | Base |
| `list` | `GET /:collection`, or `QUERY /:collection` | Base |
| `create` | `POST /:collection` | Base |
| `clone` | `POST /:collection/:id/clone` | Base |
| `patchById` | `PATCH /:collection/:id` | Base |
| `patchByQuery` | `PATCH /:collection` | Base |
| `replaceById` | `PUT /:collection/:id` | Base |
| `replaceByQuery` | `PUT /:collection` | Base |
| `deleteById` | `DELETE /:collection/:id` | Base |
| `deleteByQuery` | `DELETE /:collection` | Base |
| `listByView` | `GET /:collection/:view`, or `QUERY /:collection/:view` | Views (extension) |
**Rule `HTTP_ENDPOINTS`**: MUST
Servers MUST expose each operation they support with the method and path in the table above, where `:collection` is the Collection Slug, `:id` the Resource ID and `:view` the View name.
> **Note (non-normative)**
>
> Discovering which Collections an API exposes is defined by the Schema extension (`GET /@schema`, [section 7](#7-schemas)).
### 2.1 Paths
**Rule `HTTP_PATH_ID_ENCODING`**: MUST
The `:id` segment MUST be percent-encoded as required by [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986). Composite Resource IDs ([Base `ID_COMP_KEY_URLENCODED`](./crud/base.md#ID_COMP_KEY_URLENCODED)) are encoded as a whole in the segment.
> **Tip (non-normative): Example**
>
> The composite Resource ID `store=12&number=345` is addressed as `GET /orders/store%3D12%26number%3D345`. A `list` with the same Fields as conditions, `GET /orders?store=12&number=345`, matches the same Resource, but returns a list (with zero or one Resource) and never fails with `404`.
**Rule `HTTP_PATH_VIEW_PRECEDENCE`**: MUST
For `GET /:collection/:segment` and `QUERY /:collection/:segment`, when the Views extension is supported and a View named `:segment` exists in the Collection, the Server MUST execute the View; otherwise, `:segment` MUST be interpreted as a Resource ID.
> **Note (non-normative)**
>
> View names and Resource IDs of the same Collection never collide ([Views `VIEW_ID_CONFLICT`](./crud/views.md#VIEW_ID_CONFLICT)).
**Rule `HTTP_PATH_RESERVED`**: MUST
Path segments starting with `@` right after `/:collection` (for example `/:collection/@views`) are reserved for extensions, to expose resources about the Collection itself, and MUST NOT be interpreted as Resource IDs or View names.
> **Note (non-normative)**
>
> Resource IDs are Slugs ([Base `ID_SLUG`](./crud/base.md#ID_SLUG)) and never start with `@`. Extensions use this space for their own resources, such as the management of Views (`/:collection/@views`) and of schemas (`/:collection/@schema`, [section 7](#7-schemas)), and, in the future, user interfaces (`/:collection/@ui`).
### 2.2 The `QUERY` method
**Rule `HTTP_QUERY_METHOD`**: MAY
Servers MAY support the `QUERY` method ([RFC 10008](https://www.rfc-editor.org/rfc/rfc10008)) for `list` and `listByView`, with the Search Query in the request body, labeled with its media type (such as `application/vnd.unquery+json` or `text/vnd.unquery.sql`). Conditions in the query string, if any, are combined with the body with `and`.
> **Note (non-normative)**
>
> `QUERY` is safe and idempotent, like `GET`, and carries the Search Query in the body, which avoids URL length limits.
### 2.3 Writes on several Resources
**Rule `HTTP_BYQUERY_FILTER_REQUIRED`**: MUST
`PATCH`, `PUT` and `DELETE` on `/:collection` without any condition MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error. To affect every Resource of the Collection, the Client MUST send the empty filter `@q={}` explicitly.
> **Note (non-normative): Rationale**
>
> `DELETE /orders` without a filter would delete every order. Requiring an explicit empty filter makes that intent visible in the request.
### 2.4 The `clone` operation
**Rule `HTTP_CLONE`**: MUST
`POST /:collection/:id/clone` MAY carry a patch in the body, as a JSON Patch ([RFC 6902](https://www.rfc-editor.org/rfc/rfc6902), `application/json-patch+json`) or a JSON Merge Patch ([RFC 7396](https://www.rfc-editor.org/rfc/rfc7396), `application/merge-patch+json`), and MUST respond with `201 Created` and a `Location` header with the URL of the copy.
### 2.5 Managing Views
> **Caution (non-normative): Requires the Views extension**
>
> This section applies only to Servers that support the [Views extension](./crud/views.md#1-views) (`views ^0.1.0`).
The `@views` Collection of each Collection ([Views `VIEW_COLLECTION`](./crud/views.md#VIEW_COLLECTION)) uses the endpoints of [section 2](#2-endpoints) under `/:collection/@views`, with the View name as the Resource ID.
| Operation | Method and path |
|---|---|
| `list` | `GET /:collection/@views` |
| `get` | `GET /:collection/@views/:view` |
| `create` | `POST /:collection/@views` |
| `clone` | `POST /:collection/@views/:view/clone` |
| `patchById`, `patchByQuery` | `PATCH /:collection/@views/:view`, `PATCH /:collection/@views` |
| `replaceById`, `replaceByQuery` | `PUT /:collection/@views/:view`, `PUT /:collection/@views` |
| `deleteById`, `deleteByQuery` | `DELETE /:collection/@views/:view`, `DELETE /:collection/@views` |
**Rule `HTTP_VIEWS_ENDPOINTS`**: MUST
Servers MUST expose the operations on Views they support with the method and path in the table above.
> **Tip (non-normative): Example: listing the Views of a Collection**
>
> ```http
> GET /orders/@views?@fields=_id,description
> ```
**Rule `HTTP_VIEW_DESCRIBEDBY`**: SHOULD
Responses of `listByView` for a View with a `schema` ([Views `VIEW_SCHEMA`](./crud/views.md#VIEW_SCHEMA)) SHOULD include a `Link` header field with the `describedby` relation to `/:collection/@views/:view`.
> **Tip (non-normative): Example: executing a View and its describedby link**
>
> ```http
> GET /orders/sales-by-month?year=2026
>
> HTTP/1.1 200 OK
> Link: ; rel="describedby"
> ```
**Rule `HTTP_VIEW_SCHEMA_RAW`**: MUST
`GET /:collection/@views/:view` with `Accept: application/schema+json` MUST respond with only the value of the `schema` Field of the View, compiled as specified by ESType ([ESType section 2](./estype.md#2-compilation)), labeled `application/schema+json`. When the View has no `schema`, the Server MUST fail with the [`NOT_FOUND`](./crud/base.md#NOT_FOUND) error, with target `schema`.
> **Tip (non-normative): Example: reading only the schema of a View**
>
> ```http
> GET /orders/@views/sales-by-month
> Accept: application/schema+json
>
> HTTP/1.1 200 OK
> Content-Type: application/schema+json
>
> { "type": "object", "properties": { "month": { "type": "string" } } }
> ```
## 3. Query string
The query string carries the Search Query and the Parameters of an operation. It follows the query string mapping of [UnQuery](https://github.com/lingodata/unquery) ([UnQuery section 4](./unquery.md#4-query-string-mapping)): keys starting with `@` are control parameters, and other keys are conditions on Fields.
### 3.1 Control parameters
**Rule `HTTP_CONTROL_PARAMS`**: MUST
Servers MUST accept the Parameters they support with the control parameter names and values in the table below.
| Parameter | Value | Implements |
|---|---|---|
| `@q` | a complete UnQuery filter, in JSON or SQL syntax | [Base `SEARCH_QUERY_UNQUERY`](./crud/base.md#SEARCH_QUERY_UNQUERY) |
| `@fields` | a field list ([Base section 3.3.1](./crud/base.md#331-field-lists)) | [Base `PROJECTION_FIELD_LIST`](./crud/base.md#PROJECTION_FIELD_LIST) |
| `@sort` | a field list | [Base `SORTING_FIELD_LIST`](./crud/base.md#SORTING_FIELD_LIST) |
| `@page`, `@limit` | integers, `@page` from 1 and `@limit` from 1 | [Base `PAGINATION_PAGE`](./crud/base.md#PAGINATION_PAGE) |
| `@offset` | integer from 0 | [Base `PAGINATION_OFFSET`](./crud/base.md#PAGINATION_OFFSET) |
| `@cursor` | the opaque cursor of the next page | [Base `PAGINATION_CURSOR`](./crud/base.md#PAGINATION_CURSOR) |
| `@expand` | a field list of relationship Fields | [Relationships `REL_EXPAND`](./crud/relationships.md#REL_EXPAND) (requires the Relationships extension) |
| `@derive` | `true` or `false` | [Schema `SCHEMA_DERIVE`](./crud/schema.md#SCHEMA_DERIVE) (requires the Schema extension, [section 7](#7-schemas)) |
**Rule `HTTP_PARAM_VALUES`**: MUST
Integers MUST be written in decimal and booleans as `true` or `false`. An invalid value MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error.
Preconditions, such as the expected match count and the denial of upserts, are header fields ([section 4.8](#48-preconditions)).
> **Tip (non-normative): Example**
>
> `GET /orders?status=paid&total=>100&@sort=-createdAt&@fields=_id,total&@page=2&@limit=20`
### 3.2 Custom parameters
**Rule `HTTP_CUSTOM_PARAMS`**: MUST
Custom Parameters ([Base section 3.3.3](./crud/base.md#333-custom-parameters)) MUST be written as `@` followed by their name, and their names MUST NOT be equal to the control parameters of this specification.
**Rule `HTTP_UNKNOWN_CONTROL`**: MUST
A key starting with `@` that is neither a control parameter nor a Custom Parameter of the Server MUST be ignored and reported as a [`PARAM_IGNORED`](./crud/base.md#PARAM_IGNORED) Warning ([Base `PARAM_CUSTOM_UNKNOWN`](./crud/base.md#PARAM_CUSTOM_UNKNOWN)); with the strict preference, the operation fails.
> **Note (non-normative)**
>
> This is the handling that [UnQuery `QS_CONTROL_UNKNOWN`](./unquery.md#QS_CONTROL_UNKNOWN) leaves to the protocol. Custom Parameters keep the `@` prefix so that Servers can tell unknown ones apart from conditions and report them.
### 3.3 View parameters
> **Caution (non-normative): Requires the Views extension**
>
> This section applies only to Servers that support the [Views extension](./crud/views.md#1-views) (`views ^0.1.0`).
**Rule `HTTP_VIEW_PARAMS`**: MUST
In [`listByView`](./crud/views.md#14-execution-operation-listbyview), keys equal to a parameter declared by the View ([Views `VIEW_PARAMS`](./crud/views.md#VIEW_PARAMS)) MUST be interpreted as View parameters, without a prefix, and excluded from filtering ([UnQuery `QS_IGNORE_LIST`](./unquery.md#QS_IGNORE_LIST)). Every other key follows [section 3.1](#31-control-parameters) and UnQuery.
**Rule `HTTP_VIEW_PARAM_VALUES`**: MUST
View parameter values MUST be read from the query string as UnQuery values ([UnQuery section 4](./unquery.md#4-query-string-mapping)) and then converted with the `params` schema of the View ([Views `VIEW_PARAMS_CONVERT`](./crud/views.md#VIEW_PARAMS_CONVERT)).
> **Tip (non-normative): Example**
>
> `GET /orders/sales-by-month?year=2026&month=11&status=paid` runs the View `sales-by-month` with the parameters `year` and `month`, filtered by `status`.
> **Note (non-normative)**
>
> A declared View parameter takes precedence over a Field with the same name, as a View name takes precedence over a Resource ID ([section 2.1](#21-paths)). To filter by such a Field, use `@q`, for example `@q={"year":2025}`.
### 3.4 Conditions on single Resources
**Rule `HTTP_CONDITIONS_BY_ID`**: MUST
Conditions in the query string of endpoints on a single Resource (`/:collection/:id`) MUST be ignored and reported as a [`CONDITION_IGNORED`](#CONDITION_IGNORED) Warning, with the key in `parameter`; with the strict preference, the operation fails.
> **Note (non-normative)**
>
> `CONDITION_IGNORED` is a Warning code of this specification ([Base `WARN_EXTENSION_CODES`](./crud/base.md#WARN_EXTENSION_CODES)). It differs from [`PARAM_IGNORED`](./crud/base.md#PARAM_IGNORED): the ignored key is a condition on a Field, such as a tracking parameter, not an unknown control parameter.
> **Note (non-normative): Rationale**
>
> Single-Resource operations have no Search Query, so conditions there are usually unrelated keys, such as tracking parameters (`utm_source`). Ignoring them keeps links working; the Warning lets Clients notice mistakes.
## 4. Headers and metadata
Operation Metadata ([Base section 3.4](./crud/base.md#34-metadata)) is carried in HTTP header fields. New header fields defined by this specification have no `X-` prefix ([RFC 6648](https://www.rfc-editor.org/rfc/rfc6648)) and, when structured, use Structured Field Values ([RFC 9651](https://www.rfc-editor.org/rfc/rfc9651)).
### 4.1 Content negotiation
**Rule `HTTP_ACCEPT`**: SHOULD
Clients SHOULD send the `Accept` header field with the Resource Representations they accept (`application/vnd.ecson+json`, `application/json`). Servers MUST respond with a matching `Content-Type`, chosen as specified in [section 4.1.1](#411-choosing-the-resource-representation), or fail with the [`NEGOTIATION`](./crud/base.md#NEGOTIATION) error.
**Rule `HTTP_PLAIN_JSON`**: MUST
`application/json` MUST be treated as the plain JSON Resource Representation ([Base `REPR_PLAIN_JSON`](./crud/base.md#REPR_PLAIN_JSON)), and `application/vnd.ecson+json` as ECSON, both in responses and in request bodies.
**Rule `HTTP_CONTENT_TYPE`**: MUST
Request bodies MUST be labeled with `Content-Type`: a Resource Representation for Resources, `application/json-patch+json` or `application/merge-patch+json` for patches, and an UnQuery media type for Search Queries in `QUERY` requests.
**Rule `HTTP_ACCEPT_QUERY`**: SHOULD
Servers that support the `QUERY` method SHOULD advertise the Search Query formats they accept in the `Accept-Query` response header field ([RFC 10008](https://www.rfc-editor.org/rfc/rfc10008)).
**Rule `HTTP_PREFER`**: MUST
The return preference ([Base `META_PREFER_REPRESENTATION`](./crud/base.md#META_PREFER_REPRESENTATION)) MUST be sent as `Prefer: return=representation` or `Prefer: return=minimal`, and the strict preference ([Base `META_WARN_PREFERENCE`](./crud/base.md#META_WARN_PREFERENCE)) as `Prefer: handling=strict` (with `handling=lenient` as the default), as defined by [RFC 7240](https://www.rfc-editor.org/rfc/rfc7240).
**Rule `HTTP_PREFER_ALLOW`**: MUST
The Warning codes that remain Warnings under the strict preference ([Base `META_WARN_PREFERENCE_EXCEPT`](./crud/base.md#META_WARN_PREFERENCE_EXCEPT)) MUST be sent as the `allow` parameter of `handling=strict`, as a quoted string of codes separated by spaces.
> **Tip (non-normative): Example**
>
> ```http
> Prefer: handling=strict; allow="LIMIT_REDUCED ORDER_NOT_PRESERVED"
> ```
> **Note (non-normative)**
>
> RFC 7240 lets preferences carry parameters, and Servers ignore what they do not recognize. A Server that does not know the `allow` parameter applies `handling=strict` to every Warning, which fails more operations, never fewer.
**Rule `HTTP_PREFERENCE_APPLIED`**: SHOULD
Servers SHOULD report the preferences they applied in the `Preference-Applied` response header field.
#### 4.1.1 Choosing the Resource Representation
The `Accept` header field decides between ECSON (`application/vnd.ecson+json`) and plain JSON (`application/json`) in responses. ECSON is the default: plain JSON is sent only when the Client asks for it explicitly.
**Rule `HTTP_ACCEPT_WEIGHT`**: MUST
The Server MUST give ECSON and plain JSON the weight (`q`) of the most specific media range of `Accept` that matches each of them ([RFC 9110, section 12.5.1](https://www.rfc-editor.org/rfc/rfc9110#section-12.5.1)), where `*/*` and `application/*` match both. A Representation that no media range matches, or whose weight is `0`, is not accepted.
**Rule `HTTP_ACCEPT_ECSON_DEFAULT`**: MUST
The Server MUST respond in ECSON, if it supports ECSON, when there is no `Accept` header field, when `Accept` has only wildcard media ranges (`*/*`, `application/*`), and when ECSON and plain JSON have the same weight ([Base `META_RES_FALLBACK`](./crud/base.md#META_RES_FALLBACK) and [`META_RES_TIE`](./crud/base.md#META_RES_TIE)).
**Rule `HTTP_ACCEPT_PLAIN_JSON`**: MUST
The Server MUST respond in plain JSON only when ECSON is not accepted, or when plain JSON has a higher weight than ECSON.
| `Accept` sent by the Client | Response `Content-Type` | Why |
|---|---|---|
| (none) | `application/vnd.ecson+json` | no declaration |
| `*/*` (default of curl and of `fetch`) | `application/vnd.ecson+json` | only wildcards |
| `application/json, text/plain, */*` (default of [axios](https://axios-http.com/docs/req_config)) | `application/vnd.ecson+json` | same weight: `*/*` also accepts ECSON |
| `application/json` | `application/json` | ECSON is not accepted |
| `application/json, */*;q=0.8` | `application/json` | plain JSON has the higher weight |
| `application/json, application/vnd.ecson+json;q=0` | `application/json` | ECSON is refused |
| `application/vnd.ecson+json` | `application/vnd.ecson+json` | explicit |
> **Caution (non-normative): Clients that need plain JSON**
>
> Most HTTP clients send `*/*` by default, alone or beside `application/json`, and receive ECSON. A Client that needs plain values MUST send `Accept: application/json` without wildcards, or give ECSON a lower weight, as in the table above. ECSON responses are valid JSON ([RFC 8259](https://www.rfc-editor.org/rfc/rfc8259)) with the `+json` suffix ([RFC 6839](https://www.rfc-editor.org/rfc/rfc6839)), so generic JSON parsers read them; only typed values look different, such as `{ "$date": "2026-11-06T12:00:00.000Z" }` instead of `"2026-11-06T12:00:00.000Z"`.
**Rule `HTTP_VARY_ACCEPT`**: SHOULD
Responses whose Representation depends on `Accept` SHOULD include `Vary: Accept` ([RFC 9110, section 12.5.5](https://www.rfc-editor.org/rfc/rfc9110#section-12.5.5)), so that caches do not serve an ECSON response to a plain JSON Client.
> **Caution (non-normative): Request bodies**
>
> `Accept` only chooses the response. The request body is read according to its own `Content-Type` ([`HTTP_PLAIN_JSON`](#HTTP_PLAIN_JSON)): a body labeled `application/json` is plain JSON, and objects such as `{ "$date": "..." }` in it are plain objects, not dates, except in Fields with `estype` ([Schema `SCHEMA_VALUE_CONVERSION`](./crud/schema.md#SCHEMA_VALUE_CONVERSION), [ESType `CONVERT_FORM_PER_FIELD`](./estype.md#CONVERT_FORM_PER_FIELD)). Many clients label every JSON body `application/json` (for example, [axios](https://github.com/axios/axios) does so for objects). A Client that sends typed values MUST label the body `application/vnd.ecson+json`.
### 4.2 Specification versions
**Rule `HTTP_CRUD_SPECS`**: MUST
Servers MUST send the `CRUD-Specs` response header field, a Structured Field Dictionary whose keys are specification names and whose values are Strings with the version ([Base `META_CRUD_SPECS`](./crud/base.md#META_CRUD_SPECS)).
**Rule `HTTP_CRUD_REQUIRE`**: MAY
Clients MAY send the `CRUD-Require` request header field, a Structured Field Dictionary whose keys are specification names and whose values are Strings with node-semver ranges ([Base `META_CRUD_REQUIRE`](./crud/base.md#META_CRUD_REQUIRE)).
> **Tip (non-normative): Example**
>
> ```http
> CRUD-Require: base="^0.2.0", async="~0.1.0"
>
> CRUD-Specs: base="0.2.0", async="0.1.0", relationships="0.1.0"
> ```
### 4.3 Counts
**Rule `HTTP_COUNTS`**: SHOULD
The Matched Count and the Modified Count ([Base `META_MATCHED_COUNT`](./crud/base.md#META_MATCHED_COUNT) and [`META_MODIFIED_COUNT`](./crud/base.md#META_MODIFIED_COUNT)) SHOULD be sent in the `Matched-Count` and `Modified-Count` response header fields, as decimal integers.
### 4.4 Pagination links
**Rule `HTTP_PAGINATION_LINKS`**: SHOULD
Paginated responses SHOULD include a `Link` header field ([RFC 8288](https://www.rfc-editor.org/rfc/rfc8288)) with the URLs of the `next` and `prev` pages and, when known, the `first` and `last` pages. With cursor pagination, the `next` link MUST carry the cursor of the next page ([Base `PAGINATION_CURSOR`](./crud/base.md#PAGINATION_CURSOR)), and its absence means there is no next page.
> **Tip (non-normative): Example**
>
> ```http
> Link: ; rel="next", ; rel="prev"
> ```
### 4.5 Written Resources
**Rule `HTTP_LOCATION`**: MUST
When a write operation targets a single Resource, the Server MUST send its URL in `Content-Location` when the response carries the Resource (`return=representation`), and in `Location` otherwise.
### 4.6 Resource metadata
> **Caution (non-normative): Requires the Metadata extension**
>
> This section applies only to Servers that support the [Metadata extension](./crud/metadata.md#1-resource-metadata) (`metadata ^0.1.0`).
When the Metadata extension is supported, Resource metadata is also mirrored in standard header fields for operations on a single Resource ([Metadata `META_PROTOCOL_MIRROR`](./crud/metadata.md#META_PROTOCOL_MIRROR)).
**Rule `HTTP_META_ETAG`**: SHOULD
The `ETag` response header field SHOULD be the strong entity tag of `_meta.hash`, and `Last-Modified` the timestamp of the `updated` event (or of `created`, before any update).
**Rule `HTTP_META_IF_MATCH`**: SHOULD
Servers SHOULD support `If-Match` on write operations as the expected hash ([Metadata `META_DOC_CONDITIONAL`](./crud/metadata.md#META_DOC_CONDITIONAL)), failing with `412 Precondition Failed` ([`PRECONDITION_FAILED`](./crud/metadata.md#PRECONDITION_FAILED)) when it does not match.
**Rule `HTTP_META_IF_NONE_MATCH`**: MAY
Servers MAY support `If-None-Match` on `GET /:collection/:id`, responding `304 Not Modified` without a body when the hash matches.
### 4.7 Correlation and Warnings
#### 4.7.1 Correlation ID
**Rule `HTTP_CORRELATION_ID`**: SHOULD
The Correlation ID ([Base `META_CORRELATION_ID`](./crud/base.md#META_CORRELATION_ID)) SHOULD be sent in the `Correlation-ID` header field, in `uuid-hex` format, by Clients in requests and by Servers in responses.
**Rule `HTTP_TRACEPARENT`**: SHOULD
Servers SHOULD accept and propagate the `traceparent` header field of [W3C Trace Context](https://www.w3.org/TR/trace-context/). When a request has `traceparent` and no `Correlation-ID`, the Correlation ID MUST be its `trace-id`, formatted as `uuid-hex`. When both are present and differ, `Correlation-ID` prevails.
> **Tip (non-normative): Example**
>
> The Correlation ID `0190a5f2-7c3e-7b1a-9f4e-2d8c6b1e4a90` and the trace ID in `traceparent: 00-0190a5f27c3e7b1a9f4e2d8c6b1e4a90-00f067aa0ba902b7-01` are the same 16 bytes, so CRUD operations appear in tracing tools without any mapping.
#### 4.7.2 Warnings
**Rule `HTTP_WARNING`**: MUST
Warnings ([Base `META_WARN`](./crud/base.md#META_WARN)) MUST be sent in the `Warning` response header field as a Structured Field List of Strings, each String being a Warning code with a `message` parameter. Several Warnings MAY be sent in one field value, separated by commas, or in several `Warning` field lines, which are equivalent.
**Rule `HTTP_WARNING_DATA`**: MUST
The other members of a Warning ([Base `WARN_DATA`](./crud/base.md#WARN_DATA)), such as `parameter`, `field`, `id` and `error`, MUST be sent as parameters of its item, with String values.
> **Tip (non-normative): Example**
>
> ```http
> Warning: "PARAM_IGNORED";message="Unknown parameter @srot";parameter="@srot", "LIMIT_REDUCED";message="limit reduced to 100";parameter="@limit"
> ```
> **Caution (non-normative): Compatibility**
>
> This specification redefines the `Warning` header field, which [RFC 9111](https://www.rfc-editor.org/rfc/rfc9111#section-5.5) obsoleted for HTTP caching, with a different syntax (`299 - "text"`). Old caches and intermediaries may still process or remove it.
### 4.8 Preconditions
Preconditions make a write operation fail, without writing, when the current state is not the one the Client expects. They are header fields, as HTTP conditional requests are, and fail with `412 Precondition Failed`.
**Rule `HTTP_EXPECT_MATCH`**: MUST
The expected match count ([Base `PARAM_EXPECT_MATCH`](./crud/base.md#PARAM_EXPECT_MATCH)) MUST be sent in the `Expect-Match` request header field, as a decimal integer. When it does not match, the Server MUST respond `412 Precondition Failed` with the [`EXPECT_MISMATCH`](./crud/base.md#EXPECT_MISMATCH) code.
**Rule `HTTP_DENY_UPSERT`**: MUST
The denial of upserts ([Base `PARAM_DENY_UPSERT`](./crud/base.md#PARAM_DENY_UPSERT)) MUST be sent as `If-Match: *` on `PUT /:collection/:id`, which by [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110#section-13.1.1) is false when the Resource does not exist. The Server MUST then respond `412 Precondition Failed` with the [`UPSERT_DENIED`](./crud/base.md#UPSERT_DENIED) code.
> **Tip (non-normative): Example**
>
> ```http
> PUT /customers/0190a5f2-1111-7000-8000-000000000001
> If-Match: *
>
> PATCH /orders?status=pending
> Expect-Match: 1
> ```
> The first request replaces the customer only if it exists; the second patches only if exactly one pending order matches.
> **Note (non-normative)**
>
> `If-None-Match: *` on `PUT /:collection/:id` has the opposite effect, also defined by RFC 9110: the Resource is created only if it does not exist yet.
## 5. Errors
**Rule `HTTP_ERROR_STATUS`**: MUST
Servers MUST respond to failed operations with the status code mapped to the error code in the table below ([Base `ERROR_PROTOCOL_MAPPING`](./crud/base.md#ERROR_PROTOCOL_MAPPING)).
| Error code | Status |
|---|---|
| [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) | `400 Bad Request`, or `422 Unprocessable Content` for Resources that do not conform to a `strict` schema ([section 7](#7-schemas)) |
| [`INVALID_PATCH`](./crud/base.md#INVALID_PATCH) | `400 Bad Request` when the patch is malformed, `422 Unprocessable Content` when it cannot be applied ([RFC 5789](https://www.rfc-editor.org/rfc/rfc5789)) |
| [`NOT_FOUND`](./crud/base.md#NOT_FOUND) | `404 Not Found` |
| [`CONFLICT`](./crud/base.md#CONFLICT) | `409 Conflict` |
| [`EXPECT_MISMATCH`](./crud/base.md#EXPECT_MISMATCH) | `412 Precondition Failed` |
| [`UPSERT_DENIED`](./crud/base.md#UPSERT_DENIED) | `412 Precondition Failed` |
| [`NEGOTIATION`](./crud/base.md#NEGOTIATION) | `406 Not Acceptable` for the response format, `415 Unsupported Media Type` for the request format, `400 Bad Request` for specification versions |
| [`UNSUPPORTED`](./crud/base.md#UNSUPPORTED) | `405 Method Not Allowed`, with an `Allow` header field, for a method not supported on the endpoint; `501 Not Implemented` for other features and operators |
| [`STRICT_WARNINGS`](./crud/base.md#STRICT_WARNINGS) | `422 Unprocessable Content` |
| [`ACCESS_DENIED`](./crud/base.md#ACCESS_DENIED) | `403 Forbidden`, or `401 Unauthorized` when the Client is not authenticated |
| [`INTERNAL`](./crud/base.md#INTERNAL) | `500 Internal Server Error`, or `503 Service Unavailable`, with `Retry-After`, when the Data source is unavailable |
| [`PRECONDITION_FAILED`](./crud/metadata.md#PRECONDITION_FAILED) (Metadata) | `412 Precondition Failed` |
| [`SCHEMA_INCOMPATIBLE`](./crud/schema.md#SCHEMA_INCOMPATIBLE) (Schema) | `409 Conflict` |
**Rule `HTTP_ERROR_BODY`**: SHOULD
Error bodies SHOULD be Problem Details objects ([RFC 9457](https://www.rfc-editor.org/rfc/rfc9457)) labeled `application/problem+json`, with the `code` and `target` members of [Base `ERROR_PROBLEM_DETAILS`](./crud/base.md#ERROR_PROBLEM_DETAILS).
> **Tip (non-normative): Example**
>
> ```http
> HTTP/1.1 404 Not Found
> Content-Type: application/problem+json
>
> { "type": "about:blank", "title": "Not Found", "status": 404,
> "detail": "Order 0190a5f2-7c3e-7b1a-9f4e-2d8c6b1e4a90 not found",
> "code": "NOT_FOUND", "target": "resource" }
> ```
## 6. Asynchronous operations
> **Caution (non-normative): Requires the Asynchronous operations extension**
>
> This section maps the **[Asynchronous operations extension](./crud/async.md#1-asynchronous-operations)** (`async ^0.1.0`) to HTTP. It applies only to Servers that support that extension; Servers that do not support it ignore this section, and every operation is synchronous.
### 6.1 Negotiation
**Rule `HTTP_ASYNC_PREFER`**: MUST
A Client that prefers asynchronous processing ([Async `ASYNC_CLIENT_PREFER`](./crud/async.md#ASYNC_CLIENT_PREFER)) MUST send `Prefer: respond-async` ([RFC 7240](https://www.rfc-editor.org/rfc/rfc7240)).
**Rule `HTTP_ASYNC_EXPECT`**: MUST
A Client that requires asynchronous processing ([Async `ASYNC_CLIENT_REQUIRE`](./crud/async.md#ASYNC_CLIENT_REQUIRE)) MUST send `Expect: 202-accepted`.
**Rule `HTTP_ASYNC_417`**: MUST
When the negotiation fails ([Async `ASYNC_SERVER_MATRIX`](./crud/async.md#ASYNC_SERVER_MATRIX)), the Server MUST respond `417 Expectation Failed` with the [`NEGOTIATION`](./crud/base.md#NEGOTIATION) code.
### 6.2 Accepting an operation
**Rule `HTTP_ASYNC_202`**: MUST
When the Server runs an operation asynchronously, it MUST respond `202 Accepted`, with the Operation ID in the `Operation-ID` header field and the URL of the operation state in the `Location` header field.
**Rule `HTTP_ASYNC_OPERATIONS_PATH`**: SHOULD
When the operation state is served by the same API, its URL SHOULD be `/@operations/:operationId`, relative to the base URL of the API. Servers MAY use any other URL, including on another host.
### 6.3 Operation state
**Rule `HTTP_ASYNC_POLL_425`**: MUST
While the operation is pending, `GET` on the operation URL MUST respond `425 Too Early`, with the state (`status: "pending"`) and, when known, the progress in the body, and SHOULD include `Retry-After`.
**Rule `HTTP_ASYNC_POLL_DONE`**: MUST
When the operation has completed, `GET` on the operation URL MUST respond with the status code, header fields and body that the synchronous response would have had, for both success and failure ([Async `ASYNC_POLL_SUCCESS`](./crud/async.md#ASYNC_POLL_SUCCESS) and [`ASYNC_POLL_FAILURE`](./crud/async.md#ASYNC_POLL_FAILURE)).
> **Tip (non-normative): Example**
>
> ```http
> GET /@operations/0190a5f2-9a00-7c00-8000-00000000abcd
>
> HTTP/1.1 425 Too Early
> Retry-After: 5
> Content-Type: application/json
>
> { "status": "pending", "progress": { "done": 12000, "total": 50000 } }
> ```
> When the `deleteByQuery` completes, the same request returns `204 No Content` with `Modified-Count: 50000`, as the synchronous response would.
> **Note (non-normative): Rationale**
>
> `202 Accepted` is the response to the original request. Responding to polls of a pending operation with a different status (`425`) keeps every `2xx` poll response equal to the final result, so a Client never mistakes a progress object for the Result.
### 6.4 Progress stream
**Rule `HTTP_ASYNC_SSE`**: MAY
Servers MAY stream the state of an operation as [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html) when the Client requests the operation URL with `Accept: text/event-stream`: `progress` events carry the progress, and a final `done` event carries the completed state, after which the stream ends.
### 6.5 Callbacks
**Rule `HTTP_ASYNC_CALLBACK_HEADERS`**: MAY
The callback URLs ([Async `ASYNC_CALLBACK_URL`](./crud/async.md#ASYNC_CALLBACK_URL) and [`ASYNC_CALLBACK_ERROR_URL`](./crud/async.md#ASYNC_CALLBACK_ERROR_URL)) MAY be sent in the `Callback` and `Callback-Error` request header fields. The `Location` of the operation state MUST be sent even when callbacks are requested ([Async `ASYNC_CALLBACK_POLL_FALLBACK`](./crud/async.md#ASYNC_CALLBACK_POLL_FALLBACK)).
**Rule `HTTP_ASYNC_STANDARD_WEBHOOKS`**: MUST
Callbacks MUST be `POST` requests that conform to [Standard Webhooks](https://www.standardwebhooks.com/) 1.0: the `webhook-id` header field MUST be the Operation ID, and the `webhook-timestamp` and `webhook-signature` header fields MUST be sent and computed as that specification defines. Servers SHOULD prefer the asymmetric signature scheme (`v1a`, Ed25519) and MUST document how Clients obtain the verification keys.
**Rule `HTTP_ASYNC_CALLBACK_PAYLOAD`**: MUST
The callback body MUST be a JSON object with `type` (`crud.operation.succeeded` or `crud.operation.failed`), `timestamp` (ISO 8601, when the operation completed) and `data`, an object with the `operationId` and the completed state: the `status` code, the relevant `headers` and the `body` of the response that the operation URL returns.
**Rule `HTTP_ASYNC_CALLBACK_LARGE`**: MAY
When the body exceeds the size the Server accepts for callbacks, the Server MAY omit `data.body` and set `data.truncated` to `true`; the Client then retrieves the state from the operation URL.
**Rule `HTTP_ASYNC_CALLBACK_RETRIES`**: SHOULD
Servers SHOULD retry failed deliveries as recommended by Standard Webhooks: only `2xx` responses are successful, retries use exponential backoff with jitter, `410 Gone` stops deliveries to that URL, and `Retry-After` is honored.
> **Tip (non-normative): Example**
>
> ```http
> POST /hooks/crud HTTP/1.1
> Host: client.example.com
> Content-Type: application/json
> webhook-id: 0190a5f2-9a00-7c00-8000-00000000abcd
> webhook-timestamp: 1793816405
> webhook-signature: v1a,hnO3f9T8Ytu9HwrXslvumlUpqtNVqkhqw/enGzPCXe5BdqzCInXqYXFymVJaA7AZdpXwVLPo3mNl8EM+m7TBAg==
>
> { "type": "crud.operation.succeeded",
> "timestamp": "2026-11-04T18:20:00.000Z",
> "data": {
> "operationId": "0190a5f2-9a00-7c00-8000-00000000abcd",
> "status": 204,
> "headers": { "Modified-Count": "50000" },
> "body": null
> } }
> ```
## 7. Schemas
> **Caution (non-normative): Requires the Schema extension**
>
> This section applies only to Servers that support the [Schema extension](./crud/schema.md#1-schemas) (`schema ^0.1.0`).
### 7.1 Endpoints
The `@schema` Collection ([Schema `SCHEMA_COLLECTION`](./crud/schema.md#SCHEMA_COLLECTION)) uses the endpoints of [section 2](#2-endpoints), with `@schema` as the Collection and the Slug of the described Collection as the Resource ID.
| Operation | Method and path |
|---|---|
| `list` | `GET /@schema` |
| `get` | `GET /@schema/:collection` |
| `create` | `POST /@schema` |
| `clone` | `POST /@schema/:collection/clone` |
| `patchById` | `PATCH /@schema/:collection` |
| `patchByQuery` | `PATCH /@schema` |
| `replaceById` | `PUT /@schema/:collection` |
| `replaceByQuery` | `PUT /@schema` |
| `deleteById` | `DELETE /@schema/:collection` |
| `deleteByQuery` | `DELETE /@schema` |
**Rule `HTTP_SCHEMA_ENDPOINTS`**: MUST
Servers MUST expose the operations on schemas they support with the method and path in the table above.
**Rule `HTTP_SCHEMA_ALIAS`**: MUST
`GET`, `PUT`, `PATCH` and `DELETE` on `/:collection/@schema` MUST be equivalent to the same method on `/@schema/:collection`.
> **Tip (non-normative): Example**
>
> ```http
> GET /@schema?@fields=_id
> GET /customers/@schema
> PUT /@schema/customers
> PATCH /@schema?@q={}
> ```
### 7.2 Derivation
**Rule `HTTP_SCHEMA_DERIVE`**: MUST
The "Derive" Parameter ([Schema `SCHEMA_DERIVE`](./crud/schema.md#SCHEMA_DERIVE)) MUST be sent as the control parameter `@derive=true`.
> **Tip (non-normative): Example**
>
> ```http
> PUT /@schema/customers?@derive=true
> Content-Type: application/json
>
> { "_id": "customers", "validation": "strict" }
> ```
### 7.3 Linking Resources to their schema
**Rule `HTTP_SCHEMA_DESCRIBEDBY`**: SHOULD
Responses of `get` and `list` on a Collection with a registered schema SHOULD include a `Link` header field with the `describedby` relation to `/@schema/:collection`.
> **Tip (non-normative): Example: describedby link in a list response**
>
> ```http
> GET /customers
>
> HTTP/1.1 200 OK
> Link: @schema/customers>; rel="describedby"
> ```
**Rule `HTTP_SCHEMA_RAW`**: MUST
`GET /@schema/:collection` with `Accept: application/schema+json` MUST respond with only the value of the `schema` Field, compiled as specified by ESType ([ESType section 2](./estype.md#2-compilation)), labeled `application/schema+json`. When the Collection has no registered schema ([Schema `SCHEMA_NULL`](./crud/schema.md#SCHEMA_NULL)), the Server MUST fail with the [`NOT_FOUND`](./crud/base.md#NOT_FOUND) error, with target `schema` ([Schema `SCHEMA_NOT_FOUND_TARGET`](./crud/schema.md#SCHEMA_NOT_FOUND_TARGET)).
> **Tip (non-normative): Example: reading only the JSON Schema**
>
> ```http
> GET /@schema/customers
> Accept: application/schema+json
>
> HTTP/1.1 200 OK
> Content-Type: application/schema+json
>
> { "type": "object", "properties": { "_id": { "type": "string" }, "name": { "type": "string" } }, "required": ["_id", "name"] }
> ```
> **Note (non-normative)**
>
> [JSON Schema Core, section 9.5.1.1](https://json-schema.org/draft/2020-12/json-schema-core) recommends the `describedby` relation ([IANA Link Relations](https://www.iana.org/assignments/link-relations/link-relations.xhtml)) to link instances to their schema. The media type `application/schema+json` is proposed by JSON Schema but not yet registered by IANA.
### 7.4 Errors and Warnings
**Rule `HTTP_SCHEMA_STATUS`**: MUST
An [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) error caused by a Resource that does not conform to a `strict` schema ([Schema `SCHEMA_STRICT`](./crud/schema.md#SCHEMA_STRICT)) MUST be mapped to `422 Unprocessable Content`; other [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) errors keep `400 Bad Request`.
**Rule `HTTP_SCHEMA_PROBLEM_ERRORS`**: SHOULD
The Problem Details object of a [`SCHEMA_STRICT`](./crud/schema.md#SCHEMA_STRICT) error SHOULD carry the violations ([Schema `SCHEMA_VIOLATION_DETAILS`](./crud/schema.md#SCHEMA_VIOLATION_DETAILS)) in an `errors` member, as an array of output units.
**Rule `HTTP_SCHEMA_WARNING_PARAMS`**: SHOULD
Each [`SCHEMA_VIOLATION`](./crud/schema.md#SCHEMA_VIOLATION) Warning SHOULD be a separate item of the `Warning` header field, with the parameters `instance` (the `instanceLocation`) and `keyword` (the `keywordLocation`).
> **Tip (non-normative): Example**
>
> ```http
> HTTP/1.1 201 Created
> Warning: "SCHEMA_VIOLATION";message="must be integer";instance="/age";keyword="/properties/age/type"
> ```
## 8. References
### 8.1 Normative references
- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): requirement level key words (BCP 14)
- [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110): HTTP Semantics
- [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986): URI Generic Syntax
- [RFC 10008](https://www.rfc-editor.org/rfc/rfc10008): The HTTP QUERY Method
- [RFC 7240](https://www.rfc-editor.org/rfc/rfc7240): Prefer Header for HTTP
- [RFC 9651](https://www.rfc-editor.org/rfc/rfc9651): Structured Field Values for HTTP
- [RFC 8288](https://www.rfc-editor.org/rfc/rfc8288): Web Linking
- [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457): Problem Details for HTTP APIs
- [RFC 5789](https://www.rfc-editor.org/rfc/rfc5789): PATCH Method for HTTP
- [RFC 6902](https://www.rfc-editor.org/rfc/rfc6902) and [RFC 7396](https://www.rfc-editor.org/rfc/rfc7396): JSON Patch and JSON Merge Patch
- [W3C Trace Context](https://www.w3.org/TR/trace-context/): `traceparent`
- [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html) (WHATWG HTML)
- [Standard Webhooks](https://www.standardwebhooks.com/) 1.0
- [JSON Schema 2020-12](https://json-schema.org/draft/2020-12/json-schema-core): `describedby` and `application/schema+json` ([section 7](#7-schemas))
- [IANA Link Relations](https://www.iana.org/assignments/link-relations/link-relations.xhtml): `describedby`
- [ESType](https://github.com/lingodata/estype) `^0.1.0`: schema compilation (sections 2 and 7)
- [UnQuery](https://github.com/lingodata/unquery), [ECSON](https://github.com/lingodata/ecson) and the CRUD API Base Specification and extensions (LingoData)
### 8.2 Informative references
- [RFC 6648](https://www.rfc-editor.org/rfc/rfc6648): Deprecating the "X-" Prefix
- [RFC 9111](https://www.rfc-editor.org/rfc/rfc9111): HTTP Caching (obsoletes the original `Warning` header field)
- [RFC 8470](https://www.rfc-editor.org/rfc/rfc8470): Using Early Data in HTTP (defines `425 Too Early`)
---
# CRUD API MCP Protocol
Version: 0.2.0 · Status: draft · License: Apache-2.0 · MCP revision: 2026-07-28
Source: lingodata/crud@bc225ba
## 1. Overview
This Protocol specification maps the CRUD API Base Specification and its extensions to the [Model Context Protocol](https://modelcontextprotocol.io/specification/2026-07-28) (MCP), so that AI agents and other MCP clients can operate on Resources of any Data source. It is part of the **LingoData** family.
| Concept | MCP |
|---|---|
| Operations | MCP tools named `crud.` ([section 2](#2-tools)) |
| Search Queries and Parameters | tool arguments |
| Metadata | the `_meta` object of requests and results |
| Errors | tool execution errors (`isError`) with Problem Details |
| Asynchronous operations | the MCP Tasks extension ([section 5](#5-asynchronous-operations)) |
| Schemas | the `@schema` Collection, `crud.schema.*` tools and MCP resources ([section 6](#6-schemas)) |
### 1.1 Conventions
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)) when, and only when, they appear in all capitals, as shown here.
### 1.2 MCP version
**Rule `MCP_VERSION`**: MUST
This specification targets MCP `2026-07-28`. Servers MAY also support earlier MCP revisions that negotiate extensions during the `initialize` handshake (`2025-11-25`).
### 1.3 MCP extension
**Rule `MCP_EXTENSION_ID`**: MUST
This specification is an MCP extension with the identifier `dev.lingodata/crud`. Servers MUST advertise it in the `extensions` field of their capabilities (`server/discover`), with the specifications they implement as settings ([Base `META_CRUD_SPECS`](./crud/base.md#META_CRUD_SPECS)).
> **Tip (non-normative): Example**
>
> ```json
> { "capabilities": {
> "tools": {},
> "extensions": {
> "dev.lingodata/crud": { "specs": { "base": "0.2.0", "relationships": "0.1.0" } }
> } } }
> ```
> **Note (non-normative)**
>
> The identifier is provisional, as is the LingoData name. MCP requires extension identifiers to start with a reversed domain name owned by the publisher.
**Rule `MCP_SPEC_RANGES`**: MUST
This specification supports the Base Specification `^0.2.0` and the extensions Asynchronous operations `^0.1.0`, Metadata `^0.1.0`, Relationships `^0.1.0` and Views `^0.1.0`. Rules that map an extension apply only to Servers that support it.
## 2. Tools
Each CRUD operation is an MCP tool. The tools are generic: the target Collection is an argument.
**Rule `MCP_TOOLS`**: MUST
Servers MUST expose each operation they support as the tool in the table below, with the listed arguments. In `crud.patch`, `crud.replace` and `crud.delete`, the Client MUST send either `id` (for the `ById` operation) or `query` (for the `ByQuery` operation), and the Server MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) code when both or neither are sent.
| Tool | Operation | Arguments |
|---|---|---|
| `crud.get` | `get` | `collection`, `id`, `fields?`, `expand?` |
| `crud.list` | `list` | `collection`, `query?`, `fields?`, `sort?`, `page?`, `limit?`, `offset?`, `cursor?`, `expand?` |
| `crud.listByView` | `listByView` (Views) | `collection`, `view`, `viewParams?`, and the optional arguments of `crud.list` |
| `crud.create` | `create` | `collection`, `resources` (a Resource or an array of Resources), `fields?` |
| `crud.clone` | `clone` | `collection`, `id`, `patch?`, `patchFormat?`, `newId?` |
| `crud.patch` | `patchById`, `patchByQuery` | `collection`, `id` or `query`, `patch`, `patchFormat?`, `expectMatch?`, `ifMatch?`, `fields?` |
| `crud.replace` | `replaceById`, `replaceByQuery` | `collection`, `id` or `query`, `resource`, `expectMatch?`, `denyUpsert?`, `ifMatch?`, `fields?` |
| `crud.delete` | `deleteById`, `deleteByQuery` | `collection`, `id` or `query`, `expectMatch?`, `ifMatch?` |
**Rule `MCP_TOOL_ANNOTATIONS`**: SHOULD
Tools SHOULD declare annotations: `readOnlyHint: true` for `crud.get`, `crud.list` and `crud.listByView`; `destructiveHint: true` for `crud.replace` and `crud.delete`; and `idempotentHint: true` for `crud.replace` and `crud.delete`.
**Rule `MCP_COLLECTION_TOOLS`**: MAY
Servers MAY also expose tools specific to a Collection (for example `orders.list`), with the same arguments except `collection`.
### 2.1 Arguments
**Rule `MCP_ARGS_FORMATS`**: MUST
`query` MUST be an UnQuery filter: a JSON object in the JSON syntax, or a string in the SQL syntax. `fields`, `sort` and `expand` MUST be field lists ([Base section 3.3.1](./crud/base.md#331-field-lists)), as strings or as arrays of field paths. `patchFormat` MUST be `json-patch` (default) or `merge-patch`.
**Rule `MCP_ARGS_ECSON`**: MUST
Resources, patches, View parameters and query operands in arguments MUST be read as ECSON serializations.
> **Note (non-normative)**
>
> MCP has no content negotiation of the Resource Representation: arguments are read as ECSON, and results are sent in ECSON ([Base `META_RES_FALLBACK`](./crud/base.md#META_RES_FALLBACK)). ECSON is valid JSON, so MCP clients that do not know ECSON can read results, and they see typed values as small objects, such as `{ "$date": "2026-11-06T12:00:00.000Z" }`.
**Rule `MCP_ARGS_PRECONDITIONS`**: MUST
`expectMatch` ([Base `PARAM_EXPECT_MATCH`](./crud/base.md#PARAM_EXPECT_MATCH)), `denyUpsert` ([Base `PARAM_DENY_UPSERT`](./crud/base.md#PARAM_DENY_UPSERT)) and `ifMatch` (the expected `_meta.hash`, [Metadata `META_DOC_CONDITIONAL`](./crud/metadata.md#META_DOC_CONDITIONAL)) MUST fail without writing, with the [`EXPECT_MISMATCH`](./crud/base.md#EXPECT_MISMATCH), [`UPSERT_DENIED`](./crud/base.md#UPSERT_DENIED) and [`PRECONDITION_FAILED`](./crud/metadata.md#PRECONDITION_FAILED) codes respectively.
### 2.2 Results
**Rule `MCP_RESULT_STRUCTURED`**: MUST
The Result MUST be returned in `structuredContent` without envelopes: the Resource for `crud.get`, an array of Resources (or of rows, for aggregated Views) for `crud.list` and `crud.listByView`, the written Resources for writes with the `representation` preference, and `null` otherwise. `content` SHOULD include a text item with the same value serialized as ECSON.
> **Tip (non-normative): Example**
>
> ```json
> { "jsonrpc": "2.0", "id": 7,
> "method": "tools/call",
> "params": { "name": "crud.list",
> "arguments": { "collection": "orders",
> "query": { "status": "paid", "total": { "@gte": 100 } },
> "sort": "-createdAt", "limit": 2 } } }
>
> { "jsonrpc": "2.0", "id": 7,
> "result": { "resultType": "complete", "isError": false,
> "structuredContent": [
> { "_id": "0190a5f2-7c3e-7b1a-9f4e-2d8c6b1e4a90", "status": "paid", "total": 250 },
> { "_id": "0190a5f2-7c3e-7b1a-9f4e-2d8c6b1e4a91", "status": "paid", "total": 120 } ],
> "content": [{ "type": "text", "text": "[{\"_id\":\"0190a5f2-...\", ...}]" }],
> "_meta": { "dev.lingodata/crud.matchedCount": 37, "dev.lingodata/crud.nextCursor": "eyJwIjoyfQ" } } }
> ```
> **Note (non-normative): Rationale**
>
> MCP clients, such as AI applications, invoke tools, and many SDKs reject unknown methods, so tools make the CRUD API usable by any MCP client. MCP `2026-07-28` allows any JSON value in `structuredContent`, so results need no envelope.
> **Note (non-normative)**
>
> Discovering which Collections a Server exposes is defined by the Schema extension (`crud.list` on `@schema`, [section 6](#6-schemas)).
### 2.3 Views
> **Caution (non-normative): Requires the Views extension**
>
> The rules below apply only to Servers that support the [Views extension](./crud/views.md#1-views) (`views ^0.1.0`).
**Rule `MCP_VIEWS_COLLECTION`**: MUST
The tools of [section 2](#2-tools) MUST accept `/@views` as the `collection` argument, for the `@views` Collection of `` ([Views `VIEW_COLLECTION`](./crud/views.md#VIEW_COLLECTION)), with the View name as `id`.
**Rule `MCP_VIEWS_TOOLS`**: MAY
Servers MAY also expose the tools `crud.views.get`, `crud.views.list`, `crud.views.create`, `crud.views.clone`, `crud.views.patch`, `crud.views.replace` and `crud.views.delete`, equivalent to the tools of [section 2](#2-tools) with `collection: "/@views"`, whose `collection` argument is the Collection of the Views.
**Rule `MCP_VIEW_TOOLS`**: MAY
Servers MAY expose a tool for each View (for example `orders.sales-by-month`), equivalent to `crud.listByView` for that View, whose `inputSchema` has the View parameters as described by `params`, besides the optional arguments of `crud.list`. Such tools MUST NOT declare an `outputSchema`.
> **Note (non-normative): Rationale**
>
> The `schema` of a View is a hint that the Server does not validate ([Views `VIEW_SCHEMA`](./crud/views.md#VIEW_SCHEMA)), and MCP requires tool results to conform to the `outputSchema` when one is declared. A tool per View lets AI applications see each saved report as a tool with typed parameters.
> **Tip (non-normative): Example**
>
> ```json
> { "name": "crud.list", "arguments": { "collection": "orders/@views", "fields": "_id,description" } }
> ```
## 3. Metadata
Operation Metadata ([Base section 3.4](./crud/base.md#34-metadata)) is carried in the `_meta` object of the `tools/call` request and of its result, under keys with the `dev.lingodata/crud.` prefix, as required by MCP `_meta` key naming.
**Rule `MCP_META_KEYS`**: MUST
Metadata MUST use the keys in the table below, in the request `_meta` (Client to Server) or in the result `_meta` (Server to Client).
| Key | Direction | Value | Implements |
|---|---|---|---|
| `dev.lingodata/crud.specs` | result | object of specification names to versions | [Base `META_CRUD_SPECS`](./crud/base.md#META_CRUD_SPECS) |
| `dev.lingodata/crud.require` | request | object of specification names to node-semver ranges | [Base `META_CRUD_REQUIRE`](./crud/base.md#META_CRUD_REQUIRE) |
| `dev.lingodata/crud.prefer` | request | `representation` (default) or `minimal` | [Base `META_PREFER_REPRESENTATION`](./crud/base.md#META_PREFER_REPRESENTATION) |
| `dev.lingodata/crud.handling` | request | `lenient` (default) or `strict` | [Base `META_WARN_PREFERENCE`](./crud/base.md#META_WARN_PREFERENCE) |
| `dev.lingodata/crud.allowedWarnings` | request | array of Warning codes that remain Warnings, with `handling` set to `strict` | [Base `META_WARN_PREFERENCE_EXCEPT`](./crud/base.md#META_WARN_PREFERENCE_EXCEPT) |
| `dev.lingodata/crud.async` | request | `prefer` or `require` | Async ([section 5](#5-asynchronous-operations)) |
| `dev.lingodata/crud.matchedCount` | result | integer | [Base `META_MATCHED_COUNT`](./crud/base.md#META_MATCHED_COUNT) |
| `dev.lingodata/crud.modifiedCount` | result | integer | [Base `META_MODIFIED_COUNT`](./crud/base.md#META_MODIFIED_COUNT) |
| `dev.lingodata/crud.warnings` | result | array of Warning objects: `code`, `message` and the other members of [Base `WARN_DATA`](./crud/base.md#WARN_DATA) | [Base `META_WARN`](./crud/base.md#META_WARN) |
| `dev.lingodata/crud.nextCursor` | result | the cursor of the next page | [Base `PAGINATION_CURSOR`](./crud/base.md#PAGINATION_CURSOR) |
| `dev.lingodata/crud.schema` | result | `{ "collection", "version" }` of the schema | Schema ([section 6](#6-schemas)) |
**Rule `MCP_META_TRACEPARENT`**: SHOULD
The Correlation ID ([Base `META_CORRELATION_ID`](./crud/base.md#META_CORRELATION_ID)) SHOULD be carried in the `traceparent` key of `_meta`, as defined by MCP for W3C Trace Context, with the Correlation ID as the `trace-id` (its 16 bytes in hexadecimal, without hyphens).
## 4. Errors
MCP distinguishes protocol errors, returned as JSON-RPC errors, from tool execution errors, returned in tool results with `isError: true` so that models can correct themselves and retry.
**Rule `MCP_ERROR_TOOL_RESULT`**: MUST
Failed CRUD operations MUST be reported as tool execution errors: a tool result with `isError: true`, whose `structuredContent` is the error data as a Problem Details object ([Base `ERROR_PROBLEM_DETAILS`](./crud/base.md#ERROR_PROBLEM_DETAILS), without the `status` member) and whose `content` has a text item with the same object serialized.
**Rule `MCP_ERROR_PROTOCOL`**: MUST
JSON-RPC errors MUST be used only for errors defined by MCP itself, such as an unknown tool or a malformed request. This specification defines no JSON-RPC error codes.
> **Tip (non-normative): Example**
>
> ```json
> { "jsonrpc": "2.0", "id": 4,
> "result": {
> "resultType": "complete",
> "isError": true,
> "structuredContent": { "type": "about:blank", "title": "Not Found",
> "detail": "Order 0190a5f2-7c3e-7b1a-9f4e-2d8c6b1e4a90 not found",
> "code": "NOT_FOUND", "target": "resource" },
> "content": [{ "type": "text", "text": "{\"code\":\"NOT_FOUND\", ...}" }]
> } }
> ```
> **Note (non-normative): Rationale**
>
> MCP `2026-07-28` forbids new codes in `-32000` to `-32019` and reserves `-32020` to `-32099` for the MCP specification. Tool execution errors need no codes of their own, and the Base error codes travel in the Problem Details object.
## 5. Asynchronous operations
> **Caution (non-normative): Requires the Asynchronous operations extension**
>
> This section maps the **[Asynchronous operations extension](./crud/async.md#1-asynchronous-operations)** (`async ^0.1.0`) to MCP, using the MCP Tasks extension ([`io.modelcontextprotocol/tasks`](https://github.com/modelcontextprotocol/ext-tasks), revision `2026-07-28`). It applies only to Servers that support both.
In MCP, an asynchronous CRUD operation is an MCP task: the CRUD term "operation" corresponds to the MCP term "task".
| Asynchronous operations extension | MCP Tasks |
|---|---|
| Operation ID | `taskId` |
| pending | `working` |
| succeeded | `completed`, with a result whose `isError` is `false` |
| failed (a CRUD error) | `completed`, with a result whose `isError` is `true` ([section 4](#4-errors)) |
| retention ([`ASYNC_RETENTION`](./crud/async.md#ASYNC_RETENTION)) | `ttlMs` |
| suggested polling interval | `pollIntervalMs` |
### 5.1 Negotiation
**Rule `MCP_ASYNC_TASKS`**: MUST
A Client that prefers or requires asynchronous processing ([Async `ASYNC_CLIENT_PREFER`](./crud/async.md#ASYNC_CLIENT_PREFER) and [`ASYNC_CLIENT_REQUIRE`](./crud/async.md#ASYNC_CLIENT_REQUIRE)) MUST declare the MCP Tasks extension in its request capabilities, and MUST declare which one it means in the `dev.lingodata/crud.async` key of the request `_meta`, with the value `prefer` or `require`.
**Rule `MCP_ASYNC_NEGOTIATION`**: MUST
When the Client requires asynchronous processing and the Server cannot provide it, the Server MUST fail with a tool execution error with the [`NEGOTIATION`](./crud/base.md#NEGOTIATION) code. When the Server can only run the operation asynchronously and the Client did not declare the MCP Tasks extension, the Server MUST return the MCP `MissingRequiredClientCapability` error (`-32021`), as defined by MCP Tasks.
### 5.2 Tasks
**Rule `MCP_ASYNC_CREATE_TASK`**: MUST
When the Server runs an operation asynchronously, it MUST respond to `tools/call` with a `CreateTaskResult` (`resultType: "task"`), whose `taskId` is the Operation ID, a UUIDv7 in `uuid-hex` format ([Async `ASYNC_OPERATION_ID`](./crud/async.md#ASYNC_OPERATION_ID)).
**Rule `MCP_ASYNC_RESULT`**: MUST
When the operation has completed, `tasks/get` MUST return the task with `status: "completed"` and, in `result`, the tool result that the synchronous call would have returned, including its `_meta` and, for CRUD errors, `isError: true` ([Async `ASYNC_POLL_SUCCESS`](./crud/async.md#ASYNC_POLL_SUCCESS) and [`ASYNC_POLL_FAILURE`](./crud/async.md#ASYNC_POLL_FAILURE)).
**Rule `MCP_ASYNC_PROGRESS`**: MAY
Servers MAY report progress ([Async `ASYNC_PROGRESS`](./crud/async.md#ASYNC_PROGRESS)) with MCP progress notifications, when the request carries a `progressToken`, and in the `statusMessage` of the task.
> **Note (non-normative)**
>
> Callbacks ([Async `ASYNC_CALLBACK_URL`](./crud/async.md#ASYNC_CALLBACK_URL)) are not mapped to MCP: MCP clients follow tasks by polling `tasks/get` or through MCP notifications.
## 6. Schemas
> **Caution (non-normative): Requires the Schema extension**
>
> This section applies only to Servers that support the [Schema extension](./crud/schema.md#1-schemas) (`schema ^0.1.0`).
### 6.1 Tools
**Rule `MCP_SCHEMA_COLLECTION`**: MUST
The tools of [section 2](#2-tools) MUST accept `@schema` as the `collection` argument, with the Slug of the described Collection as `id` ([Schema `SCHEMA_COLLECTION`](./crud/schema.md#SCHEMA_COLLECTION)).
**Rule `MCP_SCHEMA_TOOLS`**: MAY
Servers MAY also expose the tools `crud.schema.get`, `crud.schema.list`, `crud.schema.create`, `crud.schema.clone`, `crud.schema.patch`, `crud.schema.replace` and `crud.schema.delete`, equivalent to the tools of [section 2](#2-tools) with `collection: "@schema"`, with the same arguments except `collection`.
> **Note (non-normative): Rationale**
>
> MCP tool names should use only letters, digits, `_`, `-` and `.` ([MCP, Tool Names](https://modelcontextprotocol.io/specification/2026-07-28/server/tools.md)), so the Collection tools of [`MCP_COLLECTION_TOOLS`](#MCP_COLLECTION_TOOLS) cannot be named `@schema.list`. The `crud.schema.*` tools give MCP clients a declared option for schemas.
**Rule `MCP_SCHEMA_CLONE`**: MUST
`crud.clone` with `collection: "@schema"`, and `crud.schema.clone`, MUST receive `newId` ([Schema `SCHEMA_CLONE_ID`](./crud/schema.md#SCHEMA_CLONE_ID)).
**Rule `MCP_SCHEMA_DERIVE`**: MUST
The "Derive" Parameter ([Schema `SCHEMA_DERIVE`](./crud/schema.md#SCHEMA_DERIVE)) MUST be sent as the boolean argument `derive` of `crud.create` and `crud.replace` (and of `crud.schema.create` and `crud.schema.replace`). The Server MUST fail with the [`INVALID_INPUT`](./crud/base.md#INVALID_INPUT) code when `derive` is sent with a Collection other than `@schema`.
> **Tip (non-normative): Example**
>
> ```json
> {
> "name": "crud.get",
> "arguments": { "collection": "@schema", "id": "customers" }
> }
> ```
### 6.2 Linking Resources to their schema
**Rule `MCP_SCHEMA_META`**: SHOULD
Results of `crud.get` and `crud.list` on a Collection with a registered schema SHOULD include, in `_meta`, the key `dev.lingodata/crud.schema` with an object holding the `collection` and the `version` of its schema.
**Rule `MCP_SCHEMA_RESOURCES`**: MAY
Servers MAY expose the schema Resource of every Collection, including Collections without a registered schema ([Schema `SCHEMA_NULL`](./crud/schema.md#SCHEMA_NULL)), as an MCP resource with the URI template `lingodata-crud://schema/{collection}` and the MIME type `application/json`, whose content is the schema Resource (`_id`, `validation`, `schema` and `_meta`).
> **Note (non-normative)**
>
> MCP lists database schemas among the examples of resources ([MCP, Resources](https://modelcontextprotocol.io/specification/2026-07-28/server/resources.md)), which lets AI applications read schemas as context without calling a tool. Listing these resources also discovers the Collections of the Server; a Collection with `schema: null` has free-form Fields.
> **Caution (non-normative): Provisional**
>
> The `lingodata-crud` URI scheme is provisional until the publication domain of the LingoData family is defined.
### 6.3 Collection tools
**Rule `MCP_SCHEMA_INPUT`**: SHOULD
Collection tools ([`MCP_COLLECTION_TOOLS`](#MCP_COLLECTION_TOOLS)) on a Collection with a registered schema SHOULD use that schema, compiled as specified by ESType ([ESType section 2](./estype.md#2-compilation)), in their `inputSchema` for the `resources` and `resource` arguments.
**Rule `MCP_SCHEMA_OUTPUT`**: MAY
Collection tools on a Collection with a `strict` schema MAY declare an `outputSchema` built from it, compiled as specified by ESType ([ESType section 2](./estype.md#2-compilation)). They MUST NOT declare one for a `lenient` schema.
> **Note (non-normative): Rationale**
>
> MCP requires tool results to conform to the `outputSchema` when one is declared. With a `lenient` schema, stored Resources may not conform, so the result could break that requirement. MCP clients treat the keywords of the Schema vocabulary (`refCollection`, `dbType`) and `estype` as annotations ([JSON Schema Core, section 6.5](https://json-schema.org/draft/2020-12/json-schema-core#section-6.5)). The compiled schema accepts both the plain JSON form and the ECSON form of each value.
### 6.4 Errors and Warnings
**Rule `MCP_SCHEMA_ERRORS`**: SHOULD
The Problem Details object of a [`SCHEMA_STRICT`](./crud/schema.md#SCHEMA_STRICT) error SHOULD carry the violations ([Schema `SCHEMA_VIOLATION_DETAILS`](./crud/schema.md#SCHEMA_VIOLATION_DETAILS)) in an `errors` member, and each [`SCHEMA_VIOLATION`](./crud/schema.md#SCHEMA_VIOLATION) Warning in `dev.lingodata/crud.warnings` SHOULD have the members `instance` (the `instanceLocation`) and `keyword` (the `keywordLocation`).
## 7. References
- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): requirement level key words (BCP 14)
- [Model Context Protocol, revision 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28)
- [MCP extensions](https://modelcontextprotocol.io/extensions/overview)
- [MCP Tasks extension](https://github.com/modelcontextprotocol/ext-tasks), revision 2026-07-28
- [JSON-RPC 2.0](https://www.jsonrpc.org/specification)
- [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457): Problem Details for HTTP APIs
- [W3C Trace Context](https://www.w3.org/TR/trace-context/)
- [JSON Schema 2020-12](https://json-schema.org/draft/2020-12/json-schema-core): `inputSchema`, `outputSchema` and the Schema extension ([section 6](#6-schemas))
- [ESType](https://github.com/lingodata/estype) `^0.1.0`: schema compilation ([section 6](#6-schemas))
- [UnQuery](https://github.com/lingodata/unquery), [ECSON](https://github.com/lingodata/ecson) and the CRUD API Base Specification and extensions (LingoData)