# 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](./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

<a id="SCHEMA_COLLECTION"></a>**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`](./base.md#COLLECTION_SLUG)), so `@schema` cannot be the name of another Collection.

<a id="SCHEMA_LIST_ALL"></a>**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)).

<a id="SCHEMA_LIST_CACHE"></a>**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`](./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 }
> }
> ```

<a id="SCHEMA_RESOURCE_FIELDS"></a>**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.

<a id="SCHEMA_VALIDATION_DEFAULT"></a>**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)).

<a id="SCHEMA_NULL"></a>**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.

<a id="SCHEMA_VERSION"></a>**Rule `SCHEMA_VERSION`**: MUST

The version of a schema is the `_meta.version` of its Resource ([Metadata `META_DOC_VERSION`](./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

<a id="SCHEMA_CREATE_ID"></a>**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`](./base.md#INVALID_INPUT) error when it is missing.

<a id="SCHEMA_CREATE_NULL"></a>**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`](./base.md#CONFLICT) error only when the Collection already has a registered schema.

<a id="SCHEMA_CLONE_ID"></a>**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`](./base.md#INVALID_INPUT) error when it is missing.

<a id="SCHEMA_COLLECTION_MISSING"></a>**Rule `SCHEMA_COLLECTION_MISSING`**: MUST

Writing a schema for a Collection that does not exist MUST fail with the [`NOT_FOUND`](./base.md#NOT_FOUND) error, with target `collection`, unless the Server creates the Collection as allowed by [`SCHEMA_COLLECTION_CREATE`](#SCHEMA_COLLECTION_CREATE).

<a id="SCHEMA_COLLECTION_CREATE"></a>**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.

<a id="SCHEMA_DELETE"></a>**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.

<a id="SCHEMA_META_SCHEMA"></a>**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`](./base.md#INVALID_INPUT) error when it is invalid.

<a id="SCHEMA_DIALECT"></a>**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`](./base.md#NEGOTIATION) error for a dialect they do not support.

<a id="SCHEMA_ID_FIELD"></a>**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](./base.md#313-resource-ids)). The Server MUST fail with the [`INVALID_INPUT`](./base.md#INVALID_INPUT) error when a written `schema` does not describe `_id`.

<a id="SCHEMA_NO_META_FIELD"></a>**Rule `SCHEMA_NO_META_FIELD`**: MUST NOT

A `schema` MUST NOT describe the `_meta` Field. The Server MUST fail with the [`INVALID_INPUT`](./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.

<a id="SCHEMA_DERIVE"></a>**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.

<a id="SCHEMA_DERIVE_EXPLICIT"></a>**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).

<a id="SCHEMA_DERIVE_NO_SCHEMA"></a>**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`](./base.md#INVALID_INPUT) error when it includes `schema`.

<a id="SCHEMA_DERIVE_UNSUPPORTED"></a>**Rule `SCHEMA_DERIVE_UNSUPPORTED`**: MUST

A Server that cannot derive the schema of the Collection MUST fail with the [`UNSUPPORTED`](./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 |

<a id="SCHEMA_VOCABULARY"></a>**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.

<a id="SCHEMA_ESTYPE"></a>**Rule `SCHEMA_ESTYPE`**: MAY

A Field MAY have `estype`.

<a id="SCHEMA_ESTYPE_VALIDATE"></a>**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)).

<a id="SCHEMA_ESTYPE_TYPE"></a>**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.

<a id="SCHEMA_VALUE_CONVERSION"></a>**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)).

<a id="SCHEMA_VALUE_NO_ESTYPE"></a>**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`](./base.md#REPR_NO_CONVERSION), [`REPR_NATIVE_STORAGE`](./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.

<a id="SCHEMA_REF_COLLECTION"></a>**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.

<a id="SCHEMA_DB_TYPE_INFER"></a>**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.

<a id="SCHEMA_DB_TYPE_CLIENT"></a>**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.

<a id="SCHEMA_SOURCE_APPLY"></a>**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.

<a id="SCHEMA_SOURCE_INCOMPATIBLE"></a>**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.

<a id="SCHEMA_SOURCE_DELETE"></a>**Rule `SCHEMA_SOURCE_DELETE`**: MUST

When the Data source has its own schema, deleting the schema of a Collection MUST fail with the [`UNSUPPORTED`](./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.

<a id="SCHEMA_FORCED_STRICT"></a>**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.

<a id="SCHEMA_VALIDATE_WRITES"></a>**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.

<a id="SCHEMA_NO_READ_VALIDATION"></a>**Rule `SCHEMA_NO_READ_VALIDATION`**: MUST NOT

The Server MUST NOT validate Resources on read operations.

<a id="SCHEMA_STRICT"></a>**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`](./base.md#INVALID_INPUT) error. Writes on several Resources follow [Base section 4.7](./base.md#47-writes-on-several-resources).

<a id="SCHEMA_LENIENT"></a>**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`](./base.md#META_WARN_PREFERENCE)), the [`SCHEMA_VIOLATION`](#SCHEMA_VIOLATION) Warnings make the operation fail with the [`STRICT_WARNINGS`](./base.md#STRICT_WARNINGS) error. This is how a Client requires strict validation on a `lenient` schema.

<a id="SCHEMA_VIOLATION_DETAILS"></a>**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`](./http.md#HTTP_SCHEMA_RAW)), so Clients can follow `keywordLocation` in it.

<a id="SCHEMA_NO_REVALIDATION"></a>**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

<a id="SCHEMA_NOT_FOUND_TARGET"></a>**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`](./base.md#NOT_FOUND) error, with target `schema` ([Base `RES_ERROR_DATA`](./base.md#RES_ERROR_DATA)).

This extension adds the following error code to those of the Base Specification ([Base `ERROR_EXTENSION_CODES`](./base.md#ERROR_EXTENSION_CODES)):

| Code | Condition |
|---|---|
| <a id="SCHEMA_INCOMPATIBLE"></a>`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`](./base.md#WARN_EXTENSION_CODES)):

| Code | Condition |
|---|---|
| <a id="SCHEMA_VIOLATION"></a>`SCHEMA_VIOLATION` | A Resource written to a `lenient` schema does not conform to it ([`SCHEMA_LENIENT`](#SCHEMA_LENIENT)) |
| <a id="VALIDATION_FORCED"></a>`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](./base.md#1-overview) `^0.2.0` and [Resource Metadata Extension](./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
