# Models

Source: https://developers.swell.is/backend-api/data-models

Define data collections and their API behavior. There are many standard models configured by default, such as products, orders, and others. Data models can be created manually in the Swell dashboard under **Developer > Models**, or may be installed automatically by Swell Apps, thereby expanding your database and available API endpoints.

> **Tip:** See the [Data model customization](https://developers.swell.is/guides/model-customization) guide for details on what you can do with custom models, or see [Apps model reference](https://developers.swell.is/apps/models) to learn how to configure data models in Swell Apps.

## The data model

### Fields

- `id` (string, auto): Unique identifier for the model. Default: `formula(client_id.environment_id.api.name)`.
- `name` (string, required): Slug-formatted name of the model.
- `fields` (object, required): Model fields and their properties applied for each record of a collection.

  Fields are named by the key of each property in this object, for example:

  `"fields": { "name": { "type": "string" }, ... }`

  While Swell's API supports working with record values that are not defined by a field, it is strongly recommended to define fields for known values.
  - `*` (object, required): The key of each `field` property is the desired name of the field.
    - `type` (string, required): Type of the field. Defaults to `string`.

      **Scalar types:**

      - `string`
      - `int`
      - `float`
      - `bool`
      - `date`
      - `currency`
      - `objectid`

      **Complex types:**

      - `array`
      - `object`
      - `collection`
      - `link`
      - `file`
    - `value_type` (enum): Defines the value-type of an `array` or `link` field.

      - array: Allows any value-type **except** `collection` or `record`.
      - link: Allows `collection` or `record`. Possible values: `array`, `bool`, `collection`, `currency`, `date`, `file`, `float`, `int`, `link`, `record`, `string`, `object`, `objectid`. Default: `string`.
    - `fields` (object): Nested fields of an `array` or `object` type field. The fields of an array or object are of the same schema as the top-level `fields` property.
    - `required` (boolean): Indicates the field must be defined with a non-`null` value when the record is created or updated.
    - `default` (mixed): Default value of the field, applied when a record is first created or updated while the field is otherwise `undefined`.
    - `enum` (array of value): Array of possible values that can be set on this field. System returns an error if a value is passed that does not match one of the defined `enum` options.
    - `format` (string): Automatically format the value of a string field. This may be an alternative to a more complex formula for simple use cases.

      **One of:**

      - `uppercase`: value => VALUE
      - `lowercase`: VALUE => value
      - `underscore`: TextValue => text_value
      - `slug`: TextValue => text-value
      - `slugid`: TextValue.Example => text-value.example
      - `currency-code`: usd => USD
      - `url`: example.com => https://example.com
      - `email`: user name@example.com => user+name@example.com
      - `semver`: 1 => 1.0.0
      - `password`: example => bcrypt(example)
         - Password-formatted fields are automatically hashed with the bcrypt algorithm.
    - `formula` (string): An expression used to calculate the value of the field when a record is created or updated. See Formula documentation for more details.

      The expression may reference its own value. For example, to force-uppercase a field named `code`:

      `"formula": "upper(code)"`

      If the expression results in an `undefined` value, the field itself will become undefined.
    - `unique` (mixed): If set to `true`, indicates the value must be unique across the entire collection. If set as an array of adjacent fields, indicates the combination of values must be unique across the entire collection.

      For example, the following would specify a field must be unique when combined with `account_id:`

      `"unique": ["account_id"]`
    - `readonly` (boolean): Indicates the field cannot be changed by an API call after initially being defined. Note: a `formula` field may still change the value dynamically.
    - `object_types` (object): Define type-specific fields for records that are applied according to an adjacent `type` field that is itself automatically defined. This is used when certain fields may be required or have different properties only when the record type matches one of these definitions. Object type fields are merged over regular fields, allowing the model to change the behavior of any existing field as well.

      For example:

      `"object_types": { "individual": { "full_name": { "required": true } } }`

      When defining **object_types**, a `type` field is automatically defined on the object, however you may also define it via configuration in order to enumerate each acceptable type.
      - `*` (object, required): The key of each `object_type` property is the desired name of the object type.
        - `fields` (object): Set of fields to be applied to the object given its `type`.
          - `*` (object): Define the fields to be applied to a record given its `type`. The fields of an object type are of the same schema as the top-level `fields` property.
    - `key` (string): For `link` only, specifies the foreign key to reference the primary key of a linked collection.
    - `extends` (string): For `array` and `object` only, this extends the object by applying nested fields from an adjacent field. The value should refer to another field from the top-level schema.
    - `model` (string): For `link` only, specifies the model of a linked collection.
    - `label` (string): The label of the field.
    - `description` (string): A brief description of the field.
    - `auto` (mixed): Causes the field value to be automatically resolved depending on the field type.

      **Examples:**

      - `auto: true` combined with `enum` values will automatically apply the first value.
      - `auto: true` on an `objectid` field will automatically create a new value when the record is created.
      - `auto: true` on a `date` field will automatically set the value to the current datetime when a record is created or updated.
      - `auto: [insert|update]` on a `date` field will automatically set the value to the current datetime when a record is either created or updated respectively.
      - `auto: true` on an `int` field combined with `increment.start: 1` will automatically increment the field value when a record is created, starting from `1.`
      - `auto: true` on a `string` field combined with `increment.pattern: "EXAMPLE-{0000}"` will automatically increment the string pattern, maintaining characters outside of the `{}` brackets, when a record is created.
    - `increment` (object): Used in combination with `auto: true`, defines how to automatically increment numerical values on `int` and string fields.
      - `start` (int): Number to begin incrementing from. This value applies globally for this collection, for example `start: 1` would set the number to `1, 2, 3, ...` on each record created respectively in this collection.
      - `pattern` (string): For `string` fields, defines the pattern including the numeric portion of a string in `{}` brackets, used to automatically set the string value.

        For example: `increment.pattern: "EXAMPLE-{0000}"` would result in a value  of `"EXAMPLE-0001"` on the first record created in the collection.
    - `rules` (array of rule): Trigger a system error when one or more rules are matched to record values.

      **Triggers:**

      - `expression`: Using a formula expression.
      - `conditions`: Using the equivalent format and operators of [query filtering](https://developers.swell.is/backend-api/querying/filtering#filtering).

      **Effects:**

      - `required`: Cause the field to be `required` when triggered.
      - `error`: Error message to return when triggered.
      - `expression` (string): A formula expression used to evaluate when the effect of the rule is triggered. See Formula documentation for details.
      - `conditions` (object): A query object used to match record values. When matched, the rule is triggered. Rule conditions support the equivalent format and operators of [query filtering](https://developers.swell.is/backend-api/querying/filtering#filtering).
      - `required` (boolean): If `true`, cause the field to be `required` when the rule is triggered.
      - `error` (string): Error message to return when the rule is triggered.
    - `length` (int): Requires an exact length of a `string` field.
    - `minlength` (int): Requires a minimum length of a `string` field.
    - `maxlength` (int): Requires a maximum length of a `string` field.
    - `min` (float): Requires a minimum value of an `int` or `float` field.
    - `max` (float): Requires a minimum value of an `int` or `float` field.
    - `sort` (enum): Automatically sorts an `array` field in ascending or descending order. Possible values: `asc`, `desc`.
    - `public` (boolean): Indicates that a field value is made accessible by a public API call, assuming the parent model does not have `public: true`.
    - `localized` (boolean): Indicates that a `string` or `currency` value can be localized by locale and currency codes.
- `namespace` (string): Optional namespace used in the model's API endpoint, for example "content" results in the endpoint `/content/model-name`.
- `version` (string, auto): Semver-formatted version number. This value is automatically incremented when the model is modified.
- `label` (string): Plural name of a model collection.
- `singular` (string): Singular name of a model record.
- `public` (boolean): Indicates the model collection and its values are public by default.
- `public_permissions` (object): Restrictive public query parameters for storefront API calls, if applicable.
  - `scope` (string): Set to `account` to limit public permissions to logged-in users only.
  - `fields` (array of field): Array of model fields to allow read access for.
  - `query` (object): Default parameters used when querying the model collection from a public API.
    - `where` (object): Default filter used when querying the model collection from a public API.
    - `limit` (int): Default number of records to return when querying the model collection from a public API.
    - `window` (int): Default number of pages in a pagination window to calculate when querying the model collection from a public API.
    - `sort` (string): Default sort parameter used when querying the model collection from a public API.
  - `input` (object): Permissions allowed for write access when called from a public API.
    - `scope` (string): Set to `account` to limit public permissions to logged-in users only.
    - `fields` (array of field): Array of model fields to allow write access for.
- `single` (boolean): Indicates the model only only has one record, instead of a collection.
- `abstract` (boolean): Indicates the model can be extended by another model, but cannot be instantiated as a collection.
- `primary_field` (string): The primary field used to look up records in the model collection. Default: `id`.
- `secondary_field` (string): Optional secondary field used to look up records in the model collection.
- `name_field` (string): The field used as a label for each record by default.
- `name_pattern` (string): A string pattern used to derive record names with string substitution, which can reference any field in the record. If defined, it is used instead of `name_field`.

  For example: `{name} - {sku}`

  The pattern may also reference nested or link fields, for example:

  `{parent.name} - {sku}`
- `query` (object): Default parameters used when querying the model collection.
  - `where` (object): Default filter used when querying the model collection.
  - `limit` (int): Default number of records to return when querying the model collection. Default: `15`.
  - `window` (int): Default number of pages in a pagination window to calculate when querying the model collection. Default: `10`.
  - `sort` (string): Default sort parameter used when querying the model collection.
- `storefront` (object): Storefront rendering options.
  - `enabled` (boolean): Indicates that model data may be displayed in a storefront. Default: `true`.
  - `list` (boolean): Indicates that model data may be displayed in a storefront list view.
  - `list_slug` (string): The URL slug used to play modal data in a storefront list view.
  - `list_title` (string): Title of the page to display a list of records in a storefront.
  - `list_description` (string): A description to display on a storefront list view.
  - `page` (boolean): Indicates that model data may be displayed in a storefront page view.
  - `page_slug_field` (string): Reference to a URL slug field used to play modal data in a storefront page view.
  - `page_title_field` (string): Reference to a title field to display on a storefront page view.
  - `page_description_field` (string): Reference to a description field to display on a storefront page view.
- `events` (object): Model event configuration. By default, each model is configured with `created`, `updated`, and `deleted` events. Custom events can be automatically triggered based on `conditions`, or manually triggered via API call.
  - `enabled` (boolean): Indicates that model events will be triggered by the system. Defaults to `true`.
  - `types` (array of event_type): Event types triggered by the system for this model.
    - `id` (string): ID of the event. Should be a short ID, such as `created`, while a fully-qualified event name is referenced in the following format: `[model-name].[event-name]`.
    - `conditions` (object): A query object used to match record values. When matched, the event is triggered. Event conditions support the equivalent format and operators of query filtering.
    - `fields` (array of field): Array of model fields to include in the event payload, which are sent to webhooks and app functions, as well as recorded in the system `/events` collection.
    - `hooks` (array of string): Enumerated hooks triggered by the event type. One of: `before`, `after`. Hooks allow app functions to block API call processing and modify values `before` and `after` an event is triggered.
    - `hook_timeout` (int): Maximum time in milliseconds to wait for a hook function to complete before timing out. Defaults to `60000` (60 seconds).
    - `hook_reject_error` (boolean): Indicates whether the event will reject requests when an error occurs in a configured hook function. Defaults to `false`.
    - `hook_retry_attempts` (int): Maximum number of times to retry a hook function when an unknown error occurs. Must be between `0` and `3`.
  - `root` (string, auto): Root name of event types used in webhooks. Defaults to a singularized version of the model name, for example `product`.
- `extends` (string): Name of a parent model to extend properties from.

  For example, to extend the standard product model in the definition of a new model:

  `"extends": "products"`

  All properties of the extended model will be inherited and merged under the new schema. Any property can be overridden or modified in the definition of the extending model, including field attributes.

  For example, if a parent model has an optional field `sku` and you want to make it required in the extending model:

  **models/custom-products.json**

  ```json
  {
    "extends": "products",
    "fields": {
      "sku": {
        "required": true
      }
    }
  }
  ```
- `extends_version` (string, auto): Automatically assigned version of an extended model, if applicable.
- `content_id` (string): ID of a content model that defined this model, if applicable.
- `deprecated` (boolean): Indicates the model is deprecated and may be removed in a future API version.
- `date_created` (date, auto): Date the model was created.
- `date_updated` (date, auto): Date the model was last updated.

### Example response

```json
{
  "version": "1.0.0",
  "label": "Blog",
  "plural": "Blogs",
  "extends": "base",
  "fields": {
    "title": {
      "type": "string",
      "required": true
    },
    "slug": {
      "type": "string",
      "format": "slug",
      "default": {
        "$formula": "slug(title)"
      }
    },
    "author_id": {
      "type": "objectid",
      "required": true
    },
    "author": {
      "type": "link",
      "model": ":users",
      "key": "author_id",
      "data": {
        "fields": "email,name,username"
      }
    },
    "category_id": {
      "type": "objectid",
      "required": true
    },
    "category": {
      "type": "link",
      "model": "content/blog-categories",
      "key": "category_id"
    },
    "content": {
      "type": "string",
      "format": "html",
      "multiline": true
    },
    "summary": {
      "type": "string",
      "format": "html",
      "multiline": true
    },
    "image": {
      "type": "object",
      "fields": {
        "file": {
          "type": "file"
        }
      }
    },
    "tags": {
      "type": "array",
      "value_type": "string",
      "unique": true
    },
    "published": {
      "type": "bool",
      "default": false
    },
    "date_published": {
      "type": "date",
      "label": "Publish Date"
    },
    "meta_title": {
      "type": "string",
      "label": "Page Title"
    },
    "meta_keywords": {
      "type": "string"
    },
    "meta_description": {
      "type": "string",
      "multiline": true
    }
  },
  "query": {
    "sort": "name asc"
  },
  "name_field": "title",
  "secondary_field": "slug",
  "events": {
    "enabled": true,
    "types": [{ "id": "created" }, { "id": "updated" }, { "id": "deleted" }]
  }
}
```

