# 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

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

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

Views of the same Collection MUST be uniquely identified by [Slugs](./base.md#26-general-terminology).

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

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

The Server MUST support `get` and `list` on `@views`.

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

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

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

`query` MUST be a Search Query in a format that `list` accepts ([Base `SEARCH_QUERY_UNQUERY`](./base.md#SEARCH_QUERY_UNQUERY) and [`SEARCH_QUERY_FORMATS`](./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.

<a id="VIEW_QUERY_FORMAT"></a>**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`](./base.md#NEGOTIATION) error when it does not support the format.

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

`sort` and `fields` MUST be field lists ([Base section 3.3.1](./base.md#331-field-lists)), applied as the Sorting and Projection Parameters of `list`.

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

`params` MUST be a JSON Schema of type `object`, in the format of the Schema extension ([Schema `SCHEMA_DIALECT`](./schema.md#SCHEMA_DIALECT) and [section 1.4](#14-execution-operation-listbyview)), with one property per parameter. Parameter names MUST be [Slugs](./base.md#26-general-terminology). `required` lists the required parameters, and `default` gives the value of an omitted parameter.

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

<a id="VIEW_DEFINITION_VALIDATE"></a>**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`](./schema.md#SCHEMA_META_SCHEMA)), and MUST fail with the [`INVALID_INPUT`](./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.

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

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

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

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

The Subject MUST include a View name as specified in [section 1.1](#11-the-views-collections).

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

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

If the View does not exist, the Server MUST fail the operation with the [`NOT_FOUND`](./base.md#NOT_FOUND) error, with the `view` target.

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

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

Parameter values MUST be converted as specified by [Schema `SCHEMA_VALUE_CONVERSION`](./schema.md#SCHEMA_VALUE_CONVERSION) and [`SCHEMA_VALUE_NO_ESTYPE`](./schema.md#SCHEMA_VALUE_NO_ESTYPE), using the `params` schema.

The Result follows the Base rules for `list` ([`RES_RESOURCES_FOUND`](./base.md#RES_RESOURCES_FOUND), [`RES_NO_RESULTS`](./base.md#RES_NO_RESULTS)), and accepts the pagination, projection, sorting and custom Parameters of `list`, combined with the View as follows.

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

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

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

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

<a id="VIEW_AGGREGATED"></a>**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`](./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`](./base.md#NOT_FOUND) error code of the Base Specification, and reports invalid View definitions and parameters with its [`INVALID_INPUT`](./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](./base.md#1-overview) `^0.2.0`, [Schema extension](./schema.md#1-schemas) `^0.1.0` and [Resource Metadata extension](./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
