Open MercatoDocsSearch docsAPI reference

REST API

Catalog API

Choose the endpoint or command for the part of the catalog you are changing. A product, its variants and its prices have separate identifiers and input shapes.

Open the API Explorer at /docs/api on your Open Mercato instance to inspect request and response schemas or try a call with an API key.

The catalog module exposes both command handlers and REST endpoints under /api/catalog/* (products, variants, prices, price kinds, option schemas, offers, categories, tags, product media, and dictionaries). The commands documented below remain the source of truth for validations and undo metadata, so you can safely script imports, seed data, or build bespoke HTTP wrappers even as new HTTP routes come online.

REST endpoints

Every REST route described below lives in packages/core/src/modules/catalog/api. They share a few guarantees:

/api/catalog/products

Permissions – GET requires catalog.products.view; POST/PUT/DELETE require catalog.products.manage.

Filters

ParamTypePurpose
page, pageSizenumberPagination with a max of 100 rows per page.
searchstringCase-insensitive match on title, subtitle, SKU, handle, or description.
status, isActive, configurablestringFilter by workflow status, activation, or configurability flags.
productTypeenumNarrow the list to one of the CATALOG_PRODUCT_TYPES.
channelId, channelIds, offerIdstringRestrict products bound to a specific channel/offer.
categoryIds, tagIdsstringComma-separated IDs for taxonomy filters.
userId, userGroupId, customerId, customerGroupIdstringScope best-price resolution to a specific audience.
quantity, priceDatenumber/stringProvide context for the pricing service (quantity tiers + date-based prices).
sortField, sortDirstringSort by title, SKU, createdAt, or updatedAt.
withDeletedbooleanInclude soft-deleted products.
customFieldsetstringEnsure the backend interprets cf_* filters using the selected fieldset.

The resolver decorates each item with:

Mutations – POST and PUT accept exactly the shapes validated by productCreateSchema/productUpdateSchema. DELETE requires a payload with { id } and delegates to catalog.products.delete, performing a soft delete.

/api/catalog/products/bulk-create

Permissions – POST requires catalog.products.manage. Registered mutation guards run for catalog.product/create before the batch is enqueued, so a guard that blocks a single product create blocks the bulk one too; the guarded unit is the batch envelope ({ bulk: true, itemCount }), not the individual rows, because the rows are created later by a queue worker that has no request to offer a guard.

Accepts { items: ProductBulkCreateRow[] }, each row validated by productBulkCreateRowSchema (productCreateSchema without organizationId/tenantId). The batch holds 1–2,000 rows – a lower cap than the categories endpoint's 10,000, because a product row carries offers, category links, tags, and compliance fields and therefore costs far more per row to enqueue and process. Returns 202 Accepted with { progressJobId } immediately; the batch runs asynchronously on a catalog-product-bulk-create queue worker, reporting progress via the Progress module (jobType: 'catalog.products.bulk_create') and checkpointing every 20 rows so an interrupted run resumes without re-creating already-completed rows. Cancellation is honored on the same 20-row boundary.

Resume is keyed on the row's SKU or handle, and only on those: the job records which rows already had a taken SKU or handle when it first started, so a resumed attempt can tell a product it created from one that was there all along, and reclaims the former instead of re-creating it or reporting it as a sku_taken conflict against itself. A row that carries neither a SKU nor a handle has nothing unique to match on, so if the job is interrupted after creating it but before the next checkpoint, the resumed attempt creates it again – matching such a row on title would be worse, since titles are not unique and the row could silently claim an unrelated product and drop itself from the batch. The snapshot is taken once, so a product created by anything else – a concurrent bulk job, a single POST, a sync adapter – between the job's first attempt and the resumed one is indistinguishable from one this job created, and the matching row reports itself as created with that foreign id. The window is the gap between attempts; if that matters for your import, run it when nothing else writes the same SKUs or handles.

Each row is created by calling the unchanged catalog.products.create command once per row – no bulk-only creation path, so every side effect (events, custom fields, audit log) is identical to a single POST /api/catalog/products call. Before calling the command, the worker fails rows with a SKU or handle that already exists (in the database or earlier in the same batch) without a DB round-trip through the command; other row-level errors (e.g. a validation failure inside the command) are caught per row and collected. The job's resultSummary on completion is { createdCount, failedCount, createdIds, failedItems: [{ index, title, code, message }] }, where code is one of sku_taken, handle_taken, or command_failed and is the stable identifier to branch on (message is human-readable prose and may change). createdCount + failedCount always equals items.length. A resumed run's counts cover the whole batch; its createdIds lists the products the resumed attempt created plus the ones it could reclaim by SKU or handle, because the checkpoint deliberately persists counts rather than the growing id list (ProgressJob.meta is rewritten and broadcast on every checkpoint, so nothing that grows with the batch belongs in it). On a resumed run createdIds.length can therefore be smaller than createdCount – by however many rows a durable checkpoint had already counted, which is none when the interrupted attempt died before its first one: iterate it for the ids it does carry, but never treat its length as the number of rows created. A cancelled job reports its partial summary under meta.resultSummary rather than resultSummary, because the progress module only writes the resultSummary column on completion or failure. A rejected payload returns 400 with an errors array of { path, message } for the first 20 schema issues.

/api/catalog/variants

Permissions – GET requires catalog.products.view; writes require catalog.variants.manage.

Filters

ParamTypePurpose
page, pageSizenumberPagination (≤100 per page).
searchstringMatch variant name, sku, or barcode.
productId, skustringFilter to a specific product or exact SKU.
isActive, isDefault, withDeletedstring/booleanToggle core flags or include soft-deleted rows.
sortField, sortDirstringSort by name, sku, createdAt, or updatedAt.
cf_*stringApply custom-field filters (scoped to the caller's tenant).

Responses include option values, dimensions, metadata, and flattened custom fields. POST/PUT payloads must satisfy variantCreateSchema/variantUpdateSchema; DELETE accepts { id } and calls catalog.variants.delete.

/api/catalog/prices

Permissions – GET requires catalog.products.view; mutations require catalog.pricing.manage.

Filters

ParamTypePurpose
page, pageSizenumberPagination.
productId, variantId, offerIdstringScope prices tied to a specific record.
channelId, currencyCodestringFilter by channel or ISO currency code.
priceKindId, kindstringRestrict by price kind or price kind code.
userId, userGroupId, customerId, customerGroupIdstringFilter by personalized price audiences.
withDeletedbooleanInclude rows even if the associated product/variant was soft deleted.
sortField, sortDirstringSort by currency, price kind, quantity band, createdAt, or updatedAt.
cf_*stringCustom-field filters/ordering helpers.

POST/PUT reuse priceCreateSchema/priceUpdateSchema so the HTTP route mirrors the command bus. DELETE forwards { id } to catalog.prices.delete. Responses expose raw catalog_product_price columns plus any associated custom fields.

/api/catalog/price-kinds

Permissions – all methods require catalog.settings.manage.

Filters

ParamTypePurpose
page, pageSizenumberPagination.
searchstringCase-insensitive match on code or title.
isPromotion, isActivestringFilter by promotion/activation flags (true/false).
sortField, sortDirstringSort by code, title, display mode, currency, createdAt, or updatedAt.

POST and PUT translate inputs through priceKindCreateSchema/priceKindUpdateSchema and return { id }/{ ok: true }. DELETE expects { id } and soft deletes the price kind.

/api/catalog/option-schemas

Permissions – GET requires catalog.products.view; writes require catalog.settings.manage.

Filters

ParamTypePurpose
page, pageSizenumberPagination.
idstringFetch a specific schema template.
searchstringMatch name or description.
isActive, withDeletedstring/booleanFilter by activation or include soft-deleted templates.
cf_*stringApply custom-field filters stored on option schemas.

Responses surface the saved schema JSON alongside metadata. POST/PUT wrap optionSchemaTemplateCreateSchema/optionSchemaTemplateUpdateSchema; DELETE forwards { id } to catalog.optionSchemas.delete.

/api/catalog/offers

Permissions – all methods require sales.channels.manage because offers tie catalog products to sales channels.

Filters

ParamTypePurpose
page, pageSizenumberPagination.
productId, idstringLimit offers for a given product or offer.
channelId, channelIdsstringFilter by one channel or a comma-separated list.
searchstringMatch offer title/description.
isActive, withDeletedstring/booleanRestrict by activation or include soft-deleted offers.
sortField, sortDirstringSort by title, createdAt, or updatedAt.

List responses embed:

POST/PUT feed offerCreateSchema/offerUpdateSchema; DELETE resolves { id } through catalog.offers.delete.

/api/catalog/categories

Permissions – GET requires catalog.categories.view; writes require catalog.categories.manage.

GET accepts:

ParamTypePurpose
viewenum (manage/tree)manage returns paginated rows flattened from the tree; tree returns nested nodes.
page, pageSizenumberPagination (manage view only).
searchstringMatch category names or breadcrumb labels.
statusenum (all/active/inactive)Filter by activation flag.
idsstringComma-separated category IDs to focus on specific nodes.

manage view rows include hierarchy metadata (depth, parent, child counts, breadcrumb labels) plus any custom-field values resolved via loadCustomFieldValues. tree view collapses the same hierarchy into nested children[].

POST, PUT, and DELETE route payloads through categoryCreateSchema, categoryUpdateSchema, and catalog.categories.delete respectively.

/api/catalog/categories/bulk-create

Permissions – POST requires catalog.categories.manage.

Accepts { items: CategoryBulkCreateRow[] } (1–10,000 rows, each validated by categoryBulkCreateRowSchema – categoryCreateSchema without organizationId/tenantId). Returns 202 Accepted with { progressJobId } immediately; the batch runs asynchronously on a catalog-category-bulk-create queue worker, reporting progress via the Progress module (jobType: 'catalog.categories.bulk_create') and checkpointing every 20 rows so an interrupted run resumes without re-creating already-completed rows. Cancellation is honored on the same 20-row boundary. Registered mutation guards run for catalog.category/create before the batch is enqueued, on the batch envelope rather than the individual rows.

Resume is keyed on the row's slug, and only on the slug: the job records which rows already had a taken slug when it first started, so a resumed attempt can tell a category it created from one that was there all along, and reclaims the former instead of re-creating it or reporting it as a slug_taken conflict against itself. A row without a slug has nothing unique to match on – name carries no uniqueness constraint – so if the job is interrupted after creating it but before the next checkpoint, the resumed attempt creates it again rather than risk claiming an unrelated category and dropping the row from the batch. The snapshot is taken once, so a category created by anything else – a concurrent bulk job, a single POST, a sync adapter – between the job's first attempt and the resumed one is indistinguishable from one this job created, and the matching row reports itself as created with that foreign id. The window is the gap between attempts; if that matters for your import, run it when nothing else writes the same slugs.

Each row is created by calling the unchanged catalog.categories.create command once per row – the same events and side effects as a single POST /api/catalog/categories call. Before calling the command, the worker fails rows with a slug that already exists or a parentId that doesn't resolve, without a DB round-trip through the command; other row-level errors are caught per row and collected. The job's resultSummary on completion is { createdCount, failedCount, createdIds, failedItems: [{ index, name, code, message }] }, where code is one of slug_taken, parent_not_found, or command_failed and is the stable identifier to branch on (message is human-readable prose and may change). createdCount + failedCount always equals items.length. A resumed run's counts cover the whole batch; its createdIds lists the categories the resumed attempt created plus the ones it could reclaim by slug, because the checkpoint deliberately persists counts rather than the growing id list (ProgressJob.meta is rewritten and broadcast on every checkpoint, so nothing that grows with the batch belongs in it). On a resumed run createdIds.length can therefore be smaller than createdCount – by however many rows a durable checkpoint had already counted, which is none when the interrupted attempt died before its first one: iterate it for the ids it does carry, but never treat its length as the number of rows created. A cancelled job reports its partial summary under meta.resultSummary rather than resultSummary, because the progress module only writes the resultSummary column on completion or failure. A rejected payload returns 400 with an errors array of { path, message } for the first 20 schema issues.

/api/catalog/tags

Permissions – GET requires catalog.products.view.

Query parameters: search, page, and pageSize. The handler enforces organization scope and returns { items, total }, where each item exposes id, label, slug, createdAt, and updatedAt.

/api/catalog/product-media

Permissions – GET requires catalog.products.view.

Query: productId (UUID, required). The route validates scope, loads attachment rows for the product, and returns { items: [{ id, fileName, url, thumbnailUrl }] }. Thumbnails are precomputed via buildAttachmentImageUrl for UI galleries.

/api/catalog/dictionaries/:key

Permissions – GET requires catalog.products.manage.

Path parameter :key accepts currency, currencies, unit, units, or measurement_units (aliases are normalized). The route resolves the matching dictionary for the caller's organization/tenant and returns { id, entries: [{ id, value, label, color, icon }] }. Use it to hydrate selectors that need shared catalog dictionaries without duplicating the dictionaries module API.

Running catalog commands

import { createRequestContainer } from '@/lib/di/container'
import type { CommandBus } from '@open-mercato/shared/lib/commands'

const container = await createRequestContainer()
const commandBus = container.resolve<CommandBus>('commandBus')

await commandBus.execute('catalog.products.create', {
  input: {
    organizationId,
    tenantId,
    name: 'Starter T-Shirt',
    code: 'tee-basic',
    primaryCurrencyCode: 'USD',
    metadata: { category: 'apparel' },
    customFields: { material: 'cotton' }
  },
  ctx: { auth, container }
})

Product commands – catalog.products.*

Handlers live in packages/core/src/modules/catalog/commands/products.ts.

Command idPurposeSchema
catalog.products.createCreate a product master recordproductCreateSchema (packages/core/src/modules/catalog/data/validators.ts:18)
catalog.products.updatePatch an existing product (only provided keys are updated)productUpdateSchema (packages/core/src/modules/catalog/data/validators.ts:32)
catalog.products.deleteSoft delete a product once variants/prices are cleaned upn/a (requires before.id in the undo snapshot)

Key fields from productCreateSchema:

Example payload:

{
  "organizationId": "3d552375-7813-4e9d-8807-0283c907a9f9",
  "tenantId": "a2c6e50e-a6ef-4c7a-afe4-7b6f1998b5c2",
  "name": "Starter T-Shirt",
  "code": "tee-basic",
  "primaryCurrencyCode": "USD",
  "attributeSchemaId": "edc95a4d-9fb9-4cbc-b8ce-1b93af2c8e83",
  "attributeSchema": {
    "definitions": [
      { "key": "material", "label": "Material", "kind": "text" }
    ]
  },
  "offers": [
    { "channelId": "bf5efc35-c493-44e4-9307-5f50331a7405", "title": "Online store" }
  ],
  "isConfigurable": true,
  "metadata": { "category": "apparel" },
  "customFields": { "material": "cotton" }
}

Variant commands – catalog.variants.*

Defined in packages/core/src/modules/catalog/commands/variants.ts.

Command idPurposeSchema
catalog.variants.createCreate a SKU tied to a productvariantCreateSchema (packages/core/src/modules/catalog/data/validators.ts:39)
catalog.variants.updatePatch variant attributes, dimensions, or option selectionsvariantUpdateSchema (packages/core/src/modules/catalog/data/validators.ts:65)
catalog.variants.deleteRemove a variant after ensuring there are no prices or option linksn/a (id provided through undo payload)

Highlights from variantCreateSchema:

Price commands – catalog.prices.*

Stored in packages/core/src/modules/catalog/commands/prices.ts.

Command idPurposeSchema
catalog.prices.createAdd a price row for a variantpriceCreateSchema (packages/core/src/modules/catalog/data/validators.ts:273)
catalog.prices.updateUpdate price attributespriceUpdateSchema (packages/core/src/modules/catalog/data/validators.ts:298)
catalog.prices.deleteRemove a price entryn/a

Key fields:

Shared tax calculation service

All price commands and the admin builders call the DI-provided taxCalculationService (registered by the Sales module) to keep net/gross/tax amounts consistent. The default implementation looks up the requested tax class (taxRateId) or explicit rate, normalizes non-negative inputs, and stores computed unitPriceNet, unitPriceGross, and taxAmount back on the catalog_product_prices row.

You can override/extend the calculation pipeline via the event bus:

Example hook (run from any module bootstrap/registrar):

import { createRequestContainer } from '@/lib/di/container'

const container = await createRequestContainer()
const eventBus = container.resolve('eventBus')

eventBus?.on('sales.tax.calculate.before', ({ input, setInput }) => {
  if (!input.taxRateId && input.organizationId === 'org-brazil') {
    setInput({ taxRateId: 'default-brazilian-rate' })
  }
})

eventBus?.on('sales.tax.calculate.after', ({ result, setResult }) => {
  if (result && result.taxAmount > 0) {
    setResult({ ...result, taxAmount: Math.ceil(result.taxAmount * 100) / 100 })
  }
})

Prefer taxRateId over raw percentages so the service can validate scope and reuse the Sales → Tax Rates admin UI.

Price kind commands – catalog.priceKinds.*

Stored in packages/core/src/modules/catalog/commands/priceKinds.ts.

Command idPurposeSchema
catalog.priceKinds.createRegister a reusable price kindpriceKindCreateSchema (packages/core/src/modules/catalog/data/validators.ts:258)
catalog.priceKinds.updateAdjust labels, display mode, currency, or promotion flagspriceKindUpdateSchema (packages/core/src/modules/catalog/data/validators.ts:271)
catalog.priceKinds.deleteSoft delete a price kind after ensuring no prices reference itn/a

Custom field fieldsets

Catalog products and variants no longer ship their own “attribute schema” concept. Instead they rely on the shared custom-fields engine and the CustomFieldEntityConfig fieldset metadata that is edited from Entities → System entities → catalog.catalog_product (and catalog.catalog_product_variant). Compose as many fieldsets as you need – e.g. fashion, equipment, services – and assign custom fields plus per-field groups within each set. The generated UI automatically scopes the editors, CRUD forms, and filters to the currently selected fieldset.

Key details:

Customising price selection

All API surfaces that need “best price” calculations resolve the DI token catalogPricingService, which wraps resolveCatalogPrice() from packages/core/src/modules/catalog/lib/pricing.ts. The helper emits catalog.pricing.resolve.before and catalog.pricing.resolve.after events and walks a prioritized hook registry, falling back to the built-in layered selection (selectBestPrice) when no hook handles the request.

You can plug in custom logic (e.g., loyalty tiers, partner overrides) by registering a resolver from any module initialization file:

import { registerCatalogPricingResolver } from '@open-mercato/core/modules/catalog/lib/pricing'

registerCatalogPricingResolver(
  async (rows, ctx) => {
    // rows: all matching CatalogProductPrice rows (with populated offer/variant/product)
    // ctx: PricingContext (channelId, userId, quantity, date, etc.)
    const partnerPrice = rows.find((row) => row.metadata?.partner === ctx.customerId)
    if (partnerPrice) return partnerPrice
    return undefined // fall back to the next resolver / default algorithm
  },
  { priority: 100 },
)

Feature flags

RBAC gates for REST/UX surfaces are declared in packages/core/src/modules/catalog/acl.ts:1:

Grant these to API keys or roles you intend to use with wrapper endpoints so future upgrades continue to respect access boundaries.


You can call the command bus directly or go through the REST endpoints above – the schemas listed here ensure imports, integrations, and tests remain aligned with the core module.

Previous: Cart API · Next: Customers API