REST 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.
Every REST route described below lives in packages/core/src/modules/catalog/api. They share a few guarantees:
metadata export.{ items, total, page, pageSize, totalPages } responses and accept both cf_<key> and cf:<key> filters emitted by the custom-field engine./api/catalog/productsPermissions – GET requires catalog.products.view; POST/PUT/DELETE require catalog.products.manage.
Filters
| Param | Type | Purpose |
|---|---|---|
page, pageSize | number | Pagination with a max of 100 rows per page. |
search | string | Case-insensitive match on title, subtitle, SKU, handle, or description. |
status, isActive, configurable | string | Filter by workflow status, activation, or configurability flags. |
productType | enum | Narrow the list to one of the CATALOG_PRODUCT_TYPES. |
channelId, channelIds, offerId | string | Restrict products bound to a specific channel/offer. |
categoryIds, tagIds | string | Comma-separated IDs for taxonomy filters. |
userId, userGroupId, customerId, customerGroupId | string | Scope best-price resolution to a specific audience. |
quantity, priceDate | number/string | Provide context for the pricing service (quantity tiers + date-based prices). |
sortField, sortDir | string | Sort by title, SKU, createdAt, or updatedAt. |
withDeleted | boolean | Include soft-deleted products. |
customFieldset | string | Ensure the backend interprets cf_* filters using the selected fieldset. |
The resolver decorates each item with:
offers: channel-level offers resolved from CatalogOffer.pricing: the return value of catalogPricingService.resolvePrice, including the matching price kind, amounts, and scope (variant/offer/channel/audience IDs).cf: keys are stripped).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-createPermissions – 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/variantsPermissions – GET requires catalog.products.view; writes require catalog.variants.manage.
Filters
| Param | Type | Purpose |
|---|---|---|
page, pageSize | number | Pagination (≤100 per page). |
search | string | Match variant name, sku, or barcode. |
productId, sku | string | Filter to a specific product or exact SKU. |
isActive, isDefault, withDeleted | string/boolean | Toggle core flags or include soft-deleted rows. |
sortField, sortDir | string | Sort by name, sku, createdAt, or updatedAt. |
cf_* | string | Apply 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/pricesPermissions – GET requires catalog.products.view; mutations require catalog.pricing.manage.
Filters
| Param | Type | Purpose |
|---|---|---|
page, pageSize | number | Pagination. |
productId, variantId, offerId | string | Scope prices tied to a specific record. |
channelId, currencyCode | string | Filter by channel or ISO currency code. |
priceKindId, kind | string | Restrict by price kind or price kind code. |
userId, userGroupId, customerId, customerGroupId | string | Filter by personalized price audiences. |
withDeleted | boolean | Include rows even if the associated product/variant was soft deleted. |
sortField, sortDir | string | Sort by currency, price kind, quantity band, createdAt, or updatedAt. |
cf_* | string | Custom-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-kindsPermissions – all methods require catalog.settings.manage.
Filters
| Param | Type | Purpose |
|---|---|---|
page, pageSize | number | Pagination. |
search | string | Case-insensitive match on code or title. |
isPromotion, isActive | string | Filter by promotion/activation flags (true/false). |
sortField, sortDir | string | Sort 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-schemasPermissions – GET requires catalog.products.view; writes require catalog.settings.manage.
Filters
| Param | Type | Purpose |
|---|---|---|
page, pageSize | number | Pagination. |
id | string | Fetch a specific schema template. |
search | string | Match name or description. |
isActive, withDeleted | string/boolean | Filter by activation or include soft-deleted templates. |
cf_* | string | Apply 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/offersPermissions – all methods require sales.channels.manage because offers tie catalog products to sales channels.
Filters
| Param | Type | Purpose |
|---|---|---|
page, pageSize | number | Pagination. |
productId, id | string | Limit offers for a given product or offer. |
channelId, channelIds | string | Filter by one channel or a comma-separated list. |
search | string | Match offer title/description. |
isActive, withDeleted | string/boolean | Restrict by activation or include soft-deleted offers. |
sortField, sortDir | string | Sort by title, createdAt, or updatedAt. |
List responses embed:
product: a lightweight snapshot (id, title, default media, SKU).prices: prices attached directly to the offer (with price kind metadata).productChannelPrice: fallback product-level price for the requested channel.POST/PUT feed offerCreateSchema/offerUpdateSchema; DELETE resolves { id } through catalog.offers.delete.
/api/catalog/categoriesPermissions – GET requires catalog.categories.view; writes require catalog.categories.manage.
GET accepts:
| Param | Type | Purpose |
|---|---|---|
view | enum (manage/tree) | manage returns paginated rows flattened from the tree; tree returns nested nodes. |
page, pageSize | number | Pagination (manage view only). |
search | string | Match category names or breadcrumb labels. |
status | enum (all/active/inactive) | Filter by activation flag. |
ids | string | Comma-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-createPermissions – 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/tagsPermissions – 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-mediaPermissions – 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/:keyPermissions – 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.
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 }
})
ensureTenantScope/ensureOrganizationScope (packages/core/src/modules/catalog/commands/shared.ts:42).customFields object or prefixed keys (cf_color); handlers call parseWithCustomFields and setCustomFieldsIfAny to persist values (packages/core/src/modules/catalog/commands/products.ts:100).catalog.products.*Handlers live in packages/core/src/modules/catalog/commands/products.ts.
| Command id | Purpose | Schema |
|---|---|---|
catalog.products.create | Create a product master record | productCreateSchema (packages/core/src/modules/catalog/data/validators.ts:18) |
catalog.products.update | Patch an existing product (only provided keys are updated) | productUpdateSchema (packages/core/src/modules/catalog/data/validators.ts:32) |
catalog.products.delete | Soft delete a product once variants/prices are cleaned up | n/a (requires before.id in the undo snapshot) |
Key fields from productCreateSchema:
organizationId, tenantId – required scope identifiers.name (string, ≤255), optional description.code (lowercase slug), statusEntryId, primaryCurrencyCode, defaultUnit, attributeSchemaId reference, attributeSchema JSON override, attributeValues map, and offers (array of { channelId, title, description }) that bind products to sales channels. When attributeSchemaId is provided, the product inherits a shared schema template; providing attributeSchema in the same payload overwrites individual fields for that single product without mutating the shared template.defaultMediaId / defaultMediaUrl – optional attachment handle + its SEO-friendly relative image URL for the primary product media. Upload images via /api/attachments, then resolve responsive URLs with buildAttachmentImageUrl(id, { width, height, slug }) or by calling /api/attachments/image/{id}/{slug} directly for server-side resizing.isConfigurable, isActive, plus arbitrary metadata JSON.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" }
}
catalog.variants.*Defined in packages/core/src/modules/catalog/commands/variants.ts.
| Command id | Purpose | Schema |
|---|---|---|
catalog.variants.create | Create a SKU tied to a product | variantCreateSchema (packages/core/src/modules/catalog/data/validators.ts:39) |
catalog.variants.update | Patch variant attributes, dimensions, or option selections | variantUpdateSchema (packages/core/src/modules/catalog/data/validators.ts:65) |
catalog.variants.delete | Remove a variant after ensuring there are no prices or option links | n/a (id provided through undo payload) |
Highlights from variantCreateSchema:
organizationId, tenantId, productId.name, sku, barcode, statusEntryId, isDefault, isActive.dimensions.width/height/depth/unit, weightValue, weightUnit).optionValues map keyed by option code to capture selections directly on the variant payload (also extracted from metadata.optionValues for backward compatibility).catalog.prices.*Stored in packages/core/src/modules/catalog/commands/prices.ts.
| Command id | Purpose | Schema |
|---|---|---|
catalog.prices.create | Add a price row for a variant | priceCreateSchema (packages/core/src/modules/catalog/data/validators.ts:273) |
catalog.prices.update | Update price attributes | priceUpdateSchema (packages/core/src/modules/catalog/data/validators.ts:298) |
catalog.prices.delete | Remove a price entry | n/a |
Key fields:
variantId, organizationId, tenantId, and priceKindId.currencyCode (ISO-4217) with optional price kind currency override.minQuantity, maxQuantity.unitPriceNet, unitPriceGross, taxRate.startsAt, endsAt (coerced to Date by Zod).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:
sales.tax.calculate.before – receives { input, setInput(next), setResult(result) }. Call setInput() to tweak the pending payload (e.g., swap the taxRateId based on the customer/region) or setResult() to bypass the built-in calculator entirely.sales.tax.calculate.after – receives { input, result, setResult(next) }. Use this to post-process the computed numbers (rounding, recoverable VAT adjustments, etc.).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.
catalog.priceKinds.*Stored in packages/core/src/modules/catalog/commands/priceKinds.ts.
| Command id | Purpose | Schema |
|---|---|---|
catalog.priceKinds.create | Register a reusable price kind | priceKindCreateSchema (packages/core/src/modules/catalog/data/validators.ts:258) |
catalog.priceKinds.update | Adjust labels, display mode, currency, or promotion flags | priceKindUpdateSchema (packages/core/src/modules/catalog/data/validators.ts:271) |
catalog.priceKinds.delete | Soft delete a price kind after ensuring no prices reference it | n/a |
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:
custom_field_entity_configs and is exposed through /api/entities/definitions?entityId=…. The request accepts ?fieldset=<code> to filter definitions server-side; the admin UI calls this automatically when the user switches fieldsets.catalog_products) and variants (catalog_product_variants) persist the chosen fieldset in the custom_fieldset_code column. Awilix commands and CRUD handlers already accept a customFieldsetCode property so you can capture that selection from bespoke flows.customFieldset=<code> query parameter so filters and the query engine interpret cf_* filters using the right definition set. The backend uses buildCustomFieldFiltersFromQuery(..., { fieldset }) to scope validation and coercion.collectCustomFieldValues, crud.create/update payloads, entity definitions UI) apply without a bespoke schema layer. Old attribute schema endpoints/tests have been removed; the existing migrations (up to Migration20251116183727) take care of dropping the template tables and extra JSON columns.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 },
)
0); return undefined to defer to the next handler.null stops the pipeline and instructs callers that no price applies.selectBestPrice) still runs last so existing behaviour remains unless you override it.catalog.pricing.resolve.before|after (each payload exposes rows, context, result, and setResult, mirroring the sales calculation hooks).catalogPricingService via DI if you need to replace the pipeline wholesale.RBAC gates for REST/UX surfaces are declared in packages/core/src/modules/catalog/acl.ts:1:
catalog.products.view / catalog.products.managecatalog.variants.managecatalog.pricing.managecatalog.settings.manageGrant 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.