Skip to content

query

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

Crystallize Query Skill

Read product data, content and commerce data from Crystallize. This skill covers how each read API behaves. Which API a storefront calls for each task, and in what order, is the storefront API contract below, in full in [[storefront]].

Consultation Approach

Before writing queries, ask:

  1. Is this a storefront (or any shopper-facing code) or the back office? It decides the API: see the contract.
  2. Is the data about the catalogue or about a shopper? Catalogue → Discovery. Cart, the price this customer pays, orders, customers, bookings, subscriptions → Shop API.
  3. Does the read run in the browser or on the server? Only an open Discovery may be called from the browser.
  4. Is the data confidential? An open Discovery serves everything it indexes to anyone: every price variant (nokPrice, wholesalePrice, …) and every market’s price list. Negotiated B2B terms never go there, see [[pricing]].
  5. Was the model or content just changed? Discovery is eventually consistent, see Discovery Indexing.

The storefront API contract

  1. Discovery API: every catalogue read. Item by path, category listing, search, typeahead, facets, variant groups, translated paths, list and market prices, stock per location, ranking and similarity. It serves published content by default and drafts with publicationState: draft (editor preview; public on an open tenant). It is eventually consistent.
  2. Shop API: everything about a shopper. Carts, the price for this customer and market, promotions and vouchers, place, orders created from the cart or directly, payments, pipeline stages on those orders, the shopper’s order history, customers, bookings, subscription contracts (one store per tenant, see [[subscriptions]]), and locks.
  3. Catalogue API: the synchronous fallback, for two tasks: per-customer price lists for display (priceFor(customerIdentifiers:)), and a read that must be in sync with what was just published, such as a price right after it changed. Discovery is updated asynchronously after a publish; Catalogue answers from the published state at once. Otherwise keep tenants off it. It is not a peer of Discovery: variants came back [] on three tenants while defaultVariant worked. Draft preview and hreflang are Discovery tasks.
  4. Core API: never in the storefront’s request path, not even server-side with a short cache. It is heavily rate limited. It is for seeding, imports, scheduled jobs, webhook receivers, admin and seller tools behind staff login, and the few tasks with no Shop API equivalent (subscription usage tracking).
  5. Legacy PIM API: setup and back office only (pipelines, markets, VAT types, stock locations, subscription plans).

The task-by-task table (task → API → call → token → browser or server), the request path per page type and the resolved contradictions between skills are in [[storefront]]. Writes follow the same contract, see [[mutation]].

Tokens, scopes, browser and server

API Endpoint Credential From the browser?
Discovery https://api.crystallize.com/{tenant}/discovery None when open (the default), drafts included. X-Crystallize-Static-Auth-Token when restricted, server-side only Yes if open (any origin). Everything it serves is then public
Shop API https://shop-api.crystallize.com/{tenant}/{route} Authorization: Bearer <JWT> from POST …/{tenant}/auth/token, minted with an access token pair scoped to this tenant (or unscoped) No. CORS allows only Crystallize origins and localhost
Catalogue https://api.crystallize.com/{tenant}/catalogue Open, static token, or token pair, as the tenant setting requires Only open, published reads. Contract-price reads are server only
Core https://api.crystallize.com/@{tenant} Token pair, session, or plugin bearer Never (except a presigned upload made on the server, see [[media]])
PIM https://pim.crystallize.com/graphql Token pair; most calls take tenantId Never

The Shop JWT is per tenant, not per shopper: it answers orders(customerIdentifier:) for any identifier. Keep it on the server, cache it, and refresh it before it expires: the API default is one day, and js-api-client asks for 12 hours. The browser holds only the cart id, in an httpOnly cookie. The token rule for minting is in [[permissions]].

Route Scope Serves
/cart cart Carts, wishlists, price context, place, booking holds
/cart/admin cart + cart:admin Promotions
/order order Orders, payments, pipeline stages
/customer customer Shop customers (synced to Core)
/subscription-contract subscription-contract (+ :admin) Contracts. Request a token of its own, see below
/booking/admin booking:admin Reservations, blocks, calendar
/lock lock Acquire and release a lock (idempotency guards)

GET https://shop-api.crystallize.com/{tenant} lists the routes a tenant serves. A token requested with every scope at once read /subscription-contract but answered “Unexpected error” on create, while a token scoped to that route alone worked. Minting, expiry and the error shapes are in Shop API Queries.

Discovery API

The schema is generated per tenant from its shapes and index settings: filter, facet and sort fields, shape types and ranking arguments differ between tenants and change after an ignite. Introspect rather than derive names. Shape types are the identifier in camelCase (... on tool, ... on machineUnit); interfaces keep their capital (... on Product, ... on Folder, ... on Document).

Entry points: search (all shapes, polymorphic hits), browse.<shape> (shape-typed; each needs its own fragment), autocomplete (on name; it restricts and pads with score-0 hits, see the reference) and topics.

Never send an explicit null. after, term, context, sorting and filters reject null (expected string, received null). Build the argument object conditionally and leave the key out.

Item by path, and category listings

query ItemByPath($path: String!) {
search(language: en, filters: { path: { equals: $path } }, pagination: { limit: 1 }) {
hits {
itemId
name
path
updatedAt
breadcrumbs {
name
path
}
... on tool {
defaultVariant {
sku
defaultPrice
}
}
}
}
}
  • A full path is unique, but a last segment is not: paths are unique only within their folder, so never look an item up by its slug with limit: 1.
  • A category listing is browse.<shape>(filters: { parentPaths: { equals: "/tools" } }), which matches at any depth, or Folder.children for direct children. A parentPaths facet gives the subfolders.
  • Relations come back in the request’s language already, so they need no second lookup to localise them.

Listing cards and product pages: variantGroups and variant(selected:)

Product-level filters match a product as soon as different variants satisfy different conditions. To show one card per colourway, or to require that one variant satisfies the whole filter, read the groups:

query Cards($parent: String!) {
browse {
product(language: en, filters: { parentPaths: { equals: $parent } }, pagination: { limit: 24 }) {
hits {
name
path
variantGroups(by: ["colour"], filter: { price_default: { range: { lte: 100 } } }, first: 4) {
key
matched
attributes {
attribute
value
}
summary {
count
price(variant: "default") {
min
max
}
}
representative {
sku
defaultPrice
firstImage {
url
}
}
values(of: "size") {
value
sku
osl: stock(location: "osl")
}
}
}
}
}
}
  • variantGroups never removes a group or changes hits, facets or paging: matching groups come first, and the rest read matched: false. Show the matched groups first when a filter is active.
  • summary.price(variant:) is the “from” price. values(of:) gives one entry per size. stock and inStock take a location, so alias one per stock location.
  • variantGroups { images } takes no arguments, and was about 70 % of one listing’s payload. Prefer representative { firstImage }, and trim renditions as [[responsive-images]] shows.
  • Group keys can contain spaces and slashes, so URL-encode them in links.
  • Tenant fields on a variant need the generated type: ... on ProductVariantForTool { gtin }.
  • On the product page, variant(selected: [{ attribute: "colour", value: "Red" }]) gives the first variant that carries every pair; its sku goes into the Shop API hydrate. Attribute names and values are case-sensitive.
  • variants(skus:) takes one SKU, and a comma list returns [] silently. Use variants(filter:) for several.

Facets and generated filter fields

Facets are in summary { facets }, a Hash. A selection component becomes one field per option (specs_extraction_dustClass_m), filtered with { exists: true }; a numeric is <path>_number, filtered with range. NumberFacet requires boundaries. The naming rules, value shapes and operator traps are in Generated field names.

Unset booleans come back false. A boolean component that was never written reads false on the hit, so a page, JSON-LD or an agent can’t tell “no” from “not stated” by the value. equals: false does not match the unset ones; exists: false and not_equals: true do. Treat false as “not stated” when publishing facts, and don’t write false for “unknown” ([[content-model]], [[seo-geo]]).

Prices and stock

Need Field
List price <variant>Price (nokPrice, defaultPrice), the priceVariants hash, <variant>PriceTiers
“From” price on a card variantGroups.summary.price(variant:); sort and filter on price_<variant>
Public market price <variant>PriceFor(marketIdentifiers: [...]), <variant>BestPriceListFor(marketIdentifiers:)
Stock shown on the page <location>Stock per variant (oslStock), the stockLocations hash; filter on stock_<location>
Contract price (B2B) Not Discovery. The Shop API cart for that customer, or the Catalogue fallback, server-side ([[pricing]])

Market prices are slow (about 1.4 s per 100 products per market), so read them only for the SKUs on screen. A new stock location needs a re-ignite before its field exists.

Paths per language: hreflang and sitemaps

Discovery has no hreflangs field. Read the item’s path in every language with one aliased query by itemId:

query Paths($id: String!) {
en: search(language: en, filters: { itemId: { equals: $id } }) {
hits {
path
updatedAt
}
}
no: search(language: no, filters: { itemId: { equals: $id } }) {
hits {
path
updatedAt
}
}
}

Empty hits mean the item has no version in that language, so leave that alternate out. A sitemap is one browse per language joined on itemId, with updatedAt as lastModified; it is on every hit. Map tenant language codes to BCP 47 (no → nb) and add x-default: see [[information-architecture]] and [[seo-geo]].

Draft preview

query Preview($path: String!) {
search(language: en, publicationState: draft, filters: { path: { equals: $path } }) {
hits {
name
publicationState
updatedAt
}
}
}

publicationState: draft works on search, autocomplete and every browse.<shape>, and the hits report publicationState: "draft". Draft preview is this Discovery read, run on the server behind editor login and never cached.

On an open Discovery, every draft is public. publicationState: draft needs no credential there: tools-universe returned its 541 draft documents to an anonymous request, and another tenant served an unpublished page the same way (2026-11-12). Never keep confidential content, prices or embargoed launches in drafts on an open tenant. To keep drafts private, restrict Discovery, run igniteDiscoApi (the setting does not reach Discovery before that, and takes a few more minutes after), and send X-Crystallize-Static-Auth-Token from the server only. The access token pair was refused there.

Consistency

Publishing is asynchronous. New shapes and components need an ignite. A new schema reaches the nodes over minutes, and an error answered in that window is cached per query body. Under heavy load Discovery answers HTTP 200 with errors: [{ message: "Response Error" }]. Ship code that reads a new field only after the field answers reliably, make cached reads fail-safe, and retry on “Response Error”. Details in Discovery Indexing.

Shop API reads

All Shop API reads run on the server, with the JWT above.

# POST https://shop-api.crystallize.com/{tenant}/cart
query {
cart(id: "cart-id") {
id
state
items {
variant {
sku
}
quantity
price {
gross
net
}
}
total {
gross
net
currency
}
}
}
  • items.price on a cart is the line total; order lines carry the unit price.
  • /order: read anything you just wrote with order(id: UUID!), and the shopper’s history with orders(customerIdentifier:, limit: 100). The listing is a second, eventually consistent store: new orders appear after seconds to minutes, a few never did, and limit/skip paging is inconsistent. Group by coreId. Take the identifier from the session, never from the client. See Shop API Order Queries.
  • /customer: customer(identifier:). /subscription-contract: subscriptionContracts(customerIdentifier:), on tenants whose contracts live on the Shop API ([[subscriptions]]).
  • Booking availability is a Shop /cart read, and Discovery never serves it ([[bookable-resources]]).

Catalogue API (fallback)

Use it for what Discovery and the Shop API can’t do: showing a specific customer’s price-list price on a page, server-side, cached per organisation, and reads that must be in sync with a publish (Discovery is asynchronous).

query ContractPrice($skus: [String!]!, $customers: [String!]) {
productVariants(skus: $skus, language: "en") {
sku
priceVariant(identifier: "nok") {
priceFor(count: 1, customerIdentifiers: $customers) {
price
identifier
}
}
}
}

Don’t use it for path reads, listings, preview or hreflang. See Catalogue API.

Core API reads (back office only)

Core is for admin dashboards, seller and approval queues across customers, imports and reporting, behind your own server and staff login. It filters orders by meta, pipelineStageIds, SKU or payment provider, which the Shop API can’t. No Core query takes a tenantId, and most root fields return a union, so always select ... on BasicError { errorName message }.

query ListOrders {
orders(
first: 20
filter: { customer: { identifier: "customer@example.com" } }
sort: { field: createdAt, direction: desc }
) {
... on OrderConnection {
edges {
node {
id
total {
gross
currency
}
}
}
}
... on BasicError {
errorName
message
}
}
}

See the Core API Queries Reference.

Best Practices

  1. Follow the contract - Discovery for catalogue reads, the Shop API for shopper data, Catalogue only for per-customer prices and in-sync reads, Core never in the request path
  2. Detect the Discovery schema, don’t hardcode it - Introspect filter, facet, sort and ranking fields after each ignite
  3. Leave optional arguments out - Never send null to Discovery or the Shop API
  4. Sort with one key, or check the order - Sort keys apply in schema order, so a secondary itemId can replace a primary that sorts after it. score is safe as the primary, and { itemId: asc } alone is stable for full scans
  5. Request only needed fields - facets cost about 17 KB per read, and image ladders dominate listings; skip them in rails and menus
  6. Treat unset booleans as “not stated” - false on a hit may mean never written
  7. Scope customerIdentifier on the server - The Shop JWT is per tenant, not per shopper
  8. Read what you just wrote by id - order(id:), never the listing, and never the listing for idempotency
  9. Keep confidential prices off Discovery - When it is open, everything it serves is public
  10. Expect lag after publishing and model changes - See Discovery Indexing

References

[[storefront]] owns the request path per page type and the full API decision table. [[mutation]] covers writes on the same APIs, and [[js-api-client]] wraps them for JS/TS. Ranking, personalisation and similarity are in [[vector-ranking]], prices for markets and customers in [[pricing]], and image renditions in [[responsive-images]].


Reference Details

Catalogue API Reference

The Catalogue API provides path-based access to items in your Crystallize tenant. In a storefront it is a fallback for one named task: showing a specific customer’s price-list prices. Every other catalogue read, including item by path, draft preview and hreflang, goes to the Discovery API ([[storefront]]).

Base URL

https://api.crystallize.com/{tenant-identifier}/catalogue

Replace {tenant-identifier} with your tenant name.

Authentication

By default, the API is accessible without authentication. You can configure access in the Crystallize App:

  1. Go to Settings → API Access
  2. Choose your preferred access level
  3. Save changes

A restricted Catalogue API takes the X-Crystallize-Static-Auth-Token header, or X-Crystallize-Access-Token-Id and X-Crystallize-Access-Token-Secret, depending on the level chosen. A missing or wrong credential answers HTTP 400 Invalid static auth token, not 401 as Discovery does. Inside a Shop API hydrate, which reads products from the Catalogue, it shows up as a GraphQL error on hydrate. Unlike Discovery, the setting takes effect at once.

When to Use Catalogue API

Task Use
A specific customer’s price-list price, for display Catalogue, server-side, cached per organisation (Prices for one customer)
Item by path, listings, search, facets, variants Discovery search(filters: { path: { equals } }), browse
Editor draft preview Discovery publicationState: draft
hreflang, translated paths, sitemaps Discovery, one aliased query per language by itemId
The price this customer pays in a cart Shop API hydrate with the customer on the cart ([[pricing]])
A back-office check that a publish landed Catalogue (or Core) by path, from a script

It is not a peer of Discovery. On three tenants (Screen Universe and two others) variants came back [] on products while defaultVariant worked, so a product page built on it showed one variant or none. It did not reproduce on tools-universe (2026-11-12). If you read variants here at all, check for an empty list.

Its stronger consistency is a reason to use it in seed and verification scripts (did every path publish?), not in the storefront’s request path. A storefront that falls back to Catalogue whenever Discovery lags gets two code paths and two failure modes for one page.

Query Structure

Basic Path Query

{
catalogue(language: "en", path: "/shop/plants") {
name
path
type
}
}

catalogue also takes version (published by default, or draft; for editor preview use Discovery’s publicationState: draft instead) and pathResolutionMethods. That one defaults to [canonical], so an alias, a historic path or a shortcut answers null unless you ask for alias, history, shortcut or any.

Product Query with Variants

{
catalogue(language: "en", path: "/shop/furniture/dining-chair") {
name
... on Product {
variants {
sku
name
price
stock
attributes {
attribute
value
}
}
}
}
}

Folder with Children

children is deprecated. Read a folder through subtree, a cursor connection:

{
catalogue(language: "en", path: "/shop/plants") {
name
subtree(first: 20, sortField: treePosition, sort: asc) {
edges {
cursor
node {
name
path
type
}
}
pageInfo {
hasNextPage
endCursor
totalNodes
}
}
}
}

sortField is treePosition (the default), publishedAt or name, and type narrows to product, document or folder.

Document Query

{
catalogue(language: "en", path: "/blog/welcome-post") {
name
... on Document {
components {
id
name
content {
... on RichTextContent {
html
}
}
}
}
}
}

Reading a Colors component

A colors component returns ColorsContent, holding a list of entries. Each entry carries whichever notations were stored — they are the same colour expressed several ways, so select the ones your frontend actually renders rather than all of them.

{
catalogue(language: "en", path: "/shop/furniture/dining-chair") {
name
components {
id
content {
... on ColorsContent {
colors {
label
hex
rgb {
r
g
b
a
}
pantone
ral
}
}
}
}
}
}

ColorEntry exposes label, hex, rgb { r g b a }, hsl { h s l a }, cmyk { c m y k }, pantone and ral. Every field is nullable — an entry only carries the notations that were authored, so a storefront reading hex needs a fallback for entries stored as Pantone only.

Colour filtering does not belong here. Discovery does index a Colors component’s hex, label and ral as filter fields, but filter on the Selection or topic that carries the colour name instead: near-identical hexes do not group into one facet. See [[content-model]] for the modelling rule.

cURL Example

Terminal window
curl \
-X POST \
-H "Content-Type: application/json" \
--data '{ "query": "{ catalogue(language: \"en\", path: \"/shop/plants\") { name } }" }' \
https://api.crystallize.com/furniture/catalogue

Limitations

The Catalogue API does not support:

  • Full-text search
  • Filtering
  • Faceting
  • Sorting beyond the children of one item (subtree)

Use the Discovery API for these capabilities.

Prices for one customer

This is the task the Catalogue API is still for. Discovery knows markets only. The Shop API resolves a customer’s price list for the cart’s customer (inherited from parent customers), which a throw-away hydrate can use as a price check. The Catalogue API resolves it for any customer you name, so this is where a B2B storefront reads an account’s agreed prices for display: server-side, cached per organisation, never from the browser.

query ContractPrice($skus: [String!]!, $customers: [String!]) {
productVariants(skus: $skus, language: "en") {
sku
priceVariant(identifier: "nok") {
price # the list price
priceFor(count: 10, customerIdentifiers: $customers) {
price # what this customer pays at this quantity
identifier # the price list that applied
modifier
modifierType
}
}
}
}

customerIdentifiers is a list, and priceFor also takes customerGroupIdentifiers and marketIdentifiers. A percentage list applies on top of the variant’s volume tiers, and a list aimed at an organisation resolves for its child customers too — see [[pricing]] for the measurements and the caveats (productVariants(skus:) caps at 150 SKUs, and priceFor is slow enough to need caching).

Size and speed (Lab Universe):

  • productVariants(skus:) takes at most 150 SKUs (TOO_MANY_SKUS_PROVIDED), and priceFor took about 2 s per 150 SKUs.
  • For a whole agreement, read the list once instead: priceList(identifier:) { productVariants(language:, first:) { edges { node { sku priceVariant(identifier:) { priceList(identifier:) { modifier modifierType } } } } } } took 3.5 s for 2,211 SKUs. Its pageInfo.hasNextPage stays true past the last SKU, so stop on an empty page.
  • Either way, cache per organisation, and apply the cached rules to the Discovery prices on the page. A slow cache miss during a Next.js prerender is cut off.

Core API Queries Reference

The Core API provides comprehensive read access to items, customers, orders, shapes, and tenant configuration. Use this for admin interfaces, reporting, and complex filtering needs.

Table of Contents

Base URL

https://api.crystallize.com/@{tenant-identifier}

Note the @ prefix before the tenant identifier.

Authentication

Authentication is required. Use access tokens generated in the Crystallize App:

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": "..."}'

Core API vs Other APIs

Use Core API for:

  • Admin interfaces and dashboards
  • Complex order filtering (by customer, SKU, payment provider)
  • Reading shape/piece definitions
  • Customer management
  • Bulk data access

Never in a storefront’s request path. Core is heavily rate limited, so it runs in seeds, imports, scheduled jobs, webhook receivers and admin or seller tools behind staff login, on your own server. A storefront reads the catalogue from Discovery and shopper data (carts, orders, customers) from the Shop API; see the contract in [[storefront]] and the query skill’s SKILL.md.

Reading a Core Response

Every query below follows these rules. The first three are checked before anything runs, so breaking one fails the whole request with a validation error.

  • The tenant comes from the URL. No query takes a tenantId argument.
  • The root fields below return a union. Select the result with ... on <Type> and the failure with ... on BasicError; items(...) { edges } without a fragment does not validate. The list types are ItemConnection, CustomerConnection, CustomerGroupConnection, OrderConnection, PieceConnection, FlowContentConnection, ArchivedItemVersionConnection, BulkTaskConnection, ImageConnection and PriceListConnection (priceLists). tenant(identifier:) needs ... on Tenant the same way. shapes is the exception: it returns a plain ShapeConnection.
  • content and config are unions too. Give content one fragment per component type you expect. The names carry Component here (RichTextComponentContent), unlike the Catalogue API (RichTextContent).
  • A missing record is null, not an error. item, customer and order answer null when nothing matches, so a client has to handle null as well as the union members.
  • An empty page has edges: null, not []. Guard before mapping over it.
  • Keep the same sort on every page. The cursor carries the sort field, and a different one is refused: Invalid pagination options: cannot provide a sort field and a cursor at the same time. first/after cannot be mixed with last/before either.

Item Queries

Get Item by ID

query GetItem {
item(id: "item-id", language: "en") {
... on Product {
id
name
shapeIdentifier
tree {
path
parentId
}
components {
componentId
type
content {
... on SingleLineComponentContent {
text
}
... on RichTextComponentContent {
html
}
}
}
defaultVariant {
sku
name
price
stock
images {
url
altText
}
}
variants {
sku
name
price
stock
}
}
... on Document {
id
name
shapeIdentifier
components {
componentId
type
}
}
... on Folder {
id
name
shapeIdentifier
tree {
path
}
}
... on BasicError {
errorName
message
}
}
}

item and items read the current version unless told otherwise (versionLabel: current, draft or published). price and stock read the default price variant and stock location: pass identifier:, or select priceVariants and stockLocations. A Core Folder has no children field; list them with items(filter: { parentItemId: "folder-id" }).

List Items with Pagination

first defaults to 25 and caps at 100. Asking for more is refused — Invalid pagination options: Cannot list more than 100 items at a time. — and it arrives as an INTERNAL_SERVER_ERROR with the path pointing at whatever field you selected, which makes it look like something else went wrong. Page with after instead. Verified on a live tenant: first: 100 returned 100 rows of 540 with hasNextPage: true, while first: 150 and first: 500 both errored.

query ListItems {
items(
language: "en"
first: 20
after: "cursor"
filter: {
shapeIdentifiers: ["product", "bundle"]
# parentItemId: "folder-id"
# topicId: "topic-id"
}
sort: { field: createdAt, direction: desc }
) {
... on ItemConnection {
edges {
cursor
node {
id
name
type
shapeIdentifier
createdAt
updatedAt
... on Product {
defaultVariant {
sku
price
stock
}
}
}
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
totalCount
}
... on BasicError {
errorName
message
}
}
}

sort.field is name (the default), createdAt or position: updatedAt is not sortable here. filter also takes type, shapeIdentifier, name (case-insensitive substring), itemIds, externalReferences, relatingToItemId, imageKeys, videoKeys and fileKeys. parentItemId lists direct children, shortcuts included.

Get Item Component

Read a specific component from an item:

query GetItemComponent {
item(id: "item-id", language: "en") {
... on Item {
id
component(id: "description") {
componentId
content {
... on RichTextComponentContent {
html
}
}
}
}
}
}

Check Identifier Availability

query CheckIdentifier {
isIdentifierAvailable(desired: "new-shape", type: shape) {
... on IdentifierAvailability {
isAvailable
suggestion
}
... on BasicError {
errorName
message
}
}
}

type is required: flow, flowStage, priceVariant, role, shape, stockLocation, customer or customerGroup. suggestion is a free alternative when isAvailable is false.

Customer Queries

Get Customer by Identifier

query GetCustomer {
customer(identifier: "customer@example.com") {
... on Customer {
identifier
type
firstName
lastName
email
phone
companyName
taxNumber
addresses {
type
firstName
lastName
street
street2
city
state
postalCode
country
phone
email
}
meta {
key
value
}
}
... on BasicError {
errorName
message
}
}
}

There is one Customer type for people and companies: type is individual or organization. Customers have no id. customer also answers on externalReference: { key: "erp", value: "1234" } instead of identifier.

List Customers

query ListCustomers {
customers(
first: 20
filter: {
email: "jane@"
# type: individual
}
) {
... on CustomerConnection {
edges {
node {
identifier
type
firstName
lastName
email
companyName
}
}
pageInfo {
hasNextPage
endCursor
}
totalCount
}
... on BasicError {
errorName
message
}
}
}

email is a case-insensitive prefix match, so a domain such as @example.com finds nothing. identifier, firstName, lastName, companyName and phone are case-insensitive substring matches. filter also takes type, meta: { key, value }, parent: { identifier, type } and logicalOperator (and by default, or to match any condition). sort.field is createdAt (the default), name, identifier or type.

Get Customer Groups

query GetCustomerGroup {
customerGroup(identifier: "group-identifier") {
... on CustomerGroup {
identifier
name
childCount
}
... on BasicError {
errorName
message
}
}
}
query ListCustomerGroups {
customerGroups(first: 20) {
... on CustomerGroupConnection {
edges {
node {
identifier
name
childCount
}
}
}
... on BasicError {
errorName
message
}
}
}

A group does not list its members. Read them with customers(filter: { parent: { identifier: "group-identifier", type: customerGroup } }).

Order Queries

Get Order by ID

query GetOrder {
order(id: "order-id") {
... on Order {
id
reference
createdAt
updatedAt
customer {
identifier
firstName
lastName
email
}
cart {
sku
name
quantity
price {
net
gross
currency
}
imageUrl
}
total {
net
gross
currency
}
payment {
provider
... on StripePayment {
paymentIntentId
}
}
meta {
key
value
}
}
... on BasicError {
errorName
message
}
}
}

List Orders with Filtering

The Core API supports advanced order filtering by customer, SKU, payment provider, and metadata:

query ListOrders {
orders(
first: 20
filter: {
customer: { identifier: "customer@example.com" }
# sku: "PROD-123"
# paymentProvider: stripe
# meta: [{ key: "source", value: "mobile-app" }]
}
sort: { field: createdAt, direction: desc }
) {
... on OrderConnection {
edges {
cursor
node {
id
createdAt
total {
gross
currency
}
customer {
identifier
}
cart {
sku
name
quantity
price {
gross
}
}
}
}
pageInfo {
hasNextPage
endCursor
}
totalCount
}
... on BasicError {
errorName
message
}
}
}

Filter Options:

  • customer - { identifier, firstName, lastName, email, companyName, address: { street, city, country } }
  • sku - Filter orders containing specific SKU
  • paymentProvider - Enum: cash, custom, klarna, paypal or stripe
  • paymentStatus, types, reference - Filter by payment status, order type or reference
  • meta - Filter by metadata key/value pairs
  • createdAt, updatedAt - Date range filtering: { min, max }
  • totalPrice - { min, max, type }, where type is net (the default) or gross
  • pipelineId, pipelineIds, pipelineStageId, pipelineStageIds - Filter by pipeline or stage
  • stockLocationIdentifier, appliedPromotionIdentifier, hasSubscription, subscriptionContractId, relatedToOrderId

sort.field is updatedAt (the default) or createdAt, and direction defaults to desc.

Shape and Piece Queries

Get Shape Definition

query GetShape {
shape(identifier: "product") {
... on Shape {
identifier
name
type
components {
id
name
type
description
}
variantComponents {
id
name
type
description
}
resolvedConfiguration
}
... on BasicError {
errorName
message
}
}
}

config on a component is the ComponentConfig union, so it needs one fragment per component type. resolvedConfiguration is the whole definition as JSON with pieces expanded, which is usually what a script wants.

List All Shapes

shapes is the one root field here with no union around it.

query ListShapes {
shapes(first: 100) {
edges {
node {
identifier
name
type
itemCount
}
}
pageInfo {
hasNextPage
endCursor
}
totalCount
}
}

Get Piece Definition

query GetPiece {
piece(identifier: "seo") {
... on Piece {
identifier
name
components {
id
name
type
}
}
... on BasicError {
errorName
message
}
}
}

List All Pieces

query ListPieces {
pieces(first: 100) {
... on PieceConnection {
edges {
node {
identifier
name
components {
id
name
type
}
}
}
}
... on BasicError {
errorName
message
}
}
}

Flow Queries

Get Flow

query GetFlow {
flow(identifier: "flow-identifier") {
... on Flow {
identifier
name
type
stages {
identifier
name
}
}
... on BasicError {
errorName
message
}
}
}

Get Flow Content

List items in a flow stage:

query GetFlowContent {
flowContent(first: 20, filter: { stageIdentifier: "stage-identifier" }) {
... on FlowContentConnection {
edges {
node {
id
stageIdentifier
createdAt
data {
... on FlowItemContentData {
language
version
item {
id
name
type
}
}
}
}
}
pageInfo {
hasNextPage
endCursor
}
}
... on BasicError {
errorName
message
}
}
}

Flows and stages are addressed by identifier. filter.item takes { id, language, version } to find where an item sits, and flowStage(identifier:) reads one stage.

Archive Queries

Get Archived Version

query GetArchive {
archive(id: "archive-id") {
... on ArchivedItemVersion {
id
number
name
archivedAt
archivedBy {
email
}
item {
id
name
}
}
... on BasicError {
errorName
message
}
}
}

archive takes either id alone, or itemId, language and number together (plus an optional versionLabel, published by default). Mixing the two is refused.

List Archived Versions

query ListArchives {
archives(filters: { itemId: "item-id", language: "en" }, first: 10, sort: { field: number, direction: desc }) {
... on ArchivedItemVersionConnection {
edges {
node {
id
number
name
archivedAt
archivedBy {
email
}
}
}
}
... on BasicError {
errorName
message
}
}
}

Bulk Task Queries

Get Bulk Task Status

query GetBulkTask {
bulkTask(id: "task-id") {
... on BulkTask {
id
type
status
createdAt
startedAt
stoppedAt
info
actor {
email
}
}
... on BasicError {
errorName
message
}
}
}

List Bulk Tasks

query ListBulkTasks {
bulkTasks(first: 20, filter: { status: started }) {
... on BulkTaskConnection {
edges {
node {
id
type
status
createdAt
}
}
}
... on BasicError {
errorName
message
}
}
}

status is pending, started, complete or error. filter also takes type and actorId.

File and Image Queries

Get Image

query GetImage {
image(key: "image-key") {
... on Image {
key
url
altText
caption {
plainText
}
variants {
url
width
height
}
}
... on BasicError {
errorName
message
}
}
}

image and images take an optional language and fall back to the tenant’s default language.

List Images

query ListImages {
images(first: 20, filter: { filename: { value: "hero", condition: contains } }) {
... on ImageConnection {
edges {
node {
key
url
altText
createdAt
}
}
}
... on BasicError {
errorName
message
}
}
}

filename.condition is contains (the default), startsWith or endsWith. filter.topic takes { ids, includeDescendants, logicalOperator }.

Error Handling

The Core API uses union return types. Always handle potential errors, and spread BasicError, the interface every error type implements, to catch them all in one fragment:

query {
item(id: "item-id", language: "en") {
... on Product {
id
name
}
... on BasicError {
errorName
message
}
}
}

Common error types:

  • UnauthorizedError - Invalid or missing credentials
  • InvalidIdError - The id is malformed; providedValue holds what was sent
  • UnknownError - Anything else; errorName carries the original error name
  • BasicError - Generic error

ItemNotFoundError and OrderNotFoundError belong to mutations. They are not members of the item and order unions, so spreading them on a read fails validation: a read answers null instead.

TypeScript Types

Use generated types for type safety:

import { Query, GetItemQuery, GetCustomerQuery, ListOrdersQuery } from "@/generated/core";

These come from your own GraphQL Code Generator run against the Core API schema: the import path is wherever your config writes them, and nothing is published under it.

Discovery API Reference

The Discovery API is a storefront’s catalogue API. Every catalogue read goes here: item by path, listings, search, facets, variant groups, prices, stock, translated paths, and drafts for preview. It is read-only and eventually consistent (Discovery Indexing). Which API serves the rest of a storefront is in [[storefront]].

Base URL

https://api.crystallize.com/{tenant-identifier}/discovery

Replace {tenant-identifier} with your tenant name — the bare identifier, no @ (that prefix belongs to the Core API).

Authentication

By default, the Discovery API is open, and its CORS allows any origin, so a browser can call it. Restrict it with the Search & Discovery entry under Settings → API Access. Discovery shares that setting with the Search API; it is separate from the Catalogue entry, so restricting one does not restrict the other.

Tenant setting Published reads Drafts (publicationState: draft)
Open (default) Nothing Nothing: drafts are public
Restricted X-Crystallize-Static-Auth-Token: <static token>; missing or wrong answers 401 The same static token, server-side only

The static token is the one credential Discovery is known to read, and a bearer token is ignored. With Search & Discovery set to accessTokenPair, Discovery still took the static token and refused the access token pair (sandbox tenant, 2026-11-16); with staticToken it refused the pair too. Send the static token whichever mode is set.

A change of the setting reaches Discovery only after an ignite. The Search API follows it at once; Discovery does not. Change the setting, run igniteDiscoApi, poll the bulk task until it is complete, then wait for several refusals in a row before you rely on it:

  • Without an ignite, Discovery stayed open to anonymous reads for at least ten minutes.
  • The ignite took 40–75 s. After it, anonymous calls flapped between 200 and 401 for about four more minutes, while the nodes caught up.
  • After that, one query body (a contract price) still answered 200 once, which looks like a cached response for that body. Drafts and prices can stay readable for a few minutes after the change.
  • Opening Discovery again needs an ignite too.
mutation { igniteDiscoApi(stacks: opensearch) { __typename ... on BulkTask { id status } } }
query ($id: ID!) { bulkTask(id: $id) { ... on BulkTask { status } } }

When Discovery is open, everything it serves is public: every price variant (nokPrice, wholesalePrice), every market’s price list through …PriceFor(marketIdentifiers:) to anyone who knows the identifier, and every draft. Never put confidential terms such as negotiated B2B prices in it ([[pricing]]), and never keep confidential content or embargoed launches in drafts on an open tenant.

The schema is generated per tenant

This is the single most important thing to know before writing a query. The Discovery schema is derived from the tenant’s shapes and index settings, so it differs between tenants and changes when the tenant is re-indexed:

  • Every shape becomes a type and a browse field — product, category, brand, … A hyphen in an identifier camelCases: the shape my-shape is myShape, with the input MyShapeFilter
  • Filter, facet and sort inputs (TenantFilter, ProductFacet, TenantSort, …) are generated from indexed component fields — price_default, stock_oslo, specs_label, variants_topics, …
  • A component with discoverable: false is left out, and a shape with none left is dropped
  • TenantLanguage is an enum of the tenant’s languages, under the same rule: nb-no is nbNo
  • Ranking inputs and their enums appear only on tenants served for ranking (see below)

Introspect, do not assume. An un-ignited tenant answers HTTP 404 with {"success": false, "message": "There is no ignited Tenant for <tenant>."} rather than serving a schema at all. A tenant with no shapes has no browse field. A tenant whose schema cannot be built answers HTTP 500 with extensions.code: "TENANT_SCHEMA_UNAVAILABLE". Retrying will not help, so report it with the tenant identifier. { __typename } is the cheapest check that a tenant is serving.

Note: The Discovery API uses lowercase type names in inline fragments (... on product, ... on category) because types are derived from your shape identifiers. Interface fragments keep their capital (... on Product, ... on Folder, ... on Document).

Generated field names

Nothing in the schema says which component or option a generated field belongs to, so builds kept deriving names and getting them wrong. The rules seen across builds (introspect TenantFilter, <Shape>Filter and TenantRankByField after each ignite to confirm them):

Source Field Filter with
Component in a piece <componentId>_<pieceComponentId> (physical_beltHook) its type’s filter
Piece inside a componentChoice <choiceId>_<pieceId>_<componentId> (specs_drilling_gears_number) its type’s filter
Numeric <path>_number, and <path>Unit on hits range: { gte, lte }
Boolean <path> equals, exists
Selection, single or multiple One field per option: <path>_<optionKeyCamel> (specs_extraction_dustClass_m) { exists: true } (false for “without”)
Variant component variants_<componentId> (variants_gtin, variants_durationHours_number) its type’s filter
Price variant, stock location price_<variant>, stock_<location> (one value per variant) range
Shape type the shape identifier in camelCase (machineUnit; product stays lowercase) shape: { equals }
  • Ids and option keys are camelCased, except that a hyphen before a digit becomes _: sds-plus → sdsPlus, keyless-13 → keyless_13, core-1-1-4-unc → core_1_1_4Unc, sold-30d → sold_30d_number, but gwp-a1-a3 → gwpA1A3_number. The field name doesn’t spell the selection’s own key (ull-silke → woolSilk), so map options from the field list rather than by hand.
  • { variants_markets: { in: [...] } } on a multi-selection is rejected: use the per-option fields with exists.
  • A selection field holds the option’s label, and its facet is keyed by the label, with the option key as label: { "SDS-plus": { "count": 14, "label": "sds-plus", "filter": "specs_concrete_toolHolder_sdsPlus" } }.
  • A component called type becomes component_type. Nested numerics are named after the component id on the shape, not the piece’s own id.
  • The same field name with two types on two shapes must be aliased in one query (a: price / b: price), or the query fails validation.
  • There is no “has this choice” filter on a componentChoice. To find the products of one spec family, OR an exists: true over that family’s fields.

Shapes of values

Value Comes back as
Selection A Hash { key: label } ({ "sds-plus": "SDS-plus" }), not a list
Item topics topics: a Hash of the leaves with labels (use it for chips); topicPaths: every ancestor, unordered
Image topics A flat hash of every ancestor path ({ "0": "/bilde", "1": "/bilde/type", … })
Content chunk An object when not repeatable, a list when repeatable
paragraphCollection A flat list
Rich text A scalar; ask for a format with format:
breadcrumbs A list of lists (one per path to the item), each ending with the item itself
Boolean never written false, see below
Colors A plain list

Selection labels come back in the editor language, so a multilingual storefront localises option labels itself.

Unset booleans read false. A boolean component that was never written comes back false on the hit. Measured on tools-universe (2026-11-12) for physical_beltHook: 30 items set it to true, none to false, and the other 510 read false.

Filter Matches
equals: true items where it was written true
equals: false only items where false was written
exists: false items where it was never written
not_equals: true written false and never written

So JSON-LD, feeds and agent filters must treat false as “not stated”, and a model should not write false for “unknown” ([[content-model]], [[seo-geo]]).

Queries

Query Use for
search Full-text search across all shapes; polymorphic hits
browse Shape-typed access — each shape becomes its own query with all its component fields
autocomplete Type-ahead on name — it restricts, it does not rank (see below)
topics Children of a topic in the topic map

Never send an explicit null for an optional argument. pagination: { after: null } is rejected with invalid_type: after Invalid input: expected string, received null, and the same goes for term and context. Leave the key out on the first page instead — with GraphQL variables that means building the argument object conditionally, not passing null.

A hit type keeps the shape identifier’s case. A shape called tool gives the Discovery type tool (lower case) while its inputs are ToolFilter, ToolFacet and ToolSort. __type(name: "Tool") answers null, so a script that introspects the schema should read the hit type from the shape query’s hits rather than capitalise the identifier itself.

search, autocomplete and every field under browse take the same argument set:

language, publicationState, path, pathResolutionMethod, term,
pagination, options, rankBy, context, nearestTo, filters, facets, sorting

Folder.children and Topic.items take that same set, which is what makes nested category listings filterable and rankable in one round trip. Their filters are a TenantFilter, and they sort by position: asc unless told otherwise.

A query nested deeper than 20 levels is refused, fragments included, and a batched request carries at most 10 operations.

{
search(language: en, filters: { type_in: [product] }, pagination: { limit: 20, after: "XXXX" }) {
summary {
totalHits
hasMoreHits
endCursor: endToken
facets
}
hits {
id
name
path
shape
score
}
}
}

Hits are polymorphic — use one inline fragment per shape, and read shape to tell them apart.

Filtering by Shape

{
search(language: en, filters: { shape: { equals: "sneaker" } }) {
hits {
name
path
}
}
}

Price Range Filter

{
search(language: en, filters: { price_sales: { range: { gte: 20, lte: 100 } } }) {
hits {
name
path
}
}
}
{
search(language: en, term: "plop", sorting: { score: desc }) {
hits {
name
path
}
}
}
  • term matches whole words only: “drill” does not find “drills” or “hammerdrill”. Add fuzzy options for typos, and the autocomplete filter for prefixes (below).
  • Search is per language. A Norwegian term on language: en finds nothing.
  • A term is expensive: full-text reads took 0.4-0.9 s where filter-only reads took under 0.1 s. Search once for the ids, and read the page’s details by id with filters.
  • With rankBy, the ranking signals replace text relevance. Add { signal: relevance } to the terms whenever there is a term ([[vector-ranking]]).

Filter operators

Filters compose with AND and OR, each taking a list of nested filters.

Input Operators
StringFilter exists, equals, not_equals, in, not_in, contains, not_contains, phrase, regex, not_regex
StringFilterWithAutocomplete the above plus autocomplete: { term, options }
NumberFilter exists, equals, not_equals, in, not_in, range: { gt, gte, lt, lte }
DateFilter exists, equals, not_equals, in, not_in, range: { gt, gte, lt, lte }
BooleanFilter exists, equals, not_equals
GeoFilter exists, within: { box, circle, polygon } — on Location components

type_in: [ItemType] (product, document, folder) is the common way to narrow a search. It is a top-level key of TenantFilter only: a shape’s own filter has no use for it.

Operators that differ from what builds expected:

  • There is no prefix. regex is anchored and must match the whole value: on tools-universe sku: { regex: "4885" } matched 0 items and "4885.*" matched 2.
  • NumberFilter has range: { gt, gte, lt, lte }, not lte at the top level.
  • Filter on itemId, not id: the hit id is the document id (<itemId>-<lang>-<state>).
  • sku: { in: [...] } filters products by SKU. There is no variants filter; use the variants_* fields, or variants(filter:) on the hit.
  • Topics: topics: { equals: "/city/helsinki" }, a plain StringFilter on the path; there is no topics_path. Two builds found no topics key on browse.<shape> filters, while tools-universe has one (2026-11-12): check the shape’s filter type, and fall back to search with type_in or to generated fields.
  • parentPaths: { equals: "/shop" } matches every descendant of /shop; parentId matches direct children.
  • not_equals keeps documents that have no value at all, and so does exists: false. See unset booleans.
  • Explicit null is rejected for after, term, context, sorting, filters and rankBy. Leave the key out.

Search is exact by default. Opt into typo tolerance through options.fuzzy:

{
search(language: en, term: "gren", options: { fuzzy: { fuzziness: SINGLE, prefixLength: 1 } }) {
hits {
name
path
}
}
}
Option Default Meaning
fuzziness NONE Max single-character edits: NONE, SINGLE, DOUBLE
prefixLength 0 Leading characters that must match exactly before edits apply
maxExpensions 50 Misspelled and inert: accepted, and the value is discarded
maxExpansions 50 Max term variations generated

Two spelling traps: FuzzySearchOptions carries maxExpensions on every tenant but the working maxExpansions only on tenants served for ranking, and sending it anywhere else is a validation error. And the enum type is Fuziness, not Fuzziness — a typed variable ($f: Fuzziness!) fails schema validation.

Raising fuzziness widens the candidate set and costs latency — prefer SINGLE before DOUBLE, and use prefixLength to keep short, common terms precise. DOUBLE is very loose on short tokens: on a 540-document tenant a multi-word query matched almost everything, which makes counts and facets meaningless. Keep a results page at SINGLE, and use DOUBLE only as a last-chance fallback when SINGLE found nothing.

Autocomplete

{
autocomplete(language: en, term: "espr", pagination: { limit: 8 }) {
hits {
name
path
}
}
}

autocomplete matches on name and otherwise takes the same arguments as search — including filters and ranking.

Autocomplete restricts; it does not rank

This is the trap. Measured on a 540-document tenant:

Query totalHits Scores
autocomplete(term: "milwaukee") 540 mixed
autocomplete(term: "zzzzqq") — matches nothing 540 all 0
search(filters: { name: { autocomplete: { term: "milwaukee" } } }) 146 all 0
the same filter plus term and sorting: { score: desc } 146 25.9 … 11.6

Two things follow:

  • The top-level autocomplete query answers with the whole index, padding the tail with score-0 hits, whatever the term. Drop hits with score: 0, or add the name filter, or you will show a type-ahead list of everything you sell.
  • name: { autocomplete: { term } } is a filter on StringFilterWithAutocomplete — name, sku and variants_name have it — and on its own every hit comes back scored 0, in no useful order. Pass the same text as term as well and sort by score: desc: the term scores the matches, the filter restricts the set.

Autocomplete is prefix matching per token, so without fuzzy options (options beside the filter’s term takes FuzzySearchOptions) it does not fix a typo inside a word (“nikkon”, “hitli”), and it does not match inside a compound word (“kjernebor” does not come up for “diamantkjernebor”). Full-text search(term:, options: { fuzzy: … }) does both. The pattern that works: prefix autocomplete first, and full-text fuzzy as the fallback when it finds nothing.

Browse Queries

The browse API provides shape-typed access — each shape becomes its own query type with all component fields available directly. This is the recommended approach for storefronts.

Browse by Shape

{
browse {
product(language: en, pagination: { limit: 25 }) {
summary {
totalHits
hasMoreHits
endToken
}
hits {
name
path
defaultVariant {
sku
defaultPrice
firstImage {
url
}
}
}
}
}
}

Browse by Path (Folder Listing)

{
browse {
category(language: en, path: "/shop/*") {
hits {
name
path
children(language: en) {
hits {
... on product {
name
path
defaultVariant {
sku
defaultPrice
}
}
}
}
}
}
}
}
  • Use path: "/shop/*" for everything under /shop, at any depth. For direct children only, use Folder.children as above, or filter on parentId
  • Use path: "/shop/exact-item" for a specific item
  • pathResolutionMethod (canonical, alias, history, shortcut) controls how a path is resolved; left out, a path matches on all four
  • Use aliases to combine multiple browse queries in one request

Combined Query with Aliases

{
folder: browse {
category(language: en, path: "/shop") {
hits {
name
path
}
}
}
products: browse {
product(language: en, path: "/shop/*") {
hits {
name
path
defaultVariant {
sku
defaultPrice
}
}
}
}
}

Sorting

sorting takes one or more generated fields plus score, each asc or desc:

{
browse {
product(language: en, sorting: { price_default: asc }) {
hits {
name
path
}
}
}
}

With no sorting, hits come back by itemId descending, not by relevance, even with a term. Send sorting: { score: desc } to order by relevance.

Sort keys apply in schema order, not in the order you write them. In { price_default: asc, itemId: asc }, itemId comes before the price fields in TenantSort, so it became the primary key and the price order was lost (one build; reproduced on tools-universe, 2026-11-12). Use one key per sort, or check the field order in the generated sort input before adding a second. score is first, so it is safe as the primary. For a full scan, { itemId: asc } alone gave stable cursor paging. Note that sorting does not compose predictably with ranking, see below.

In an asc price sort, items without a price come first. Filter them out with exists: true when that matters.

price_default holds one value per variant. For one value per product, sort or filter on defaultVariantPrice_default, lowestVariantPrice_default or highestVariantPrice_default.

Pagination

Use paginationToken (returned as endToken in summary) for efficient, consistent pagination:

{
browse {
product(language: en, pagination: { limit: 25, after: "CURSOR_FROM_PREVIOUS_PAGE" }) {
summary {
totalHits
hasMoreHits
endCursor: endToken
}
hits {
name
path
}
}
}
}

Flow:

  1. First request: omit after
  2. Use summary.endToken as the after value for the next page
  3. Stop when summary.hasMoreHits is false or hits is empty. The last page can still read hasMoreHits: true, and the empty page after it has no endToken to send

pagination accepts limit, after, before and skip. The summary field is endToken; there is no endCursor (alias it if your code expects one).

Note: skip-based pagination is deprecated for ordinary queries. Use cursor-based pagination (after). skip becomes increasingly expensive on large result sets. The exception is ranked queries — see below.

  • Page size: limit: 500 worked on one tenant, and limit: 1000 returned all 540 documents of tools-universe in one page (2026-11-12). No cap was hit below that; page anyway for anything larger.
  • limit is ignored under nearestTo.
  • Many aliased lookups in one request scale badly: batch about 25 aliases per request.
  • A full scan can come back incomplete during re-indexing: four passes over one 590-product tenant returned 173, 590, 556 and 375 hits, with hasMoreHits: false too early. For “every product” (a sitemap, an index), retry, take the union of passes, and check the count against search { summary { totalHits } } (Discovery Indexing).

Faceting

Get counts for filter values. StringFacet takes key and limit; NumberFacet and DateFacet also require boundaries.

{
search(language: en, term: "blue", facets: { shape: { limit: 5 } }) {
summary {
facets
}
hits {
name
path
}
}
}

summary.facets is a Hash, and accepts an optional key argument to pull a single facet out.

  • A selection facet is keyed by the option label, with the key as label (see Generated field names).
  • The topics facet counts every level of the path, and its limit defaults to 10 across all topic maps together: raise it, or the second map’s topics never show.
  • A parentPaths facet on a category listing gives its subfolders with counts.
  • Facets cost about 17 KB per read. Leave them out of rails, menus and anything that doesn’t render filters.

summary.priceRange(priceIdentifier: "default", quantity: 1) { min max } gives the price bounds of the current result set — useful for a range slider that matches the active filters.

Variants on a Hit

Listing filters match a product as soon as different variants satisfy different conditions. To check conditions against one variant at a time, use the variant fields on the hit:

Field Use for
variants(skus:, first:, filter:) The variants that satisfy filter on their own, in product order
variant(selected: [{ attribute, value }]) The first variant carrying every pair: product pages, add to cart
variantGroups(by:, filter:, first:) One group per attribute value, so a listing card shows one colourway each
{
browse {
product(language: en) {
hits {
name
variantGroups(by: ["colour"], filter: { price_default: { range: { lte: 100 } } }, first: 4) {
matched
attributes {
attribute
value
}
representative {
sku
defaultPrice
}
values(of: "size") {
value
sku
inStock
}
}
}
}
}
}

filter is a VariantFilterInput: the variant fields of the listing filter, with exact operators only (no contains, phrase, regex or autocomplete). variantGroups never drops a group or changes hits, facets or pagination: groups with a matching variant come first, the others read matched: false. Attribute names and values are case-sensitive. A key that only matches in another case changes nothing in the result and adds a warning under extensions.warnings.

What a ProductVariantGroup carries (introspected on tools-universe, 2026-11-12):

Field Notes
key, matched, attributes The group’s attribute values; URL-encode key in links
representative(pick:, priceVariant:) DEFAULT (default, else first in stock, else first), FIRST_IN_STOCK, CHEAPEST (for priceVariant), FIRST
summary { count matchedCount inStock(location:) matchedInStock(location:) price(variant:) matchedPrice(variant:) } price is the “from”/“to” range for a card
values(of:) { value sku matched inStock(location:) stock(location:) } One entry per value of another attribute (sizes); alias one stock per location
variants(first:, filter:) The group’s variants
images, videos No arguments: every image of every variant in the group
  • images on a group is the payload trap: it takes no rendition filter and was about 70 % of one listing’s bytes. On a card, use representative { firstImage { variants(types: "webp", minWidth:, maxWidth:) } }. Repeated variants { images } on a 260-size product made 24 cards 8.2 MB ([[responsive-images]]).
  • Product-level variant filters can be satisfied by two different variants. “Red and in size M” matches a product with a red S and a blue M. Use variants(filter:) or variantGroups(filter:) to require one variant.
  • variants(skus:) takes one SKU (String); a comma-separated list returns [] silently. variants is not paginated on the product.
  • Variant components need the generated type: ... on ProductVariantFor<Shape> { <component> }.
  • variant(selected:) answers null when no variant carries every pair. On a product page, feed it the chosen options, then send its sku to the Shop API hydrate.

Prices and stock on a variant

Every price variant and stock location becomes its own set of fields on ProductVariant. For a price variant nok:

Field Gives
nokPrice(count:) The list price (at a quantity, for tiers)
nokPriceTiers, nokPriceTierType Volume tiers
nokPriceFor(marketIdentifiers:, count:) The lowest price for those markets’ price lists
nokBestPriceListFor(marketIdentifiers:) Which list applied (identifier, modifier, modifierType)
nokPriceForEveryone, nokBestPriceListForEveryone Lists aimed at everyone
priceVariants, priceVariantFor(identifier:, marketIdentifiers:) The same by identifier, as a hash or one value
<location>Stock (oslStock), stockLocations Stock per location; stock_<location> to filter
  • Market prices are slow: about 1.4 s per 100 products per market (one tenant). Read them only for the SKUs on screen, never for a whole listing, and cache per market. …PriceForEveryone is slow under build load too.
  • Discovery knows markets only. A price for a specific customer is a Shop API (cart) or Catalogue read, on the server ([[pricing]]).
  • A new stock location or price variant needs a re-ignite before its fields exist (Discovery Indexing).

Paths per language (hreflang, sitemaps)

There is no hreflangs field. The same item’s path in each language comes from one aliased query by itemId (verified on tools-universe, 2026-11-12):

query Paths($id: String!) {
en: search(language: en, filters: { itemId: { equals: $id } }) {
hits {
path
}
}
no: search(language: no, filters: { itemId: { equals: $id } }) {
hits {
path
}
}
sv: search(language: sv, filters: { itemId: { equals: $id } }) {
hits {
path
}
}
}
  • Paths follow the translated names (/drilling-and-driving, /boring-og-skruing), so localised URLs need nothing more. Empty hits in a language means there is no version there: leave that alternate out.
  • A sitemap is one browse (or search) per language joined on itemId.
  • updatedAt is on every hit and is the sitemap’s lastModified. It was the same in every language for the same item on tools-universe.
  • aliases, history and shortcuts are on every hit too: 301 from history after a rename, and keep old paths out of the sitemap. Tenant language codes are not BCP 47 (no → nb). See [[information-architecture]] and [[seo-geo]].

Drafts (publicationState)

publicationState is published (the default) or draft, on search, autocomplete and every browse field. Hits report publicationState, and a draft hit carries the draft’s updatedAt and publishedAt: null.

query Preview($path: String!) {
search(language: en, publicationState: draft, filters: { path: { equals: $path } }) {
hits {
name
path
publicationState
updatedAt
}
}
}

Draft preview is this read, run from a server route behind editor login, and never cached.

On an open Discovery, every draft is public to anyone who asks. No credential is needed: tools-universe returned the same 541 draft documents (publicationState: "draft", publishedAt: null) with and without an access token, on search and browse, in two languages, and another tenant served an unpublished page to an anonymous request (2026-11-12). To keep drafts private, restrict Discovery, re-ignite (see Authentication) and send X-Crystallize-Static-Auth-Token from the server only.

Draft documents are indexed like published ones, so the same eventual consistency applies: a draft saved a moment ago may not be served yet.

Ranking, personalization and similarity

Ranking-enabled tenants additionally accept rankBy, context and nearestTo, and expose rankScore and rankExplain on hits. That surface — vocabularies, setItemTaste, igniteDiscoApi, the five rankBy signals, context.userTaste, nearestTo and the rerank window — is covered by the [[vector-ranking]] skill.

Two things to know from here:

  1. The arguments are absent from the schema until the tenant is served for ranking. Referencing them on an ordinary tenant is a GraphQL validation error, not an unranked result. Detect the capability: { __type(name: "RankByInput") { name } }.
  2. Ranked queries page differently. When a rerank runs over a window, after/before move the window rather than the page — use skip + limit, and remember that skip offsets into a bounded rerank window (options.rerankWindow, default 500, cap 2000). Past the window a page is empty and hasMoreHits is false, even when more documents matched. sorting picks which documents enter the window; the rerank owns the order they come back in.

Profiling

Every query can report how it was served:

{
search(language: en, term: "chair") {
summary {
profiling {
executionTime
queryEngine
collection
webNode
lastIndexCompletedAt
}
}
}
}

lastIndexCompletedAt is the reliable way to confirm a re-index actually landed.

Async Updates

The Discovery API is updated asynchronously from published data, so it is eventually consistent. A content edit usually shows within seconds, but publishing answers before anything is published, new shapes and components need an ignite, schemas roll out over minutes, errors are cached per query body, and relations and media are snapshotted at indexing time. All of it, with what to do, is in Discovery Indexing. The Catalogue API is not the fix for any of it.

Discovery Indexing and Consistency

Discovery is an index built from published content, not a view of it. Most “Discovery is broken” reports in the builds behind this file were indexing behaviour: a publish that had not landed, a schema still rolling out, or an error cached per query body. This file says what is asynchronous, how long it took, and how a storefront and a seed script live with it.

Measured on twelve builds, September to November 2026. Times are what those tenants saw, not guarantees.

The states a tenant goes through

State What Discovery answers
Never ignited HTTP 404 with a plain JSON body, {"success": false, "message": "There is no ignited Tenant for <tenant>."}, not GraphQL errors
Ignited, shape has no discoverable field The shape may have no type (contested: it may also be schema propagation, see below)
Ignite task complete The new schema reaches the nodes over 5-10 minutes, unevenly: some requests see it, others don’t
Serving Published content edits show within seconds; publishes in bulk take minutes

A probe that only looks at errors misses the 404. { __typename } is the cheapest check that a tenant is serving, and summary { profiling { queryEngine lastIndexCompletedAt } } tells which engine answered and when the last full index finished. lastIndexCompletedAt moves on an ignite, not on every publish.

Igniting

igniteDiscoApi(stacks: opensearch) (Core) re-indexes the whole tenant. With stacks: both one tenant’s task completed while profiling.queryEngine stayed atlas-search and ranking never appeared; check queryEngine after the task. Ignites are tenant-wide, so run one at a time and never build a storefront during one.

What needs an ignite (a publish is not enough):

  • New shapes, and new or changed discoverable components on a shape. Republishing the items does not add the field. One build needed a second ignite minutes after the first before a new content chunk appeared.
  • New stock locations and price variants (their <location>Stock, <variant>Price fields and filters).
  • New vocabularies for ranking ([[vector-ranking]]).
  • Removed shapes: their types linger for a few minutes after the task completes.

After an ignite, the schema reaches Discovery’s nodes over minutes. During that window the same query fails on some requests (Cannot query field "inTheBox", Abstract type Document was resolved to a type … that does not exist) and succeeds on others. In one build, 4 of 10 introspection queries saw the new filter type and 6 answered null. The rules:

  1. Wait 5-10 minutes before concluding a type or field is missing, and sample several times.
  2. Ship storefront code that queries a new field only after the field has answered ten times in a row.
  3. Coordinate model changes with deploys: the old code must not break on the new schema, and the new code must not run before the schema is there.

Answers are cached per query body

Discovery caches responses keyed on the query text, and that includes errors. A query that failed during the rollout kept failing verbatim after the index was fine, while the same query with another operation name, another field order or another limit succeeded. Successful answers are cached the same way: one build’s verification query kept answering 333 products for minutes while a renamed query answered the real 377.

So verification scripts vary the operation name (or add a harmless variable) on every call, and a failure right after a change is retested with a changed body before anyone concludes the schema is wrong. A Next.js dev server can also keep serving a failed read from its own cache: restart it.

Publishing is asynchronous

publishItem answers PublishInfo before anything is published. After 527 publishes per language at concurrency 6, 10-35 % of the items still had an older published version several minutes later, and Discovery’s counts kept climbing for about 10 minutes. A few publishItem calls answered success for items that never became published. Republishing at once only adds to the queue.

For a seed or an import:

  1. Publish, then wait until each item’s published version is at least as new as its draft (Core item(id:, language:, versionLabel: published) { … }), and republish only what still lags.
  2. Then check Discovery counts against what you published, with a fresh operation name each time.
  3. Only then ignite, if the run changed the model.

Deleted items linger in Discovery for 1-3 minutes. Unpublishing follows the same path as publishing.

Relations, media and translations are snapshotted at indexing

Discovery stores each document with what it resolved when that document was indexed:

  • Relations resolve when the referencing item is indexed. Collections published in the same run as their new titles came into Discovery with those titles missing, and stayed so until the collections were published again. Publish the targets first (people, products, folders), then the items that point at them, in each language: a title published in no before its people had a Norwegian name listed none of them in no.
  • Images and video: an item published before its image renditions or video playlists existed keeps variants: [], width: null or playlists: [] in Discovery until it is published again. Wait for the media to be processed, then publish ([[media]]).
  • A replaced image (registerImageRevision) shows in Discovery only once the items using it are re-indexed.
  • A component made discoverable after publishing needs a republish (and the ignite above).
  • Bookable products appeared in Discovery about a minute after publish, with no ignite.

Under load

  • HTTP 200 with errors: [{ message: "Response Error" }] came back after about 900 prerendered pages in one build, on different pages each run, and during an ignite. Retry on that message as well as on 429 and 5xx, cap prerender concurrency, or render on demand and cache instead of prerendering every page ([[storefront]]).
  • Totals and replicas flicker during re-indexing. Counts differ between consecutive requests, and a full cursor scan can stop early (hasMoreHits: false at 173 of 590). A complete index (sitemap, feed, llms-full.txt) needs retries, the union of passes, and a check against summary.totalHits.
  • Market price fields (…PriceFor, …PriceForEveryone) are the slowest reads under load; request them only where they are shown.

Fail-safe reads in a storefront

  • Cached reads must never throw. With Next.js 'use cache', a read that throws during warming leaves no entry, and a failing query inside a cached scope breaks background revalidation even when the caller catches it. Return an { error } value with a short cache life instead, and render a fallback.
  • Prefer shape-filtered queries and fragments that tolerate a missing type while a schema rolls out.
  • Revalidate on publish with a Core webhook (concern: items), and expect the Discovery answer to lag the webhook by seconds: revalidate again shortly after, or keep the cache life short for freshly published content ([[mutation]], [[storefront]]).

Checklist after a change

You changed Then
Content of existing items Publish; expect seconds; verify with a fresh operation name
Many items Publish; wait for published ≥ draft per item; republish laggards; check counts
A shape or discoverable field Ignite; wait 5-10 minutes; sample the schema until it answers every time; then deploy code
Stock locations, price variants Ignite, as above
Images or video Wait for renditions or playlists in Core, then publish the items that use them
Related items Publish targets first, then referrers, per language
Deleted items Expect 1-3 minutes before they disappear

Shop API Order Queries Reference

The Shop API /order scope provides queries for retrieving orders. This is a separate endpoint from the /cart scope.

Base URL

https://shop-api.crystallize.com/{tenant-identifier}/order

Important: Order queries use the /order endpoint, NOT /cart.

Authentication

Requires JWT token with the order scope.

Authorization: Bearer YOUR_JWT_TOKEN

See the Shop API Queries Reference for token generation details.

Get a Single Order

Retrieve an order by its Shop API UUID. The argument is UUID!: a variable typed ID or String fails validation. An unknown id answers a GraphQL error, not null, and so can an order created a moment ago, so a confirmation page shows the order that createFromCart returned and retries order(id:) rather than reporting “not found”. Several orders by id in one request (one alias each) worked well.

query GetOrder($id: UUID!) {
order(id: $id) {
id
coreId
reference
type
paymentStatus
createdAt
updatedAt
additionalInformation
customer {
identifier
firstName
lastName
email
phone
companyName
type
addresses {
type
street
city
postalCode
country
}
}
items {
name
sku
productId
quantity
type
imageUrl
price {
gross
net
taxAmount
taxPercent
currency
}
subTotal {
gross
net
taxAmount
currency
}
}
total {
gross
net
taxAmount
taxPercent
currency
discounts {
amount
}
taxBreakdown {
percent
base
amount
}
}
payments {
provider
transactionId
amount
method
createdAt
}
pipelines {
identifier
stage
}
appliedPromotions {
identifier
name
}
meta
metaProperty(key: "fulfillment_status")
}
}

Variables:

{
"id": "order-uuid-here"
}

Get Orders by Customer

Retrieve orders for a specific customer with pagination.

query GetCustomerOrders($customerIdentifier: String!, $limit: Int, $skip: Int) {
orders(customerIdentifier: $customerIdentifier, limit: $limit, skip: $skip) {
id
coreId
type
paymentStatus
createdAt
total {
gross
net
currency
}
items {
name
sku
quantity
price {
gross
net
}
}
pipelines {
identifier
stage
}
}
}

Variables:

{
"customerIdentifier": "john@example.com",
"limit": 100,
"skip": 0
}

Scope this on the server. The JWT is per tenant, not per shopper: orders answers for whatever customerIdentifier it is given. Take the identifier from the session and never from the client. The same holds for subscriptionContracts(customerIdentifier:) on the /subscription-contract endpoint.

limit/skip do not page by date. limit defaults to 10 and the window is taken over the customer’s orders oldest first; only the orders inside it are then sorted newest first. So a default call for a customer with 30 orders answers their ten oldest, not their ten latest. A page can also come back short without being the last: limit: 10 returned 5 orders and then 4 for a customer with 9 in the Tools Universe build. Ask for everything a customer has in one page (limit: 100) rather than walking pages.

For a company or a department there is no query by parent: read the people’s orders and filter on your own meta (the ordering person, the cost centre). A seller or approval queue across customers is a back-office read: Core orders(filter: { meta, pipelineStageIds, customer }) behind staff login, or an index fed by webhooks.

The listing lags, and is sometimes incomplete

orders(customerIdentifier:) reads a second, eventually consistent store. Seen on five builds:

  • New orders appear after seconds to minutes. Six orders created one at a time all listed after about 60 s.
  • Some never appear. 47 orders created at concurrency 4: Core had all 47, the listing showed 29 and stayed there (one tenant). Two hours after an import, limit: 100 returned 6 of 8 and 4 of 5 orders for two customers (another tenant).
  • coreId is null on some orders that have reached Core.

So:

  1. Read what you just wrote by id, never through the listing.
  2. Never use the listing for idempotency (has this seed or webhook already created the order?): it creates duplicates on a quick rerun. Key on your own meta (seedRef) checked by id, keep a ledger, or take a /lock.
  3. The confirmation page and order history say that a new order can take a moment to appear.
  4. A seed checks the listing per customer afterwards and recreates what is missing, rather than trusting one pass.

The Order Store and Core

Shop API orders and Core orders are the same orders in two stores, synced asynchronously in both directions. How an order was created decides how that behaves, and so how a storefront should read it.

An order created with the Shop API stays one order. It gets its coreId in about ten seconds and keeps its Shop id for good: addToStage on the Shop API moves the Core stage too, and an edit, stage change or delete in Core lands on that same order.

An order registered in Core and edited there appears more than once here. It has no Shop id, so every change Core pushes 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. A storefront that sums an order list then counts the same money several times over — the Lab Universe build saw a department budget of NOK 1,249,299 instead of 411,775. deleteOrder in Core removes only the latest copy. Two defences, use both:

  1. Group by coreId and keep the most recently updated copy whenever you read a list. A null coreId is not a group: those orders stay separate.
  2. Change orders through the Shop API (setMeta, addToStage) when a storefront reads them, so no copy is ever made.

So a storefront that lists orders with the Shop API should have them created there, and moved between stages there. Seed demo orders with the Shop API, not with registerOrder: orders registered in Core showed up in the Shop store only sometimes. (Tools Universe.)

Smaller consequences:

  • pipelines comes back as identifiers only ({ identifier, stage }). A storefront that shows a stage name maps the ids to names itself: read them with PIM pipeline.getMany at build time and write them into the storefront’s data, never at runtime.
  • coreId can read null on an order created with Shop create even after it has reached Core. Don’t treat a null coreId as “not synced yet”.
  • meta is a JSON object { key: value }, on orders and on lines, although it is written as [{ key, value }].
  • An order line’s imageUrl is a rendition (…/@200/x.jpeg). Strip the @<width> segment before deriving another size.
  • Orders of type test count toward a promotion’s maxUsagePerCustomer, and Shop orders can’t be deleted, so never test with a demo persona’s identifier.
  • Renewal orders of subscription contracts land in the store that holds the contracts: see [[subscriptions]].
  • Does Core deleteOrder reach the Shop store? Observed both ways: two builds saw the Shop copy stay, one saw it disappear from the listing within a minute. Verify on your tenant before relying on either.

Order Response Types

Order

Field Type Description
id UUID! Shop API order ID
coreId String Core API order ID (for PIM operations)
reference String Order reference number
type OrderType standard, draft, creditNote, etc.
additionalInformation String Free-text additional info
stockLocationIdentifier String Stock location identifier
relatedOrderIds [String] IDs of related orders
createdAt DateTime Creation timestamp
updatedAt DateTime Last update timestamp
context HashMap Order context (pricing, language)
customer Customer Customer details
items [Item] Order line items
total TotalPrice! Order totals
paymentStatus OrderPaymentStatus paid, unpaid, refunded, etc.
payments [Payment] Payment records
pipelines [Pipeline] Pipeline/workflow stage assignments
appliedPromotions [PromotionSlim!] Applied promotion details
meta HashMap All metadata as key-value map
metaProperty(key) String Single metadata value by key

Item (Order Line Item)

Field Type Description
name String! Item display name
sku String Product SKU
productId String Crystallize product ID
quantity PositiveInt Quantity ordered
group String Item grouping
type CartItemType standard, shipping, fee, etc.
imageUrl String Item image URL
price ItemPrice! Unit price
subTotal ItemPrice! Line total (price × quantity)
subscriptionContractId String Subscription contract reference
subscription Subscription Subscription details
meta HashMap Item-level metadata

ItemPrice / TotalPrice

Field Type Description
gross Float! Price including tax
net Float! Price excluding tax
taxAmount Float! Tax amount
taxPercent Float! Tax percentage
currency String! Currency code
discounts [Discount!] Applied discounts

TotalPrice also includes:

Field Type Description
taxBreakdown [TaxBreakdownEntry!] Tax by rate

Customer

Field Type Description
isGuest Boolean! Whether customer is guest
identifier String Unique customer ID
firstName String First name
lastName String Last name
middleName String Middle name
email String Email address
phone String Phone number
birthDate DateTime Date of birth
companyName String Company name
taxNumber String Tax/VAT number
type CustomerType individual or organization
externalReference String External reference
externalReferences HashMap Multiple external refs
addresses [Address] Customer addresses
meta HashMap Customer metadata

Payment

Field Type Description
provider String Payment provider (e.g., “stripe”)
transactionId String Transaction reference
amount Float Payment amount
method String Payment method (e.g., “card”)
createdAt String Payment timestamp
meta HashMap Payment metadata

Pipeline

Field Type Description
identifier String Pipeline identifier
stage String Current stage

Shop API Queries Reference

The Shop API is everything about a shopper: carts, the price for this customer and market, checkout, orders, payments, customers, bookings, subscription contracts and locks. It runs at the edge, from your server only. It is one GraphQL endpoint per route, each with its own schema and scope:

Route Scope
/cart cart
/cart/admin cart and cart:admin (promotions)
/order order
/customer customer
/subscription-contract subscription-contract (and :admin)
/booking/admin booking:admin
/lock lock

Base URL

https://shop-api.crystallize.com/{tenant-identifier}/{route}

The @ before the tenant is optional here. GET https://shop-api.crystallize.com/{tenant-identifier} lists the routes the tenant serves (seven on tools-universe, 2026-11-12), and each route serves a GraphQL playground.

Server only. The Shop API’s CORS allows Crystallize origins and localhost, so a browser call that works in development fails on your own domain (checked 2026-11-12: no Access-Control-Allow-Origin for another origin). The browser keeps the cart id in an httpOnly cookie, and server actions or routes make the calls.

Authentication

The Shop API requires a JWT token. Obtain tokens from:

POST https://shop-api.crystallize.com/{tenant-identifier}/auth/token

Getting a Token

Terminal window
curl -X POST 'https://shop-api.crystallize.com/YOUR_TENANT/auth/token' \
-H 'Accept: application/json' \
-H 'x-crystallize-access-token-id: YOUR_ACCESS_TOKEN_ID' \
-H 'x-crystallize-access-token-secret: YOUR_ACCESS_TOKEN_SECRET' \
-H 'Content-Type: application/json' \
-d '{"scopes":["cart","cart:admin","order"],"expiresIn":18000}'

From a script, send a User-Agent of your own: /auth/token refused Python’s default urllib agent with Cloudflare error 1010 (HTTP 403).

expiresIn is in seconds and defaults to one day in the API; js-api-client asks for 12 hours unless told otherwise. The response is { "success": true, "token": "..." }.

  • The JWT is always for one tenant. An access token pair that isn’t tenant-scoped can mint one for any tenant its user belongs to; a tenant-scoped pair only for its own tenant. Any other tenant answers 400 “User is not a member of tenant X”, even when the user is a member, so check the token’s scope. A plugin bearer token is not read ([[permissions]]).
  • The JWT is per tenant, not per shopper. It reads any customer’s orders and carts, so it never reaches the browser, and the customerIdentifier you pass comes from your session.
  • Cache it on the server and refresh it before it expires. An expired token fails with "exp" claim timestamp check failed; a missing or rejected one answers HTTP 401 with { "success": false, … } and no GraphQL errors.
  • Request a separate token for /subscription-contract. A token with every scope read contracts but answered “Unexpected error” on create; one scoped to subscription-contract (and :admin) worked.
  • The Shop API reads products from the Catalogue with the request’s credentials, and the Shop JWT is not one of them. On a tenant whose Catalogue API requires authentication, send its X-Crystallize-Static-Auth-Token (or its access token pair) as headers on every /cart call that reads a product, hydrate included, next to the Authorization header ([[bookable-resources]]). context.catalogue is not the place: it carries only productVariantMaxAge and productVariantImages (maxCount, renditions { minWidth maxWidth formats }).

Token Scopes

A token needs the scope named after the endpoint it calls. An /admin sub-path needs <scope>:admin as well.

Scope Description
cart Read and manage carts (/cart endpoint)
cart:admin Cart administration and promotions (/cart/admin)
order Create and manage orders (/order endpoint)
customer Read and manage customers (/customer endpoint)
subscription-contract Read and manage contracts (/subscription-contract)
lock Acquire/release locks
booking:admin Booking administration (/booking/admin, with booking)

Using the Token

Include in request headers:

Authorization: Bearer YOUR_JWT_TOKEN

Cart Queries

An unknown id answers a GraphQL error, not null.

Retrieve Cart

query {
cart(id: "cart-id-here") {
id
state
isStale
isExpired
createdAt
updatedAt
items {
lineId
name
quantity
context
variant {
sku
}
images {
url
}
price {
gross
net
taxAmount
}
}
total {
gross
net
taxAmount
}
}
}
  • The SKU sits on variant, not on the item.
  • items.price is the line total (quantity × unit price). The unit price is items.variant.price.
  • items.context is a HashMap holding taxRate, origin (crystallize or external) and managed, so it takes no sub-selection.

Profile data without Core

A storefront that needs per-shopper data (family members, sizes, saved lists) without Core can keep it on a wishlist cart: write it to customer.meta and find the cart again with carts(customerIdentifier:, types: [wishlist], name:). Wishlists never expire.

List Carts

carts lists carts and wishlists. Like orders, it answers for whatever customerIdentifier it is given, so take the identifier from the session.

query {
carts(types: [wishlist], customerIdentifier: "customer@example.com", limit: 20) {
hits {
id
name
updatedAt
}
summary {
totalHits
hasMoreHits
}
}
}

limit defaults to 20 and skip to 0. It also takes states, name, nameContains, updatedAfter, updatedBefore, createdAfter and createdBefore.

Cart as Order Intent

Retrieve a placed cart formatted for order creation:

query {
orderIntent(id: "cart-id-here", format: shop) {
order
cart {
id
total {
gross
net
}
}
}
}

order is a HashMap, so it takes no sub-selection, and it can be pushed to the matching API without transformation. format names that API and defaults to legacy: pass shop for the Shop API create, or core or coreWithOrderV2 for the Core API. A cart that is not in the placed state is refused.

Customer and Subscription Contract Queries

Both follow the same pattern on their own endpoint, with their own scope. The JWT is per tenant, so take the identifier from the session here too.

# POST https://shop-api.crystallize.com/{tenant-identifier}/customer
query {
customer(identifier: "customer@example.com") {
identifier
firstName
lastName
email
addresses {
type
street
city
postalCode
country
}
meta
}
}

/subscription-contract serves subscriptionContract(id:) and subscriptionContracts(customerIdentifier:, limit:, skip:), which answers an empty list when no customerIdentifier is given. Contracts live in one store per tenant, the Shop API (marked experimental) or Core: read them where that tenant writes them. See [[subscriptions]].

Cart Concepts

Hydration

The process where Shop API fetches and computes data on your behalf to construct or update the cart.

Cart Items

Two types of items can be in a cart:

  1. SKU Items - Items with a SKU that exist in Crystallize
  2. External Items - Items that don’t exist in Crystallize (e.g., shipping)

Managed vs Unmanaged Items

  • Managed (true): Shop API fetches info from Crystallize
  • Managed (false): You provide all item information

SKU items start as managed but become unmanaged if you override properties like pricing.

Expiration

  • You can set cart expiration time with context.ttl (30 days by default); every write pushes expiresAt back
  • A cart in the cart state goes stale after context.staleTtl without a write (1 hour by default), and turns abandoned within five minutes
  • Carts are automatically deleted three months after expiresAt. Wishlists never expire


Crystallize AI