Skip to content

mutation

Terminal window
npx skills add https://github.com/crystallizeapi/ai --skill mutation

Crystallize Mutation Skill

Create, update and manage data in Crystallize with GraphQL mutations. Writes split along the same line as reads: everything a shopper does goes through the Shop API, from your server, and catalogue and tenant management goes through the Core API, from scripts and the back office. The full storefront contract is in [[storefront]].

Consultation Approach

Before writing mutations, ask:

  1. Who triggers the write: a shopper (storefront, account page, payment webhook) or the back office (seed, import, admin tool)? Shopper → Shop API. Back office → Core API (or a mass operation).
  2. Will a storefront read the result? Orders and customers a storefront lists are created and changed on the Shop API, so they stay one record in one store.
  3. Do you have the right token? Core takes an access token pair. The Shop API takes a JWT minted for one tenant, with a pair scoped to that tenant or unscoped.
  4. Is it a field edit or a rebuild? updateComponent for one field; anything with components replaces the whole set (see What a partial write replaces).
  5. Should it go live? Creating or updating an item doesn’t publish it, and publishing is asynchronous.
  6. One-off or bulk? Single mutations, or a mass operation ([[mass-operations]]).

The storefront API contract, for writes

Who writes API Runs Examples
A shopper, through the storefront Shop API Server actions, routes, payment webhooks Cart, customer on the cart, place, orders, payments, customers, bookings, contracts, locks
The back office, scripts, imports Core API Scripts, jobs, admin tools behind login Items, variants, components, publish, customers with hierarchies, media, webhooks
Tenant setup Legacy PIM Setup scripts Pipelines, stock locations, VAT types, markets, subscription plans
Many items at once Mass operations Scripts Imports, migrations
  • Core is never in the storefront’s request path: it is heavily rate limited and not meant for shopper traffic, not even server-side behind a cache. The exceptions are webhook receivers and staff tools, which are back office. The Shop API is edge-distributed and syncs to Core asynchronously, so the back office still sees every order.
  • The Shop API is server only. Its CORS allows only Crystallize origins and localhost, so a browser call that works in development fails on your own domain. The browser keeps the cart id in an httpOnly cookie.
  • Write an order in one store, see Orders: which store, which call.

Endpoints and tokens

API Endpoint Credential
Core https://api.crystallize.com/@{tenant} Access token pair
Shop /cart https://shop-api.crystallize.com/{tenant}/cart JWT, cart scope
Shop /cart/admin https://shop-api.crystallize.com/{tenant}/cart/admin JWT, cart + cart:admin (promotions)
Shop /order https://shop-api.crystallize.com/{tenant}/order JWT, order
Shop /customer https://shop-api.crystallize.com/{tenant}/customer JWT, customer
Shop /subscription-contract https://shop-api.crystallize.com/{tenant}/subscription-contract JWT, subscription-contract, its own token
Shop /booking/admin https://shop-api.crystallize.com/{tenant}/booking/admin JWT, booking:admin
Shop /lock https://shop-api.crystallize.com/{tenant}/lock JWT, lock
PIM (legacy) https://pim.crystallize.com/graphql Access token pair; most calls take tenantId

Core API

Terminal window
curl -X POST 'https://api.crystallize.com/@your-tenant' \
-H 'Content-Type: application/json' \
-H 'X-Crystallize-Access-Token-Id: YOUR_TOKEN_ID' \
-H 'X-Crystallize-Access-Token-Secret: YOUR_TOKEN_SECRET' \
-d '{"query": "mutation { ... }"}'

Note the @ before the tenant identifier. Generate access tokens in the Crystallize App under Settings > Access Tokens; see [[permissions]] for scoping them.

Shop API

The @ is optional on the Shop API. Mint the JWT on your server, with one scope per route you call:

Terminal window
curl -X POST 'https://shop-api.crystallize.com/your-tenant/auth/token' \
-H 'Content-Type: application/json' \
-H 'X-Crystallize-Access-Token-Id: YOUR_TOKEN_ID' \
-H 'X-Crystallize-Access-Token-Secret: YOUR_TOKEN_SECRET' \
-d '{"scopes": ["cart", "order", "customer"], "expiresIn": 86400}'

It answers { "success": true, "token": "..." }, sent as Authorization: Bearer <token>.

  • The access token must not be tenant-scoped: the token endpoint checks it on /@me, which refuses tenant-scoped tokens and plugin bearer tokens ([[permissions]]).
  • scopes is required. expiresIn is in seconds: one day by default in the API, 12 hours in js-api-client. Cache the JWT and refresh it before it expires; an expired one fails with "exp" claim timestamp check failed.
  • The JWT is per tenant, not per shopper: it can write any customer’s cart or order, so it never reaches the browser.
  • Request a separate token for /subscription-contract: a token with every scope answered “Unexpected error” on create.
  • The Shop API reads products from the Catalogue with the request’s credentials. On a tenant whose Catalogue requires a token, send it (X-Crystallize-Static-Auth-Token, or the pair) on every /cart call that reads products.

Decision Tree

What do you need to do?
│
├─ Shopper actions (storefront, account page, payment webhook): Shop API, server-side
│ ├─ Create or update the cart → /cart hydrate (send the WHOLE item list: it replaces) or addSkuItem
│ ├─ Customer on the cart → /cart setCustomer, or hydrate(customer: { identifier, isGuest: false })
│ │ └─ B2B on behalf of a company → the organisation as the cart customer, the person in cart meta
│ ├─ Lock the cart before charging → /cart place (charge its total)
│ ├─ Order from the cart → /order createFromCart(id, { pipelines, paymentStatus, payments }), no fulfill
│ ├─ Order without a cart (POS, accepted quote, demo seed) → /order create
│ ├─ Payments → /order addPayments / setPayments (paymentStatus is set once, at creation)
│ ├─ Pipeline stage → /order addToStage (ids, not names), then setMeta
│ ├─ Order metadata → /order setMeta (not Core updateOrder)
│ ├─ Customer record → /customer customer(input), addAddress, setMeta
│ ├─ Bookings → /cart bookSkuItem, confirmCartBooking: see bookable-resources
│ ├─ Subscription contracts → one store per tenant: see subscriptions
│ └─ Idempotency guard (webhooks, one order per cart) → /lock acquire / release
│
├─ Catalogue (back office, scripts): Core API
│ ├─ Create new item → createProduct / createDocument / createFolder
│ ├─ Update a field, or translate → updateComponent (per component, per language)
│ ├─ Rename → update*(input: { name }) (changes the path; the old one goes to history)
│ ├─ Add/update product variants → addProductVariant / updateProductVariant (send its components)
│ ├─ Publish/unpublish → publishItem / unpublishItem (asynchronous)
│ └─ Delete an item → deleteItem
│
├─ Customers in the back office: Core API
│ ├─ A person or a company, with parents → createCustomer (type: individual | organization)
│ └─ Update → updateCustomer(identifier:) (lists you send replace the stored ones)
│
├─ Orders nobody reads from the edge (imports into the back office) → Core registerOrder
│
├─ Media (images, video) → see the media skill
│
├─ Cache revalidation on publish → Core createWebhook(concern: "items")
│
└─ Bulk operations → a mass operation: see the mass-operations skill

Orders: which store, which call

Shop API orders and Core orders are meant to be one order in two stores, synced asynchronously. Shop /order is the entry for volume: asynchronous, a FIFO queue, built for millions of orders, so an answer means accepted, not stored. Core is synchronous but rate limited, so it suits imports and back-office edits. Where an order is born decides what later writes do to it, so choose by who reads it:

The order Create with Change with
Comes from a storefront cart Shop /order createFromCart Shop setMeta, addToStage, addPayments
Has no cart but a storefront or the Shop API lists it (POS, accepted quote, demo seed) Shop /order create The same Shop calls
Nobody reads it from the edge (an import into the back office) Core registerOrder Core updateOrder
  • A Core edit of a Core-born order adds another copy to the Shop store (a sync bug, reported): three updateOrder calls left three Shop orders with one coreId, and a storefront summing the list counted the money three times. Until it is fixed, readers group by coreId. A Core edit of a Shop-born order overwrites it whole.
  • createFromCart: the cart must be placed; pass pipelines, paymentStatus and payments in the input rather than chaining calls, because the order is saved just after the answer. It copies the cart’s meta (plus cartId, cartState, cartType) into the order, and its input has no meta, so set meta on the cart first. additionalInformation: null is refused (“Output validation error”, naming no field): leave it out. It moves the cart to ordered, so never call fulfill after it. The order id is the cart id.
  • create takes relatedOrderIds (Core ids) for an order made from a quote. Whether it honours createdAt was observed both ways (back-dated on one tenant, “now” on another): keep the intended date in meta (orderedAt) as well.
  • The listing lags. orders(customerIdentifier:) shows new orders after seconds to minutes, and a few never appeared. Read by id, and key idempotency on your own meta or a /lock, never on the listing ([[query]]).
  • There is no delete on the Shop API. Archive with setMeta and filter.

Details, inputs and the full store table: Shop API Order Mutations.

Common Workflow Patterns

Checkout (storefront, all server-side)

  1. Cart: a server action calls /cart hydrate with the whole basket, the price context and the customer. Check the SKUs against Discovery in parallel: an unknown SKU is dropped, or fails the call.
  2. Customer and meta: setCustomer (for B2B, the organisation, with the person in cart meta), then setMeta.
  3. Place: place locks the cart and hydrates it one last time. If order creation later fails, the shopper needs a new cart.
  4. Payment: create the provider session on the server from place’s total ([[payments]]).
  5. Order: in the provider’s webhook, verify, then /order createFromCart with pipelines, paymentStatus and payments in the input. Bookings: once cart.orderId is set, confirmCartBooking again ([[bookable-resources]]).
  6. Confirmation: show the order createFromCart returned, or order(id:) with a retry; say that order history can take a moment to update.

See Shop API Cart Mutations and Shop API Order Mutations.

Create a product end-to-end (back office)

  1. Create the product with shape, parent folder, VAT type, at least one variant, and every required component. A numeric with a unit list must have a value on create, or the write fails (Unit-bound numerics)
  2. Translate with updateComponent per component and language, after the language version exists
  3. Publish, then wait for the published version before relying on Discovery (Discovery Indexing)

Update content on an existing item

  1. Query the item to confirm its ID and current state (use the query skill)
  2. Call updateComponent for each field you change: it touches only that component
  3. Publish if the change should go live

Revalidate the storefront on publish

Register a Core webhook with concern: "items"; item and product are accepted and never fire. Add a graphqlQuery with preserveDefaultPayload: true when the receiver needs the path, and debug with webhookInvocations. See Webhooks.

Bulk import / mass operations

Use a mass operation: see [[mass-operations]], and [[content-model]] for shapes and pieces. Order: pieces, shapes, topic maps, items.

Error Handling

The Core API uses union return types. Always include error fragments:

mutation {
createProduct(language: "en", input: { ... }) {
... on Product {
id
name
}
... on BasicError {
errorName
message
}
}
}

The Shop API has no unions: a failure comes back in the standard GraphQL errors list. A missing, expired or rejected token answers HTTP 401 with { "success": false, … } and no errors. Neither API accepts an explicit null for an optional field: leave the key out.

Common Core error types: BasicError, UnauthorizedError, ItemNotFoundError, OrderDoesNotBelongToTenantError.

Using the JS API Client

For JavaScript/TypeScript, use @crystallize/js-api-client; see [[js-api-client]].

import { createClient } from "@crystallize/js-api-client";
const api = createClient({
tenantIdentifier: "your-tenant",
accessTokenId: "...",
accessTokenSecret: "...",
});
// Core API mutations (back office only)
const result = await api.nextPimApi(mutationString, variables);
// Shop API mutations (server-side): one caller per route, the Shop API token is fetched for you
await api.shopCartApi(cartMutation, variables); // /cart
await api.shopOrderApi(orderMutation, variables); // /order (js-api-client 7.5+)

For checkout, prefer the helpers: createCartManager (hydrate, place), createShopOrderManager (createFromCart, addPayments, setPayments, addToStage) and createShopCustomerManager (upsert, addAddress).

Output Format

When generating mutations for the user, produce:

  1. GraphQL mutations with clear variable placeholders (e.g., "your-tenant-id", "item-id")
  2. Variable definitions when the mutation uses GraphQL variables
  3. Expected response shape so the user knows what to look for
  4. Where it runs: server action, webhook, script or admin tool, and which token it needs

If the user is working in a JS/TS project, prefer generating code using @crystallize/js-api-client helpers.

References

  • Core API Mutations - Item CRUD, variants, components, partial writes, unit-bound numerics, id argument types, customers, pipelines, webhooks, publish/unpublish, delete
  • Shop API Cart Mutations - Cart hydration, item management, checkout flow, cart lifecycle
  • Shop API Order Mutations - Order creation (from cart or direct), payments, pipelines, metadata, the order store
  • Media & Images - Moved to the [[media]] skill

[[storefront]] owns the API contract and the request path per page type. [[query]] covers reads across the same APIs. Importing images and video is [[media]]. For bulk writes that would otherwise hit rate limits, use [[mass-operations]]. Vector ranking has its own Core mutations (upsertVocabulary, setItemTaste, igniteDiscoApi) in [[vector-ranking]]. Taking payment is in [[payments]], bookings in [[bookable-resources]], subscription contracts in [[subscriptions]], and prices and promotions in [[pricing]].


Reference Details

Core API Mutations Reference

The Core API provides full read/write access to items, shapes, customers, orders, and configuration. It is for the back office (seeds, imports, scheduled jobs, webhook receivers, admin tools behind staff login) and never for a storefront’s request path: shopper writes go to the Shop API ([[storefront]]).

See SKILL.md for endpoint URLs and authentication headers.

Two things decide the shape of every call on this page:

  • Mutations are top level. createProduct, publishItem, updateComponent — there is no product { … } or item { … } wrapper. That wrapper belongs to the legacy PIM API, which is a different endpoint with a different schema.
  • The tenant is in the URL (https://api.crystallize.com/@<tenant>), so no input takes a tenantId. The PIM API does, which is the quickest way to tell a Core example from a PIM one.

Table of Contents


Reading a result

Every mutation returns a union: the thing you asked for, or one of several error types. The error members all implement BasicError, so one fragment catches every failure and errorName identifies it:

mutation PublishItem($id: ID!, $language: String!) {
publishItem(id: $id, language: $language) {
__typename
... on PublishInfo {
id
versionId
}
... on BasicError {
errorName
message
}
}
}

Three error members are on almost every union: UnauthorizedError (the token lacks the permission), UnknownError, and ExperimentalFeaturesNotAvailableError (the feature is not enabled for the tenant). Select __typename when you want to branch on the outcome in code.

The success member is often not the item. Reaching for ... on Item is the most common mistake here:

Mutation Success member
createProduct / updateProduct Product
createDocument / createFolder Document / Folder
publishItem / unpublishItem PublishInfo
deleteItem / deleteCustomer DeleteCount { removed }
updateComponent UpdatedComponent
removeComponent ItemComponentRemoved
addProductVariant / updateProductVariant ProductVariant
modifyProductVariantStock ProductStockLocation
modifyProductVariantPrice ProductPriceVariant
addItemsToFlowStage FlowContentList

The examples below keep the BasicError fragment where a call is easy to get wrong, and leave it out where it would only repeat itself. Add it everywhere in real code.


Item Mutations

language is an argument, not an input field, on every create and update.

Create Product

variants and vatTypeId are required — a product cannot exist without at least one SKU and a VAT type. Read the VAT types from the PIM API (see below) and keep the id in your config. Exactly one variant must have isDefault: true, or the call fails.

mutation CreateProduct($input: CreateProductInput!, $language: String!) {
createProduct(input: $input, language: $language) {
__typename
... on Product {
id
name
}
... on BasicError {
errorName
message
}
}
}
{
"language": "en",
"input": {
"shapeIdentifier": "sneaker",
"name": "Air Max 2024",
"vatTypeId": "<vat type id>",
"tree": { "parentId": "<folder id>" },
"variants": [{ "sku": "air-max-2024-42", "name": "Size 42", "isDefault": true, "price": 129.99 }]
}
}

tree is { parentId, position }. Leave it out and the item is created without a place in the tree; add one later with createItemTreeNode(input: { itemId, parentId, position }).

Send every required component on create. Creation validates the shape, so a required relation or a numeric with a unit list fails with ComponentContentValidationFailedError unless its content is in components. Create-then-fill does not work.

Create Document

mutation CreateDocument($input: CreateDocumentInput!, $language: String!) {
createDocument(input: $input, language: $language) {
... on Document {
id
name
}
... on BasicError {
errorName
message
}
}
}
{
"language": "en",
"input": {
"shapeIdentifier": "blog-post",
"name": "Welcome to Our Store",
"tree": { "parentId": "<folder id>" }
}
}

Create Folder

mutation CreateFolder($input: CreateFolderInput!, $language: String!) {
createFolder(input: $input, language: $language) {
... on Folder {
id
name
}
... on BasicError {
errorName
message
}
}
}
{
"language": "en",
"input": {
"shapeIdentifier": "category",
"name": "Summer Collection",
"tree": { "parentId": "<shop folder id>" }
}
}

Publish Item

Publishing makes the item visible on the storefront. Creating an item does NOT publish it.

Publishing runs in the background. The answer means the request was accepted, not that the published version exists yet, even though PublishInfo.versionId already names it. A step that depends on the published version has to read it first: item(id:, language:, versionLabel: published).

mutation PublishItem {
publishItem(id: "<item id>", language: "en", includeDescendants: false) {
... on PublishInfo {
id
versionId
}
... on BasicError {
errorName
message
}
}
}

includeDescendants: true publishes the children too, which is what you want for a folder. disableComponentValidation: true publishes an item whose shape validation would otherwise block it — an empty numeric piece is the usual reason.

publishItems(ids: [ID!]!, language: String!) exists for batches of up to 50 ids (more answers TooManyItemsProvidedError). It takes the same two flags and answers with a PublishItemsRequest, { language, success { itemId }, failure { itemId, error } }, so read failure: one item failing validation does not fail the call. unpublishItems is the same.

Unpublish Item

Unpublishing always takes the children with it. includeDescendants defaults to true here, unlike on publishItem, and false is ignored: everything under the item goes off the storefront. Move a child out first to keep it live.

mutation UnpublishItem {
unpublishItem(id: "<item id>", language: "en") {
... on PublishInfo {
id
}
... on BasicError {
errorName
message
}
}
}

Delete Item

mutation DeleteItem {
deleteItem(itemId: "<item id>") {
... on DeleteCount {
removed
}
... on BasicError {
errorName
message
}
}
}

The argument is itemId, and the answer is a count, not the item.

Deleting a folder deletes everything under it. There is no check and no prompt: the children go in the background, after the answer, and removed counts only the item you named. Move what you want to keep first.

Move Item in Tree

mutation MoveItem {
moveItemTreeNode(itemId: "<item id>", language: "en", input: { parentId: "<new parent id>", position: 1 }) {
itemId
parentId
path
position
}
}

moveItemTreeNode returns an ItemTreeNode directly — it is one of the few mutations that is not a union. position is a PositiveInt, so it counts from 1.


What a partial write replaces

The item mutations are not patches. Sending a component list means “these are the components now”, and the calls that look narrow have the widest blast radius. Every row below cost a build a round of re-imports.

Call What it does to everything you did not send
updateProduct / updateDocument with components Replaces the whole component set: translated components in that language, shared (non-translated) ones in every language
updateProduct / updateDocument with only name Leaves components alone, but changes the path (see below)
updateDocument(input: { topicIds }) alone Keeps every component: topics can be rewritten on each run
updateProductVariant without components Empties that variant’s components in that language
updateComponent(itemId, language, component) Touches that one component only — use it for partial edits
updateComponent with a piece Replaces every sub-component of the piece: resend them all
updateProductVariant(images) in one language Writes that language only: write variant images per language
product/upsert and friends in a mass operation Replace all components, so send every one, not only the changed one
setItemTaste Emptied every variant’s components on one tenant (contested, below)

Translating is where this bites. Writing two fields in a second language with updateProduct(language: "no", input: { components: [tagline, summary] }) fails with “Need to provide at least 1 related items for component brand” — and had it passed, it would have dropped everything not sent. Translate with updateComponent per component, and rename with update*(input: { name }). Shared (non-multilingual) components then keep showing in every language, untouched.

Renaming changes the path. update*(input: { name }) regenerates the item’s path from the new name (lower case, æ → ae, ø → o, å → a, other diacritics stripped, every run of non-alphanumerics → -) and writes the old path to history. To keep a legacy URL, pick a name that slugifies to the old slug and keep the display title in a component, or add aliases; otherwise 301 from history ([[information-architecture]]).

Create the language version before translating components. updateComponent(language: "fi") on an item with no Finnish version fails with a bare TypeError — Cannot read properties of undefined (reading 'shortcuts'). Write update*(id, language: "fi", input: { name }) first, then the components, and not concurrently.

createdAt is accepted and ignored on CreateDocumentInput, UpdateDocumentInput and document/upsert: the item gets “now”. Keep an original publish date in a component of its own.

setItemTaste has a side effect on variants — contested. After writing taste, the draft’s variant components were gone in every language while product components survived, and the publish that follows taste then published them empty. Order the pipeline: taste first, then (re)write variant components, then publish. (Tools Universe. The same build first blamed a shape update and re-ran it, which changed nothing. Four later tenants did not see it: keep a read-back check rather than a rule; [[vector-ranking]].)

A variant’s content chunks may not publish at all — contested. On the same tenant a variant chunk sat in the draft, but after publishItem the current version — and Discovery — had chunks: [], while a singleLine on the same variant and a numeric on another shape’s variants published fine. If a variant chunk disappears on publish, move that data to the product (one row per variant, with the SKU in it). Another tenant published variant chunks fine and Discovery served them, so check on yours.

Creating an item validates its required components, so create is not “create then fill”: a document whose relation has minItems: 1, or a numeric with a unit list, fails createDocument with ComponentContentValidationFailedError unless those components are in the create input. Send everything on create.

Unit-bound numerics

A numeric component with a unit list is the most common write failure across builds (nine of them). The rule, in one place:

  • It fails create, updateProduct and an upsert’s update for any product or variant that has no value, even when you didn’t send the component and even when it isn’t required: No unit provided for numeric item component runtime. Need to specify one of the following units: min.
  • The empty value then blocks publishing too.
  • The unit is stored per value, so range filters in Discovery compare raw numbers across units ([[content-model]]).

Workarounds that worked:

Workaround Cost
Drop the units list from the component config None for writes; the unit is still stored per value. Keep one unit per numeric
Create with { number: 0, unit }, then removeComponent Two writes per item
updateComponent per component instead of update* One call per component
publishItem(disableComponentValidation: true) Also hides shape-limit violations (relations over max), so check those yourself

Id argument types

The Core item mutations don’t agree on the type of the id, and a shared $id variable with the wrong type fails validation before anything runs (introspected 2026-11-12):

Mutation Id argument
updateFolder, updateDocument, updateProduct id: String!
updateComponent itemId: ID (or sku: String for a variant)
publishItem, unpublishItem id: ID!
deleteItem itemId: ID!
removeComponent itemId: ID!, componentId, sku
updateProductVariant sku: String!
addVariantTopics sku: String!, topicIds: [String!]!

Component Updates

updateComponent changes one component on one item, in one language. It is the call to reach for when you are editing rather than rebuilding: everything else that takes components replaces the whole set.

mutation UpdateComponent($itemId: ID!, $language: String!, $component: ComponentInput!) {
updateComponent(itemId: $itemId, language: $language, component: $component) {
__typename
... on UpdatedComponent {
updatedComponentPath
item {
id
}
}
... on BasicError {
errorName
message
}
}
}

Arguments worth knowing:

Argument Meaning
itemId The item to edit
sku Edit a variant’s component instead — pass the SKU rather than itemId
language Required; components are per language unless the shape says otherwise
disableContentValidation Defaults to true: pass false to have the shape validate the content

With the default, updateComponent stores content the shape would reject and the problem only surfaces on publish. ComponentContentValidationFailedError needs disableContentValidation: false.

ComponentInput is { componentId, <one content key> }. The content key names the component type, and the examples below differ only in that key. removeComponent(itemId:, language:, componentId:) clears one; it also takes sku for a variant component, and itemId stays required.

Rich Text

html and json are lists — one entry per block.

{ "componentId": "description", "richText": { "html": ["<p>New product description</p>"] } }

Single Line

{ "componentId": "tagline", "singleLine": { "text": "Premium quality materials" } }

Numeric

number is required, so a numeric cannot carry a unit without a value.

{ "componentId": "weight", "numeric": { "number": 1.5, "unit": "kg" } }

Boolean (Switch)

{ "componentId": "featured", "boolean": { "value": true } }

Images Component

images is a list of ImageInput, and key is the only required field. The key comes from the media library — see Media & Images.

{ "componentId": "gallery", "images": [{ "key": "<image key>", "altText": "Product front view" }] }

Selection

{ "componentId": "color", "selection": { "keys": ["red"] } }

Colors

{
"componentId": "brand-color",
"colors": { "colors": [{ "label": "Midnight Blue", "hex": "#191970", "rgb": { "r": 25, "g": 25, "b": 112 } }] }
}

The content input is colors: { colors: [GraphqlInputColorEntry!] } — note the doubled key: the component input field is colors, and it wraps a list also called colors.

Each entry carries any combination of hex, rgb { r g b a }, hsl { h s l a }, cmyk { c m y k }, pantone, ral and label. They are notations of the same colour, not separate colours — send as many as the item actually has, and write the whole list every time, since the list replaces rather than merges. colors is also valid inside NestableComponentInput, so it works within chunks, choices and pieces.

See the [[content-model]] skill for when to use Colors rather than a Selection.

Item Relations

Relate by item, by SKU, or both.

{ "componentId": "related-products", "itemRelations": { "itemIds": ["<item id>"], "skus": ["<sku>"] } }

Content Chunk (repeatable)

chunks is a list of lists: one inner list per repetition, holding that repetition’s components.

{
"componentId": "specifications",
"contentChunk": {
"chunks": [
[
{ "componentId": "label", "singleLine": { "text": "Weight" } },
{ "componentId": "value", "singleLine": { "text": "1.5 kg" } }
],
[
{ "componentId": "label", "singleLine": { "text": "Dimensions" } },
{ "componentId": "value", "singleLine": { "text": "30x20x10 cm" } }
]
]
}
}

The other content keys on ComponentInput follow the same pattern: datetime, files, gridRelations, location, paragraphCollection, piece, propertiesTable, videos, and the structural componentChoice / componentMultipleChoice, which nest a NestableComponentInput.


Product Variants

Variants are purchasable SKUs on a product. There is no setVariants on Core: variants are added, updated and deleted one at a time, and stock and price have their own mutations.

Task Mutation
Add a variant addProductVariant(productId:, language:, input: CreateProductVariantInput!)
Change one variant updateProductVariant(sku:, language:, input: UpdateSingleProductVariantInput!), no isDefault here
Delete one deleteProductVariant(sku:) — refuses the default with CannotDeleteDefaultVariantError
Replace the whole set updateProduct(id:, language:, input: { variants: [...] })
Stock modifyProductVariantStock(sku:, stockLocationIdentifier:, operation:, quantity:)
Price modifyProductVariantPrice(sku:, priceVariantIdentifier:, price:, tiers:, tierType:)

Add a Variant

mutation AddVariant($productId: String!, $language: String!, $input: CreateProductVariantInput!) {
addProductVariant(productId: $productId, language: $language, input: $input) {
... on ProductVariant {
sku
name
}
... on BasicError {
errorName
message
}
}
}
{
"productId": "<product id>",
"language": "en",
"input": {
"sku": "sneaker-red-42",
"name": "Red - Size 42",
"isDefault": false,
"priceVariants": [{ "identifier": "default", "price": 129.99 }],
"attributes": [
{ "attribute": "color", "value": "Red" },
{ "attribute": "size", "value": "42" }
],
"images": [{ "key": "<image key>", "altText": "Red sneaker size 42" }]
}
}

price sets the default price variant; priceVariants: [{ identifier, price }] sets any of them, which is what you want on a multi-currency tenant. See [[pricing]].

Update Stock

mutation SetStock {
modifyProductVariantStock(
sku: "sneaker-red-42"
stockLocationIdentifier: "oslo"
operation: overwrite
quantity: 50
) {
... on ProductStockLocation {
identifier
stock
}
... on BasicError {
errorName
message
}
}
}

operation is increase, decrease or overwrite, so a delta needs no read first. The stock location must exist — create it in the PIM API.

Variant Attributes

Attributes define the variant matrix (e.g. colour + size) and appear as filterable properties in the storefront. Use consistent attribute names across products so the filters line up.


Customer Mutations

One mutation creates both kinds of customer: type is individual or organization. There is no createIndividual or createOrganization on Core. From a storefront, use the Shop API /customer endpoint instead, see Customer Creation.

Create a Customer

mutation CreateCustomer($input: CreateCustomerInput!) {
createCustomer(input: $input) {
__typename
... on Customer {
identifier
type
}
... on BasicError {
errorName
message
}
}
}
{
"input": {
"identifier": "jane@example.com",
"type": "individual",
"firstName": "Jane",
"lastName": "Smith",
"email": "jane@example.com",
"phone": "+1234567890",
"addresses": [
{
"type": "delivery",
"street": "123 Main St",
"city": "New York",
"postalCode": "10001",
"country": "US"
}
]
}
}

identifier is the only required field and it is the customer’s key everywhere else — carts, orders, subscription contracts and customer-targeted price lists all name it. An address type is the enum billing, delivery or other, not a string. A company uses type: organization with companyName and taxNumber.

Customer Hierarchies

parents links a customer to a company or a group:

{
"input": {
"identifier": "buyer@acme.example.com",
"type": "individual",
"parents": [{ "identifier": "acme", "type": "customer" }]
}
}

type on a parent is customer or customerGroup, and a customer can have more than one — too many answers TooManyCustomerParentsProvidedError.

  • Customer groups are the folder concept, and they nest. CustomerType is only individual | organization; createCustomerGroup takes other groups as parents. A three-level tree works: groups → organisations (parents: [{ type: customerGroup }]) → people (parents: [{ type: customer }]). childCount reads it back. Use groups as folders, not as price-list targets ([[pricing]]).
  • customers(filter: { parent: { identifier, type: customer } }) returns direct children only.
  • customers(filter: { meta: { key, value } }) finds customers by one meta pair, and metaProperty(key) reads one value. People often carry their department’s keys too, so add a kind key or check type.
  • Meta presets (createMetaPreset) apply to an entity through a limitation keyed by the entity (customer, order, order-item, subscription-contract, asset) with the values ["no-limitations"] for “all”. An enum value is stored as a JSON array of option keys (["NOK"]); anything else renders as nothing selected, and a filter on such a key passes the array string.
  • A PIM market’s customerIdentifiers must name existing customers: create the customers first. This is how a B2B contact belongs to its company, which in turn decides whose orders it sees and which contract prices apply — see [[pricing]].

Update and Delete

mutation UpdateCustomer {
updateCustomer(identifier: "jane@example.com", input: { lastName: "Doe" }) {
... on Customer {
identifier
}
... on BasicError {
errorName
message
}
}
}

Both updateCustomer and deleteCustomer take the identifier, not an id. deleteCustomer(identifier:, deleteSubscriptionContracts: true) removes the customer and its contracts in one call; orders are deleted separately. As with items, a list you send replaces the stored one — sending meta or addresses drops whatever you left out.


Order Mutations

If a storefront lists these orders, change them on the Shop API instead. On an order born in Core (registerOrder), every updateOrder adds another copy of the order to the Shop store: three updates on one order left three Shop orders with new ids, the same coreId and different updatedAt, and a storefront summing that list counted the money three times. On an order born on the Shop API, the same calls rewrite the Shop order with Core’s whole version, over whatever the Shop wrote last. Use Shop /order setMeta and addToStage for anything a storefront reads, and keep Core order writes for back-office work on orders nobody lists from the edge. See Shop API Order Mutations.

Update Order

mutation UpdateOrder($id: ID!, $input: UpdateOrderInput!) {
updateOrder(id: $id, input: $input) {
__typename
... on Order {
id
updatedAt
}
... on BasicError {
errorName
message
}
}
}
{ "id": "<order id>", "input": { "meta": [{ "key": "tracking_number", "value": "1Z999AA10123456784" }] } }

UpdateOrderInput also carries cart, customer, payment, paymentStatus, total, additionalInformation, relatedOrderIds and stockLocationIdentifier. For a single key, updateOrderMetadata(id:, key:, value:) is narrower and does not touch the rest; deleteOrderMetadata(id:, key:) removes one.

registerOrder(input: RegisterOrderInput!) writes an order that did not come from a cart, for orders nobody reads from the edge (an import into the back office, renewals on a tenant whose contracts live in Core). A POS sale, an accepted quote or a demo seed that a storefront lists is a Shop API create instead (see the store table in Shop API Order Mutations). Quotes are type: quote with the order made from them pointing back through relatedOrderIds. The order reference can’t be set (Core gives each order a random one), so keep your own order number in meta. It answers { id, createdAt } (select it with ... on OrderConfirmation, not ... on Order) before the order is stored, so a call right behind it can get OrderNotFoundError. Before using it, read what it does to an order a storefront lists, in shop-api-order-mutations.md.


Media & Images

Importing images and video (copyRemoteAsset, presigned uploads, registerImage, registerImageRevision, updateImage, showcases, deleteImage) and getting them indexed has its own skill: see [[media]].


Pipelines

Pipelines and stages are created in the legacy PIM API (below); orders are moved between them on the Shop API (addToStage) when a storefront reads the orders.

  • moveStage fails and deletes the stage it was moving. Stages can’t be reordered: to change the order, delete and recreate the (empty) pipeline.
  • placeNewOrders: true on a stage pulls every new order into that pipeline. With it on the first stage of three pipelines, every order landed in all three. For typed pipelines (orders, rentals, quotes), leave it off and place each order explicitly.
  • Read pipeline and stage ids with PIM pipeline.getMany at build time and write them into the storefront’s data; edges is null on a tenant with no pipelines.

Webhooks

A storefront revalidates its Discovery cache on publish through a Core webhook. No other skill covers them.

mutation Hook($input: CreateWebhookInput!) {
createWebhook(input: $input) {
__typename
... on Webhook {
id
}
... on BasicError {
errorName
message
}
}
}
{
"input": {
"name": "Revalidate storefront",
"concern": "items",
"event": "publish",
"method": "POST",
"url": "https://shop.example.com/api/revalidate",
"headers": [{ "name": "x-secret", "value": "…" }],
"graphqlQuery": "query ($id: ID!, $language: String!) { item(id: $id, language: $language) { ... on Item { tree { path } } } }",
"graphqlQueryTarget": "next",
"preserveDefaultPayload": true
}
}
  • concern and event are plain strings and are not validated. The concern that fires for item publishes is items (plural): item and product are accepted and never fire, and so is nope. Check what fires with the webhookInvocations query.
  • Register one webhook per event: publish and unpublish (two builds did this, and both fired).
  • The default payload has no path. Add a graphqlQuery (graphqlQueryTarget is current or next) with preserveDefaultPayload: true when the receiver needs the path or the language.
  • The receiver is a server route that verifies the request and clears the storefront’s Discovery cache tag. Expect Discovery to lag the webhook by seconds (Discovery Indexing). Crystallize does not retry a failed delivery by itself; retryWebhookInvocation(id:) re-sends one.
  • Set webhooks up once per tenant, in a setup script, not from the storefront.

List quirks

  • first is capped at 100 and asking for more returns 100 without a warning; shapes(first:) and pieces(first:) above 100 fail instead. Paginate.
  • items(filter: { itemIds }) ignored the filter and returned the first 100 items by name: read item(id:) per item.
  • items(filter: { shapeIdentifiers: [...] }) (plural) returned unrelated items with a correct totalCount; the singular shapeIdentifier works and paginates. Query once per shape.
  • The orders sort is { field: createdAt, direction: desc }, not { createdAt: desc }.

Flow Mutations

Flows model item workflows (e.g. Draft > Review > Published). Items are added to a stage and removed from it; there is no setFlowStage on Core.

mutation AddToStage($items: [ItemFlowStageAssociationInput!]!) {
addItemsToFlowStage(stageIdentifier: "review", items: $items) {
__typename
... on FlowContentList {
content {
id
}
}
... on BasicError {
errorName
message
}
}
}
{ "items": [{ "id": "<item id>", "language": "en", "version": "draft" }] }

An item is named by { id, language, version }, where version is current, draft or published. moveFromFlowIdentifier moves items out of another flow in the same call, and deleteItemsFromFlowStage(stageIdentifier:, items:) takes them out again. Stage and flow identifiers are the ones you gave createFlow / createFlowStage.


Vector Ranking Mutations

Discovery’s vector ranking is authored entirely on the Core API. Four calls, in this order:

Mutation Notes
upsertVocabulary(input: UpsertVocabularyInput!) Full replace, not a patch — omitted dimensions are dropped
setItemTaste(input: SetItemTasteInput!) One item, one language, one vocabulary. Writes the draft
publishItem(id: ID!, language: String!) The indexer reads the published version — skipping this fails silently. See the note on publishing below
igniteDiscoApi(stacks: opensearch) Async; poll bulkTask(id:) until complete, then allow propagation. stacks: opensearch is required for vectors to be built
mutation UpsertVocabulary($input: UpsertVocabularyInput!) {
upsertVocabulary(input: $input) {
name
dimensions {
id
weight
}
lastUpdated
}
}
mutation SetItemTaste($input: SetItemTasteInput!) {
setItemTaste(input: $input) {
__typename
... on Product {
id
}
... on BasicError {
errorName
message
}
}
}
mutation Index {
igniteDiscoApi(stacks: opensearch) {
__typename
... on BulkTaskIgnition {
id
type
status
createdAt
}
... on BasicError {
errorName
message
}
}
}

setItemTaste and igniteDiscoApi return unions whose error members implement BasicError, so a single fragment covers every failure and errorName identifies it. upsertVocabulary returns the Vocabulary directly and fails as a GraphQL error.

Read back with vocabulary(name:) and item(id:, language:) { ... on Item { taste { vocabulary entries { key weight } } } }.

publishItem and publishItems both run in the background, so neither return is proof that the items are published yet — index right after them and the index may read the old versions. Wait for item(id:, language:, versionLabel: published) to show the new content first.

Run igniteDiscoApi the first time, and again after every upsertVocabulary — an unindexed vocabulary change has no effect and raises no error. A taste change needs no ignition on a tenant already served for ranking: publishing the item re-indexes it. Run it last, once shapes and published content exist. A task that ends in error is blocking: bulkTask(id:) { ... on BulkTask { status info } } carries the reason in info.traces. Probe Discovery with { __typename } before reporting success. On a tenant not yet served for ranking, omitting stacks: opensearch fails silently: the index rebuilds, but without vectors. On a tenant already served for ranking, the task ends in error. Full guidance, including vocabulary design, positional weights and key validation, is in the [[vector-ranking]] skill.

Only in the legacy PIM API

Some tenant configuration has no Core equivalent at all — it is neither readable nor writable there. For these, use https://pim.crystallize.com/graphql, which is namespaced (subscriptionPlan { create(...) }) and takes the tenant id as an argument rather than @tenant in the URL:

Concept Why you need it
Subscription plans, periods, meters The template a subscription contract points at — see [[subscriptions]]
Order pipelines and their stages Creating them; Core can move an order between existing stages
Stock locations modifyProductVariantStock needs one to exist
VAT types createProduct requires a vatTypeId
Markets Targeting price lists at a market — see [[pricing]]
Tenant preferences (setPreferences) Registering a custom admin view through input: { frontends }

Price variants are not in this list: createPriceVariant, updatePriceVariant, deletePriceVariant and the priceVariant / priceVariants queries are all on Core.

Anything created in the PIM API is read back through its own generated ids — plan period ids in particular — so capture them when you create them rather than re-deriving them later.

Error Handling

The Core API uses union return types. Always handle potential errors:

mutation UpdateComponent($itemId: ID!, $language: String!, $component: ComponentInput!) {
updateComponent(itemId: $itemId, language: $language, component: $component, disableContentValidation: false) {
__typename
... on UpdatedComponent {
updatedComponentPath
}
... on ComponentContentValidationFailedError {
errors {
componentId
message
}
}
... on BasicError {
errorName
message
}
}
}

A specific member first, then BasicError as the catch-all, is the pattern to copy: errorName tells you which one you actually got.

Common error types:

Error Cause
UnauthorizedError Missing or insufficient access token permissions
UnknownError Unclassified failure
ExperimentalFeaturesNotAvailableError The feature is not enabled for this tenant
ItemNotFoundError Item ID doesn’t exist
ItemDoesNotBelongToTenantError Item ID belongs to a different tenant
ComponentContentValidationFailedError Content does not match the shape; carries per-component errors
ProductVariantNotFoundError No variant with that SKU
OrderNotFoundError Order ID doesn’t exist

Images, video and media

Media has its own skill now: see [[media]].

Rendering images (srcset, sizes, formats) is [[responsive-images]].

Shop API Cart Mutations Reference

The Shop API /cart scope provides edge-distributed mutations for cart management and checkout flows.

See SKILL.md for endpoint URLs and authentication headers. This file covers the /cart endpoint only. For order creation and management, use the /order endpoint.

Cart State Machine

Carts follow a state machine that controls what operations are allowed:

cart → placed → ordered
↕ ↗
abandoned
State Description Mutable?
cart Active cart, items and prices can be changed Yes
placed Locked for payment — no modifications allowed No
ordered Linked to an order via orderId No
abandoned Explicitly abandoned, or left to go stale Yes: a write revives it

abandon works only from cart, so a placed cart cannot be abandoned: its only way forward is ordered. An abandoned cart goes back to cart on the next hydrate or write, and can be placed directly.

A write on a placed or ordered cart can look like it worked. hydrate refuses a placed cart and serves an ordered one read-only, but addSkuItem, setCustomer, setMeta and the other item mutations answer with the changed cart while nothing is stored. Check state before you write.

Query the cart state with:

query {
cart(id: "cart-id") {
id
state # cart | placed | ordered | abandoned
isStale # true once staleAt has passed: no write for context.staleTtl
isExpired # true once expiresAt has passed: no write for context.ttl
orderId # set when an order is created from the cart
}
}

Stale is about time, not prices. Every write pushes staleAt forward by context.staleTtl (1 hour by default), and a stale cart turns abandoned within about five minutes. Wishlists never go stale or expire.

Cart Hydration

The primary mutation for creating and updating carts. Hydration:

  1. Takes SKUs and external items as input
  2. Fetches product data from Catalogue API
  3. Calculates prices, taxes, and totals
  4. Returns a fully constructed cart

Hydrating an existing id replaces the cart, it does not merge. items, externalItems, customer, meta and context are all taken from this input, so anything you leave out is dropped, the customer and the price context included. Resend the whole cart, or use the targeted mutations below. An id that does not exist creates a new cart with a new id.

A SKU the catalogue does not return is dropped with no error: an unknown SKU, an unpublished product, or a language it is not published in. Compare the items you get back with the ones you sent.

Basic Hydration

mutation {
hydrate(
input: { items: [{ sku: "robot-pink-standard", quantity: 1 }, { sku: "robot-red-standard", quantity: 3 }] }
) {
id
state
isStale
isExpired
items {
name
quantity
variant {
sku
}
price {
gross
net
}
}
total {
gross
net
}
}
}

Hydration with Customer and Context

The hydrate input accepts customer info inline — this is the recommended way to associate a customer during checkout. isGuest is required on CustomerInput. It also accepts item type and group for categorizing line items.

mutation {
hydrate(
input: {
customer: { identifier: "john@example.com", isGuest: false, firstName: "John", lastName: "Doe" }
context: {
language: "en"
price: {
pricesHaveTaxesIncludedInCrystallize: true
decimals: 4
currency: "EUR"
selectedVariantIdentifier: "sales"
compareAtVariantIdentifier: "default"
fallbackVariantIdentifiers: ["default"]
}
}
items: [
{ sku: "palissade-lounge-sofa-iron-red", quantity: 1, type: standard, group: "Outdoor" }
{ sku: "palissade-bar-stool-sky-grey", quantity: 1, type: standard, group: "Outdoor" }
{ sku: "monstera-deliciosa-medium", quantity: 2, type: standard, group: "Plants" }
]
}
) {
id
state
isStale
customer {
identifier
firstName
lastName
}
appliedPromotions {
identifier
name
mechanism {
type
value
}
}
items {
name
variant {
sku
price {
gross
net
taxAmount
taxPercent
}
compareAtPrice {
gross
net
}
}
price {
net
gross
taxAmount
discounts {
percent
amount
}
}
}
total {
net
gross
discounts {
percent
amount
}
}
}
}

CartInput Fields

Field Type Description
id UUID Existing cart ID (omit to create new cart)
items [CartSkuItemInput] SKU items to add to the cart
externalItems [CartItemInputType] External items (shipping, fees)
customer CustomerInput Customer info (inline with hydration)
context ContextInput Language and pricing context
type CartType cart or wishlist
name String Optional cart name (mainly for wishlists)
meta [KeyValueInput] Arbitrary key-value metadata

CartSkuItemInput Fields

Field Type Required Description
sku String! Yes Product variant SKU
quantity PositiveInt No Quantity (default: 1)
lineId String No Selects an existing line, needed only when several lines share a SKU. Read it from items { lineId }
type CartItemType No standard, subscription, shipping, fee, promotion, refund, service, digital, bonus, tax
group String No Free-form group label (e.g., “Outdoor”, “Plants”)
taxRate Rate No Override tax rate for this item
meta [KeyValueInput] No Item-level metadata

Context Options

context holds language, ttl, staleTtl and a nested price object:

Field Description
language Locale for product names (default: “en”)
ttl Seconds until the cart expires, reset by each write (default: 30 days)
staleTtl Seconds without a write before the cart goes stale (default: 1 hour)
price.selectedVariantIdentifier Price variant to use as active price (default: default)
price.compareAtVariantIdentifier Price variant for discount comparison
price.fallbackVariantIdentifiers Tried in order when the selected variant has no price. If none has one, the SKU’s first price variant is used, so a wrong identifier prices the line instead of failing
price.decimals Decimal precision (default: 0, recommended: 4)
price.pricesHaveTaxesIncludedInCrystallize Default false. Tax handling: true for B2C, false for B2B
price.discountOnNetPrices Apply discounts on the net price (default: false)
price.taxRate Override tax rate, between 0 and 1
price.markets Array of markets for price lists
price.currency Label stamped on the prices (default: eur). It converts nothing and nothing checks it against the price variant, so pass that variant’s currency
price.customerGroups Customer groups for pricing (customerGroup is deprecated)
price.voucherCodes Apply voucher codes (voucherCode is deprecated)

Hydration with External Items

For items not in Crystallize (shipping, fees):

mutation {
hydrate(
input: {
items: [{ sku: "product-sku", quantity: 1 }]
externalItems: [
{
sku: "shipping-fedex"
quantity: 1
name: "FedEx Ground Shipping"
images: []
variant: {
price: { gross: 12.99, net: 10.39 }
product: { id: "shipping-product", path: "/shipping" }
}
}
]
}
) {
id
items {
name
variant {
sku
}
}
}
}

Cart Item Management

Add SKU Item

Add a single SKU item to an existing cart. If the SKU is already in the cart, quantity is added to that line. It does not take a booking: use bookSkuItem, see [[bookable-resources]].

mutation {
addSkuItem(id: "cart-id", input: { sku: "new-product-sku", quantity: 2, type: standard, group: "Furniture" }) {
id
items {
name
variant {
sku
}
quantity
}
}
}

Add External Item

Add a fully custom item not in Crystallize (e.g., shipping, service fees). name and variant are required, and variant.price is the unit price. If the SKU is already an external line, quantity is added to it.

mutation {
addExternalItem(
id: "cart-id"
input: {
sku: "shipping-standard"
name: "Standard Shipping"
quantity: 1
type: shipping
variant: { price: { gross: 9.99, net: 7.99 }, product: { id: "shipping-product", path: "/shipping" } }
}
) {
id
items {
name
variant {
sku
}
price {
gross
net
}
}
}
}

Remove Items

quantity defaults to 1, so leaving it out takes one unit off the line. The line goes when it reaches 0: pass its full quantity to remove it.

mutation {
removeCartItem(id: "cart-id", sku: "product-to-remove", quantity: 3) {
id
items {
variant {
sku
}
quantity
}
}
}

Update Item Quantity

addCartItem adds to a line already in the cart and removeCartItem takes from it, both by a delta. A SKU that is not in the cart is ignored: use addSkuItem for that.

mutation {
addCartItem(id: "cart-id", sku: "product-sku", quantity: 2) {
id
items {
quantity
variant {
sku
}
}
}
}

Change Item Pricing

Override managed pricing (makes item unmanaged). price is the unit price, and input also takes quantity, which is how to set an absolute quantity. A SKU that is not in the cart is ignored.

mutation {
changeCartItemPricing(id: "cart-id", input: { sku: "product-sku", price: { gross: 49.99, net: 39.99 } }) {
id
items {
context # HashMap: managed, origin, taxRate
variant {
sku
}
price {
gross
net
}
}
}
}

An unmanaged line keeps its price through later hydrations, only its quantity moves.

setCartItem(id:, input:) is the full form: it takes the same CartItemInput as addExternalItem, so name and variant are required, then adds or replaces the line and flags it unmanaged.

Customer Information

Set Customer on Cart

The argument is input here, and customer on the /order endpoint’s setCustomer. isGuest is required, and the customer you send replaces the one on the cart.

mutation {
setCustomer(
id: "cart-id"
input: { isGuest: false, firstName: "John", lastName: "Doe", email: "john@example.com", phone: "+1234567890" }
) {
id
customer {
firstName
lastName
email
}
}
}

Set Addresses

Addresses live on the customer, so they go in customer.addresses with a type of billing, delivery or other:

mutation {
setCustomer(
id: "cart-id"
input: {
isGuest: false
firstName: "John"
addresses: [
{ type: billing, street: "123 Main St", city: "New York", postalCode: "10001", country: "US" }
{ type: delivery, street: "456 Oak Ave", city: "Brooklyn", postalCode: "11201", country: "US" }
]
}
) {
id
}
}

Set Cart Metadata

merge defaults to true, and false replaces all the meta.

mutation {
setMeta(id: "cart-id", meta: [{ key: "campaign", value: "summer" }], merge: true) {
id
meta
}
}

Cart to Order Intent

createFromCart is the normal way to get an order from a cart. Use orderIntent, a query on /cart, when you create the order yourself: it works on a placed cart only, and you close the cart with fulfill afterwards.

query {
orderIntent(id: "cart-id", format: shop) {
order # HashMap: the order input
cart {
id
state
}
}
}

format is legacy (the default), core, coreWithOrderV2 or shop. Use shop for the /order create mutation.

Cart Lifecycle

Place Cart

Placing a cart locks it and makes it immutable. This should happen when the user enters checkout (e.g., before collecting payment). After placing, items, quantities, and prices cannot be changed. place hydrates the cart one last time first, so charge the total it returns, not the one you showed earlier.

mutation {
place(id: "cart-id") {
id
state # now "placed"
items {
name
quantity
}
total {
gross
net
currency
}
}
}

Back navigation: If the user navigates back after the cart is placed, create a new cart by calling hydrate without an id. The placed cart cannot be modified.

Fulfill Cart

Not needed after createFromCart. createFromCart on the /order endpoint already moves the cart to ordered and sets orderId, and the order id is the cart id. Use fulfill to link a placed cart to an order created some other way:

mutation {
fulfill(id: "cart-id", orderId: "order-uuid") {
id
state # now "ordered"
orderId # the linked order ID
}
}

Abandon Cart

Explicitly mark a cart as abandoned (e.g., user left checkout, session timeout). This fails on a placed or ordered cart.

mutation {
abandon(id: "cart-id") {
id
state # now "abandoned"
}
}

Mark as Wishlist

Convert a cart in state cart to a non-expiring wishlist:

mutation {
markAsWishlist(id: "cart-id", name: "My Favorites") {
id
isWishlist
name
}
}

Set Cart Expiration

There is no expiration mutation. Pass context.ttl and context.staleTtl, in seconds, to hydrate.

Remove Cart

remove returns a Boolean, so it takes no selection:

mutation {
remove(id: "cart-id")
}

Complete Checkout Flow

The full checkout flow spans the /cart and /order endpoints (and /customer when you keep customer records), all called from your server. No step uses the Core API:

0. (Optional) Create Customer → POST /customer — customer(input:)
1. Hydrate Cart → POST /cart — Create cart with items, customer, context
2. (Optional edits) → POST /cart — addSkuItem, setCustomer, etc.
3. Place Cart → POST /cart — Lock cart for payment
4. Create Order → POST /order — createFromCart (⚠ different endpoint!)

After step 4 the cart is ordered and linked to the order; the order id is the cart id. There is no separate fulfill step.

Customer Creation

Customers can be created before checkout, on the Shop API or the Core API, or inline during hydration:

  • Shop API /customer (from a storefront): customer(input: { identifier, ... }) creates or updates the customer, and addAddress, setAddress, removeAddress and setMeta edit it. The token needs the customer scope.
  • Core API (from a back office or a seed, never from the storefront’s request path): createCustomer with type: individual or type: organization, and parents for a company hierarchy. The customer’s identifier (typically email) can then be passed to hydrate.
  • B2B, ordering on behalf of a company: put the organisation’s identifier on the cart customer, so the order belongs to the company and orders(customerIdentifier: "<company>") lists it, and put the person who ordered in cart meta (orderedBy). The Shop API has no “orders of a parent” query.
  • Inline during hydrate (recommended for checkout): Pass customer: { identifier, firstName, lastName, isGuest } directly in the hydrate input. This associates the customer with the cart without requiring a separate API call.

For guest checkout, set isGuest: true in the hydrate customer input.

Minimal checkout example:

# Step 1: Create and hydrate cart (POST /cart)
mutation {
hydrate(
input: {
customer: { identifier: "john@example.com", isGuest: false }
context: {
language: "en"
price: {
pricesHaveTaxesIncludedInCrystallize: true
decimals: 4
currency: "EUR"
selectedVariantIdentifier: "default"
}
}
items: [
{ sku: "product-sku-1", quantity: 2, type: standard }
{ sku: "product-sku-2", quantity: 1, type: standard }
]
}
) {
id
state
total {
gross
net
currency
}
}
}
# Step 2: Place cart — locks it for payment (POST /cart)
mutation {
place(id: "cart-uuid-from-step-1") {
id
state # "placed"
}
}
# Step 3: Create order from placed cart (POST /order — DIFFERENT ENDPOINT!)
mutation {
createFromCart(id: "cart-uuid-from-step-1", input: { type: standard, paymentStatus: paid }) {
id
coreId
type
total {
gross
net
currency
}
}
}

Best Practices

  1. Reuse cart IDs — Pass returned ID to subsequent requests
  2. Set customer and context in hydrate — Set them inline during hydration rather than separate calls
  3. Place before payment — Always place the cart before initiating payment to prevent modifications
  4. Use /order for order creation — createFromCart is on the /order endpoint, not /cart
  5. Handle back navigation — If user goes back after placing, create a new cart via hydrate without an id
  6. Use item groups — Group items logically (“Outdoor”, “Plants”) for organized order views
  7. Handle managed state — Know when items become unmanaged after price overrides
  8. External items for non-catalog items — Shipping, fees, discounts via addExternalItem
  9. Auto-cleanup — Carts expire 30 days after the last write by default (context.ttl) and are deleted three months after that
  10. Don’t write in parallel — Most cart writes land just after the response, and on the same cart the last one wins. Wait for each answer and work from the cart it returns

Shop API Order Mutations Reference

The Shop API /order scope provides mutations for creating and managing orders. This is a separate endpoint from the /cart scope.

See SKILL.md for endpoint URLs and authentication headers. This file covers the /order endpoint. Order mutations use /order, NOT /cart — the createFromCart mutation and all order management mutations must be sent to this endpoint.

Create Order from Cart

Convert a placed cart into an order. The cart must be in “placed” state first (via place mutation on the /cart endpoint). Any other state fails, so a second call on the same cart fails too: the first one left it ordered.

The order is saved just after the answer. An addPayments, addToStage or setMeta sent right behind createFromCart can fail with “Order … not found”, and an immediate order(id:) read can too. Pass paymentStatus, payments and pipelines in this input instead of chaining calls, and show the confirmation page from the order this mutation returns.

Run it on your server, normally in the payment provider’s webhook after verifying the payment ([[payments]]). After place the cart is locked, so if this call fails the shopper needs a new cart.

  • Cart meta becomes order meta. OrderFromCartInput has no meta: set it on the cart (hydrate(input: { meta }) or setMeta) before place. The order gets the cart’s meta plus cartId, cartState and cartType, and keeps customer.meta.
  • The order belongs to the cart’s customer. For B2B, put the organisation’s identifier on the cart so orders(customerIdentifier: "<company>") lists the company’s orders, and the ordering person in meta.
  • additionalInformation: null is refused (“Output validation error”): leave the field out.
  • coreId is null in the answer; the Core copy arrived within about 20 s with the meta and the stage.
  • appliedPromotions and reference came back null in the answer even when the cart had a promotion.
mutation CreateOrderFromCart($id: UUID!, $input: OrderFromCartInput) {
createFromCart(id: $id, input: $input) {
id
coreId
type
paymentStatus
total {
gross
net
taxAmount
currency
}
items {
name
sku
quantity
price {
gross
net
}
}
customer {
firstName
lastName
email
}
createdAt
}
}

Variables:

{
"id": "cart-uuid-here",
"input": {
"type": "standard",
"paymentStatus": "paid"
}
}

OrderFromCartInput

Field Type Description
type OrderType enum Order type. No default: pass standard
paymentStatus OrderPaymentStatus Payment status. Set here or never, see below
payments [OrderPaymentInput] Payment records
pipelines [OrderPipelineInput] Pipeline stage assignments
stockLocationIdentifier String Stock location for inventory
relatedOrderIds [String] Related Core order ids (coreId)
additionalInformation String Free-text additional info

Create Order Directly

Create an order without a cart: a POS sale, an accepted quote, a manual order, or a demo seed. Use this, not Core registerOrder, whenever a storefront or the Shop API lists the order; registerOrder is for imports nobody reads from the edge (see The Order Store and Core).

  • relatedOrderIds takes Core ids (coreId): an order made from an accepted quote points back at the quote.
  • createdAt was observed both ways: honoured on one tenant, ignored (“now”) on another. For back-dated seeds, keep the intended date in meta (orderedAt) as well and read it from there.
  • Seeds: create orders one at a time or at low concurrency, then check by id. The per-customer listing lags and can stay incomplete (47 created, 29 listed), so never use it to decide what still needs creating; key on a meta seedRef and keep a ledger.
mutation CreateOrder($input: OrderInput!) {
create(input: $input) {
id
coreId
type
paymentStatus
total {
gross
net
taxAmount
currency
}
items {
name
sku
quantity
price {
gross
net
}
}
createdAt
}
}

Variables:

{
"input": {
"customer": {
"isGuest": false,
"firstName": "John",
"lastName": "Doe",
"email": "john@example.com",
"identifier": "john@example.com",
"addresses": [
{
"type": "billing",
"street": "123 Main St",
"city": "New York",
"postalCode": "10001",
"country": "US"
},
{
"type": "delivery",
"street": "456 Oak Ave",
"city": "Brooklyn",
"postalCode": "11201",
"country": "US"
}
]
},
"items": [
{
"name": "Robot Action Figure",
"sku": "robot-pink-standard",
"quantity": 2,
"productId": "product-id",
"imageUrl": "https://example.com/robot.jpg",
"price": {
"gross": 49.99,
"net": 39.99
}
}
],
"type": "standard",
"paymentStatus": "paid",
"payments": [
{
"provider": "stripe",
"transactionId": "pi_abc123",
"amount": 99.98,
"method": "card",
"createdAt": "2025-01-15T10:30:00Z"
}
],
"meta": [
{ "key": "source", "value": "web" },
{ "key": "campaign", "value": "summer-sale" }
]
}
}

OrderInput

Field Type Required Description
items [OrderItemInput] No Order line items
customer CustomerInput No Customer information
context OrderContextInput No { language, price: { currency, decimals, discountOnNetPrices } }. currency defaults to eur, so set it
type OrderType No Order type. No default: pass standard
paymentStatus OrderPaymentStatus No Payment status. Set here or never, see below
payments [OrderPaymentInput] No Payment records
pipelines [OrderPipelineInput] No Pipeline stage assignments
stockLocationIdentifier String No Stock location for inventory deduction
relatedOrderIds [String] No Related Core order ids (coreId), for returns and replacements. A Shop id fails the sync to Core
additionalInformation String No Free-text additional info
meta [KeyValueInput] No Arbitrary key-value metadata
createdAt DateTime No Override creation timestamp. Ignored on some tenants: keep the date in meta too

OrderItemInput

Field Type Required Description
name String! Yes Item display name
sku String! Yes Item SKU
quantity PositiveInt! Yes Quantity ordered
price PriceInput! Yes Unit price (gross + net)
productId String No Crystallize product ID
imageUrl String No Item image URL
group String No Free-form group label
type CartItemType No Line type, see the enum below
promotions [Float] No Discount amounts on item total
subscriptionContractId String No Subscription contract ID
subscription OrderItemSubscriptionInput No Subscription details
meta [KeyValueInput] No Item-level metadata

PriceInput

Field Type Required Description
gross Float! Yes Price including tax
net Float! Yes Price excluding tax
discounts [DiscountInput] No Applied discounts

CustomerInput

Field Type Required Description
isGuest Boolean! Yes Whether customer is guest
identifier String No Unique customer ID
firstName String No First name
lastName String No Last name
middleName String No Middle name
email String No Email address
phone String No Phone number
birthDate DateTime No Date of birth
companyName String No Company name
taxNumber String No Tax/VAT number
type CustomerType No individual (default) or organization
externalReferences [KeyValueInput] No External system references
addresses [AddressInput] No Customer addresses
meta [KeyValueInput] No Customer metadata

AddressInput

Field Type Required Description
type AddressType No delivery, billing, or other
firstName String No First name
middleName String No Middle name
lastName String No Last name
street String No Street address
street2 String No Additional street info
streetNumber String No Street number
postalCode String No Postal/ZIP code
city String No City
state String No State/province
country String No Country code
phone String No Phone number
email String No Email address
meta [KeyValueInput] No Address metadata

OrderPaymentInput

Field Type Required Description
provider String No Payment provider name
transactionId String No Transaction reference
amount Float No Payment amount
method String No Payment method
createdAt DateTime No Payment timestamp
meta [KeyValueInput] No Payment metadata

OrderPipelineInput

Field Type Required Description
identifier String! Yes The pipeline id, not its name
stage String Yes The stage id. The schema allows null, validation does not

These are ids, see Pipeline Management. When pipelines is left out, the Core order lands in the pipelines the tenant set up for new orders.

Add Payments to Order

Add payment records to an existing order.

mutation AddPayments($id: UUID!, $payments: [OrderPaymentInput!]!) {
addPayments(id: $id, payments: $payments) {
id
paymentStatus
payments {
provider
transactionId
amount
method
createdAt
}
}
}

Variables:

{
"id": "order-uuid",
"payments": [
{
"provider": "stripe",
"transactionId": "pi_xyz789",
"amount": 99.98,
"method": "card",
"createdAt": "2025-01-15T10:30:00Z"
}
]
}

Replace All Payments

Replace all payment records on an order.

Neither mutation changes paymentStatus, and the /order endpoint has no mutation for it: it is set once, by create or createFromCart. See [[payments]] for tracking captures and refunds afterwards.

mutation SetPayments($id: UUID!, $payments: [OrderPaymentInput!]!) {
setPayments(id: $id, payments: $payments) {
id
paymentStatus
payments {
provider
transactionId
amount
}
}
}

Set Order Metadata

Set or merge metadata on an order.

mutation SetOrderMeta($id: UUID, $meta: [KeyValueInput], $merge: Boolean) {
setMeta(id: $id, meta: $meta, merge: $merge) {
id
meta
}
}

Variables:

{
"id": "order-uuid",
"meta": [
{ "key": "fulfillment_status", "value": "shipped" },
{ "key": "tracking_number", "value": "1Z999AA10123456784" }
],
"merge": true
}

When merge is true (default), new keys are added and existing keys are updated. When false, all existing metadata is replaced.

Set Order Customer

Update the customer information on an existing order. It replaces the customer, and isGuest is required.

mutation SetOrderCustomer($id: UUID!, $customer: CustomerInput!) {
setCustomer(id: $id, customer: $customer) {
id
customer {
firstName
lastName
email
identifier
}
}
}

Create Order from Subscription Contract

createFromSubscriptionContract is in the schema but not implemented: every call errors. Read the orderIntent query on the /subscription-contract endpoint and pass the result to create. See [[subscriptions]].

Pipeline Management

pipeline and stage take the pipeline id and the stage id, not their names, here and in pipelines on create and createFromCart. Read them from the PIM API (pipeline { getMany(tenantId:) { edges { node { id name stages { id name } } } } }). The Shop API does not check them: the mutation succeeds and stores what you sent, and a name there stops the order from syncing to Core.

Add Order to Pipeline Stage

Put an order in a pipeline stage. An order holds one stage per pipeline, so calling this again on the same pipeline moves it, and its other pipelines are untouched.

mutation AddToStage($id: UUID!, $pipeline: String!, $stage: String!) {
addToStage(id: $id, pipeline: $pipeline, stage: $stage) {
id
pipelines {
identifier
stage
}
}
}

Variables:

{
"id": "order-uuid",
"pipeline": "<pipeline id>",
"stage": "<stage id>"
}

Remove Order from Pipeline

mutation RemoveFromPipeline($id: UUID!, $pipeline: String!) {
removeFromPipeline(id: $id, pipeline: $pipeline) {
id
pipelines {
identifier
stage
}
}
}

Enums

OrderType

Value Description
standard Regular order
draft Draft order (not finalized)
creditNote Credit note / refund
replacement Replacement order
backorder Backorder (out-of-stock fulfillment)
preOrder Pre-order
quote Price quote
recurring Recurring/subscription order
split Split order (partial shipment)
test Test order

OrderPaymentStatus

Value Description
paid Fully paid
partiallyPaid Partially paid
partiallyRefunded Partially refunded
refunded Fully refunded
unpaid Not yet paid

CustomerType

Value Description
individual Individual person
organization Company/org

AddressType

Value Description
delivery Shipping address
billing Billing address
other Other address

CartItemType (on Order items)

Value Description
standard Regular product item
subscription Subscription item
shipping Shipping fee
fee Additional fee
promotion Promotional item
refund Refund line
service Service item
digital Digital product
bonus Bonus/gift item
tax Tax line item

Order Response Type

The Order type returned by all mutations:

Field Type Description
id UUID! Shop API order ID
coreId String Core API order ID
reference String Order reference
type OrderType Order type enum
additionalInformation String Additional info text
stockLocationIdentifier String Stock location
relatedOrderIds [String] Related order IDs
createdAt DateTime Creation timestamp
updatedAt DateTime Last update timestamp
context HashMap Order context (pricing, language)
customer Customer Customer details with addresses
items [Item] Order line items
total TotalPrice! Order totals (gross, net, tax, currency)
paymentStatus OrderPaymentStatus Payment status
payments [Payment] Payment records
pipelines [Pipeline] Pipeline stage assignments
appliedPromotions [PromotionSlim!] Applied promotions
meta HashMap All metadata as key-value map
metaProperty String Single metadata property by key

Complete Checkout Flow (Cart → Order)

The full checkout flow spans both /cart and /order endpoints:

1. Hydrate Cart → POST /cart (hydrate mutation)
2. Set Customer → POST /cart (setCustomer mutation)
3. Place Cart → POST /cart (place mutation)
4. Create Order → POST /order (createFromCart mutation)
# Step 1: Hydrate cart (on /cart endpoint)
mutation {
hydrate(input: { items: [{ sku: "product-sku", quantity: 1 }] }) {
id
}
}
# Step 2: Set customer info (on /cart endpoint)
mutation {
setCustomer(
id: "cart-id"
input: { isGuest: false, firstName: "John", lastName: "Doe", email: "john@example.com" }
) {
id
}
}
# Step 3: Place the cart (on /cart endpoint)
mutation {
place(id: "cart-id") {
id
}
}
# Step 4: Create order from cart (on /order endpoint — DIFFERENT ENDPOINT!)
mutation {
createFromCart(id: "cart-id", input: { type: standard, paymentStatus: paid }) {
id
coreId
total {
gross
net
currency
}
}
}

createFromCart also moves the cart to ordered and sets its orderId. The order id is the cart id, so there is nothing left to link: do not follow it with fulfill.

The Order Store and Core

Shop API orders and Core orders are meant to be one order in two stores, synced asynchronously in both directions. The two entries do different jobs:

  • Shop /order is the entry for volume. It is asynchronous: it puts orders on a FIFO queue and writes them to the database after it answers, and it is built to take millions of orders. An answer means accepted, not stored, so read the order back by id, with a retry.
  • Core is synchronous but rate limited. Use it for imports and back-office edits, not for storefront orders.

Where an order was born decides what a Core write does to it today.

Shop → Core. An order created here gets its coreId in about ten seconds, and addToStage moves the Core stage with it. (coreId can still read null in the answer of a Shop create even after the order has reached Core, so don’t use it as a sync flag.)

Born in Core updateOrder Core deleteOrder
Shop API (create, createFromCart) Rewrites the same Shop order with Core’s whole version Removes it from the Shop store
Core (registerOrder) Adds another copy to the Shop store (a sync bug) Removes only the latest copy

A stage moved in Core or the App does not reach the Shop store, and the next Shop write puts it back. Every /order mutation sends the whole Shop order to Core, and Core makes the order’s pipelines match it: a stage that differs is moved back, a pipeline that is missing is removed. Before a Shop write to an order whose stage may have moved, read the stages from Core and copy them over with addToStage. [[payments]] has a helper.

Seed demo orders with the Shop API, not with registerOrder, if a storefront is going to list them: orders registered in Core showed up in the Shop store only sometimes.

Editing an order born in Core adds another copy of it to the Shop store. This is a sync bug, reported to the platform team: Core and Shop /order should work on one order. Until it is fixed, plan for it. Such an order has no Shop id to come back to, so every change arrives as a new order. Three updateOrder calls on one seeded order left three orders in orders(customerIdentifier:) — new Shop ids, the same coreId, different updatedAt — and on a sandbox tenant (2026-11-17) one registerOrder plus three updateOrder calls left four. A storefront that sums that list counts the same money several times over; the Lab Universe build read a department budget of NOK 1,249,299 instead of 411,775. So:

  • Change orders through the Shop API (setMeta, addToStage, setPayments) whenever a storefront reads them. On an order born here, a Core edit also overwrites whatever the Shop wrote just before it.
  • If an order born in Core must be edited there anyway, have the reader group by coreId and keep the most recently updated copy. This is a workaround for the bug, not how the stores are meant to work.

There is no delete on the Shop API. Cancelled or mistaken orders stay in the list until deleteOrder on the Core order removes them. Otherwise archive them with setMeta (archived: true) and filter them out when reading.

(Both findings come from the Tools Universe and Lab Universe builds.)

Best Practices

  1. Use the correct endpoint — Cart operations on /cart, order operations on /order
  2. Include order scope in JWT — Token must have order scope for /order endpoint: "scopes": ["cart", "order"] when you request it
  3. Place cart before creating order — createFromCart requires the cart to be in “placed” state
  4. Always check for errors — Validate result?.errors in responses
  5. Use meta for custom data — Store fulfillment status, tracking numbers, external references
  6. Use pipelines for workflow — Track orders through fulfillment stages
  7. Use coreId — When you need to reference the order in Core API mutations
  8. Write in one store — If a storefront reads the orders, create and change them here, not in Core
  9. Resolve pipeline names up front — Orders carry pipeline and stage ids only; map them to names at build or seed time from the admin APIs


Crystallize AI