Schema & property types

Define a bucket's properties, validation, defaults, relations and translations, and every bucket-level setting.

A bucket's schema is a JSON Schema document with a few Spica-specific keywords. You can edit it in the panel, over the API (POST /bucket, PUT /bucket/:id, PATCH /bucket/:id) or as YAML with the CLI.

Bucket settings

FieldTypeDescription
titlestring, 4–100 charsRequired. Name shown in the panel and used by the CLI as the folder name.
descriptionstring, 5–250 charsRequired. Shown under the title in the panel.
propertiesobjectRequired. The properties of a document, at least one.
primarystringThe property that represents a document, for example in relation pickers. On PostgreSQL it is also the primary key.
requiredstring[]Properties that every document must have.
iconstringMaterial icon name shown in the panel. Default view_stream.
categorystringGroups buckets in the panel sidebar.
ordernumberPosition of the bucket in the panel.
readOnlybooleanDocuments can't be edited from the panel's data pages.
historybooleanKeep the previous versions of each document. Default false.
acl{read, write}Rules evaluated for USER requests. Default true==true for both.
indexesarrayDatabase indexes for the bucket.
documentSettingsobjectcountLimit and limitExceedBehaviour (prevent or remove). See Document limits.

Property names must start with a letter or _, contain only letters, digits and _, and can't be _id.

Property types

TypeStored asPanel inputNotes
stringstringText fieldSupports enum, pattern, minLength, maxLength.
textareastringMulti-line text
richtextstring (HTML)Rich text editor
numbernumberNumber fieldSupports minimum, maximum, enum.
booleanbooleanToggle
datedateDate-time pickerSend ISO 8601 strings. Supports the :created_at and :updated_at defaults.
colorstringColor pickerHex color such as #36369c.
arrayarrayList editorDescribe the items with items. Supports minItems, maxItems, uniqueItems.
multiselectarrayMulti selectAn array of values chosen from items.enum.
objectobjectNested formDescribe the fields with properties and required.
jsonany JSONJSON editorNo inner validation.
storagestring (URL)File pickerStores the URL of a storage object.
relationid or id[]Document pickerReferences documents in another bucket. See Relations.
locationGeoJSON PointMap picker{"type": "Point", "coordinates": [longitude, latitude]}
hashstringText fieldStored as a one-way keyed hash. Can be matched in filters but never read back.
encryptedobjectText fieldEncrypted at rest, decrypted in responses.
uuidstringText fieldPostgreSQL only.
integerintegerNumber fieldPostgreSQL only.
bigintstringNumber fieldPostgreSQL only. Returned as a string to keep its precision.

You can ask an instance which types it supports:

Terminal
curl https://api.example.com/api/bucket/capabilities -H "Authorization: APIKEY <key>"
JSON
{"propertyTypes": ["array", "multiselect", "boolean", "number", "object", "string", "storage", "richtext", "date", "textarea", "color", "relation", "location", "json", "hash", "encrypted"]}

Common property keywords

Every property accepts these keywords in addition to type:

KeywordDescription
titleLabel shown in the panel.
descriptionHelp text shown in the panel.
defaultValue used when the property is missing on insert.
readOnlyThe value isn't editable in the panel. Combined with default, the server always writes the default and ignores the value the client sends.
enumAllowed values.
patternRegular expression a string must match.
minLength, maxLengthString length limits.
minimum, maximumNumber limits.
items, minItems, maxItems, uniqueItemsArray item schema and limits.
properties, requiredFields of an object property.
options.translateStore one value per language. See Translations.
aclA field-level rule. See Field rules.

Example

JSON
{
  "slug": {
    "type": "string",
    "title": "Slug",
    "description": "URL-safe identifier",
    "pattern": "^[a-z0-9-]+$"
  },
  "status": {
    "type": "string",
    "title": "Status",
    "enum": ["draft", "published"],
    "default": "draft"
  },
  "tags": {
    "type": "array",
    "title": "Tags",
    "items": {"type": "string"},
    "maxItems": 10,
    "uniqueItems": true
  },
  "views": {"type": "number", "title": "Views", "minimum": 0, "default": 0}
}

A document that breaks the schema is rejected with 400:

JSON
{"message": ".slug must match pattern \"^[a-z0-9-]+$\"", "error": "validation failed", "statusCode": 400}

Server-set dates

Use the predefined defaults to let Spica fill in dates:

DefaultValue
:created_atThe time of the write that sets it.
:updated_atThe time of the write that sets it.
JSON
{
  "created_at": {"type": "date", "title": "Created at", "default": ":created_at", "readOnly": true},
  "updated_at": {"type": "date", "title": "Updated at", "default": ":updated_at"}
}

Defaults are applied on insert and on replace (PUT), not on patch (PATCH). Two consequences:

  • With readOnly, created_at is written again on every PUT. Update documents with PATCH when you want to keep the original creation time.
  • updated_at is only refreshed by PUT. If you patch documents and need a reliable modification time, set it yourself or from a bucket trigger.

GET /bucket/predefineddefaults lists the available defaults.

Relations

A relation property stores references to documents in another bucket:

JSON
{
  "author": {
    "type": "relation",
    "title": "Author",
    "bucketId": "<authorsBucketId>",
    "relationType": "onetoone",
    "dependent": false
  }
}
FieldDescription
bucketIdRequired. The referenced bucket.
relationTypeRequired. onetoone stores a single id, onetomany stores an array of ids.
dependentWhen true, deleting a document also deletes the documents it references through this property. Default false.

Write relations as ids, and use the relation query parameter to resolve them when you read.

Translations

Set options.translate to store one value per language:

JSON
{"title": {"type": "string", "title": "Title", "options": {"translate": true}}}

Write all languages as an object keyed by locale:

JSON
{"title": {"en_US": "Hello Spica", "tr_TR": "Merhaba Spica"}}

When you read, Spica returns the value in the language of the Accept-Language header and falls back to the default language. The available and default languages are stored in the bucket preferences:

Terminal
curl https://api.example.com/api/preference/bucket -H "Authorization: IDENTITY <token>"
JSON
{"scope": "bucket", "language": {"available": {"tr_TR": "Turkish", "en_US": "English"}, "default": "en_US"}}

Change them with PUT /preference/bucket or in the panel. See Localization for reading options.

Locations

A location property stores a GeoJSON point. Coordinates are [longitude, latitude]:

JSON
{"location": {"type": "Point", "coordinates": [28.97, 41.01]}}

Add a 2dsphere index when you filter by distance.

Hashed and encrypted properties

Both types protect sensitive values. They need the bucket-data-hash-secret and bucket-data-encryption-secret API options, which are derived from the master key when you don't set them.

hashencrypted
StoredA keyed hash (HMAC)Ciphertext plus a hash
ReturnedThe hashThe original value
Filter with equalityYes, send the plain valueYes, send the plain value
Use forNational ids, values you only comparePhone numbers, addresses, values you must display
JSON
{
  "national_id": {"type": "hash", "title": "National ID"},
  "phone": {"type": "encrypted", "title": "Phone"}
}

Primary keys on PostgreSQL

On PostgreSQL, primary names the bucket's primary key, and documents are identified by that property instead of _id. The primary property must be of type uuid, integer, bigint or string, can't be translated, and can set options.generated to let the database create values:

JSON
{
  "title": "Authors",
  "description": "People who write posts",
  "primary": "id",
  "properties": {
    "id": {"type": "uuid", "title": "ID", "options": {"generated": true}},
    "name": {"type": "string", "title": "Name"}
  }
}

Only the primary property can be generated. More differences between the engines are listed in MongoDB and PostgreSQL.

Changing a schema

You can change a bucket at any time. Keep in mind:

  • New required properties and stricter validation only apply to documents you write from now on.
  • Removing a property doesn't remove existing values from stored documents.
  • Changing a property's type can make old values fail validation on the next write.
  • Deleting a bucket deletes all of its documents and history.

Review schema changes before they reach production with spica plan.