Variant Group

View as Markdown

Variant Group

A variant group is a collection of variants that share the same linked content types. For example, a Colors group holds the variants White and Black. The VariantGroup class manages the variant groups of one stack through the Content Management API (CMA). Use this class to

  • list and create the variant groups of a stack
  • rename a variant group, and link or unlink content types
  • delete a variant group
  • open the variants of one group through the Variants class

Call the variantGroup method of a Stack object to get an object, for example stack.variantGroup('<VARIANT_GROUP_UID>').

Instance State

  • Call variantGroup() without a UID to work with all the variant groups of the stack, for example create and query.
  • Call variantGroup('<VARIANT_GROUP_UID>') to work with one variant group, for example update and variants.
  • Each form has only its own methods, except the three header methods. update is undefined on variantGroup(), and create is undefined on variantGroup('<VARIANT_GROUP_UID>'), so calling the wrong one throws TypeError.
  • The objects in the items of query().find() are the single-group form. create and update resolve to plain data, not to VariantGroup objects.

Warning variantGroup('') returns the collection form, because the SDK treats an empty string as no UID. Check the UID before you build the object.

Class-Level Notes

Headers.

Personalize.

  • When a Personalize experience uses a variant group, Personalize owns the group name, its variants and the personalize_metadata object, as the Variant Groups API reference states. This class cannot change those properties.

Rate limiting and retry.

  • This SDK automatically retries on 429 with configurable delay and attempt limits.

Additional Resource For more information on the retry options and their defaults, refer to the Contentstack documentation.

Capability Matrix

CapabilitySupportedNotes / Alternative
Fetch one variant group by UIDNoCall query, then pick the item whose uid matches
Get a VariantGroup object back from create or updateNoBoth resolve to plain data. Call stack.variantGroup(group.uid) for an object

Method Index

Work with the variant groups of a stack. Available on stack.variantGroup().

Method NameReturnsDescription
queryA query for variant groups, sent when you call find(), findOne() or count().Builds a variant group query.
createThe new variant group, as plain data.Creates a variant group.

Change one variant group. Available on stack.variantGroup('<VARIANT_GROUP_UID>').

Method NameReturnsDescription
updateThe updated variant group, as plain data.Renames the group or links content types.
deleteThe API response with a notice.Deletes the group and its variants.
variantsA new variants object.Opens the variants of the group.

Set request headers. Available on both forms.

Method NameReturnsDescription
addHeaderThe same variant group, for chaining.Adds one request header.
addHeaderDictThe same variant group, for chaining.Adds several request headers.
removeHeaderThe same variant group, for chaining.Removes one request header.

Class-Level Snippet

The snippet below creates a variant group for one content type, adds a variant to it, and lists the variants of the group.

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const group = await stack.variantGroup().create({
    name: 'docs-test-colors',
    content_types: ['<CONTENT_TYPE_UID>']
  })

  await stack.variantGroup(group.uid).variants().create({ name: 'docs-test-white' })

  const result = await stack.variantGroup(group.uid).variants().query().find()
  for (const variant of result.items) {
    console.log(variant.uid, variant.name)
  }
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

Methods

Each method of the VariantGroup class has its own section below, with its parameters, validation rules, behavior, and examples.

addHeader

addHeader adds one header to every request that this variant group object sends.

NameTypeDescription
key (required)string

Header name, for example x-request-id.

Default: Not applicable
value (required)string

Header value to send.

Default: Not applicable

Returns: VariantGroup. The same variant group, for chaining.

Validation

  • There is no client-side validation. A null or undefined key leaves the headers unchanged, and addHeader returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. addHeader sends no request.
  • Until its first header change, this object shares the header map of the stack, so a header that you add to the stack also reaches it. The first change copies that map. From then on, changes apply to this object only, not to the stack or to its other objects.
  • Every request method of this object sends its headers. A key that the object already holds gets the new value.
  • variants passes the headers of this object on to the Variants object it returns. Change the headers first, then call it.

Example

Basic usage: tag the requests of one variant group object

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const variantGroup = stack.variantGroup('<VARIANT_GROUP_UID>').addHeader('x-request-id', 'docs-123')
// Every request this object sends from now on carries the header
console.log(variantGroup.stackHeaders['x-request-id'])

addHeaderDict

addHeaderDict adds several headers to every request that this variant group object sends.

NameTypeDescription
headerDict (required)object

Header names and values to add.

Default: Not applicable

Returns: VariantGroup. The same variant group, for chaining.

Validation

  • There is no client-side validation. A null value, or a value that is not an object, leaves the headers unchanged, and addHeaderDict returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. addHeaderDict sends no request.
  • Copies every key of headerDict into the headers of this object. A key that the object already holds gets the new value.
  • The first header change on this object copies the header map that it shares with the stack. The change then applies to this object only.

Example

Basic usage: send two extra headers from one variant group object

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const variantGroup = stack.variantGroup('<VARIANT_GROUP_UID>')
  .addHeaderDict({ 'x-request-id': 'docs-123', 'x-trace-id': 'docs-456' })
// Every request this object sends from now on carries both headers
console.log(variantGroup.stackHeaders)

create

create creates a variant group in the stack from the details you pass.

NameTypeDescription
data (required)object

Request body with the variant group details.

Default: Not applicable
data.name (required)string

Unique name of the variant group.

Default: Not applicable
data.uidstring

Custom unique ID. You cannot change it later.

Default: API default (generated UID)
data.descriptionstring

Description of the variant group.

Default: API default
data.content_typesstring[]

UIDs of the content types to link.

Default: API default

Returns: Promise<Response>. The new variant group, as plain data.

Validation

  • There is no client-side validation. create sends data as the JSON body as it is, without a wrapper key.
  • create exists only on variantGroup(). On variantGroup('<VARIANT_GROUP_UID>') it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends POST /v3/variant_groups with data as the body, as Create variant group describes.
  • Resolves to the response body as plain data, not to a VariantGroup object. Call stack.variantGroup(group.uid) to work with the new group.
  • The API reference notes that the Variants feature might not be available to your organization by default.

Example

Basic usage: create a variant group

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const group = await stack.variantGroup().create({ name: 'docs-test-colors' })
  console.log(group.uid, group.name)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: create a variant group with a custom UID and a linked content type

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const group = await stack.variantGroup().create({
    name: 'docs-test-colors',
    uid: 'docs_test_colors',
    description: 'Color variants for product pages',
    content_types: ['<CONTENT_TYPE_UID>']
  })
  console.log(group.uid, group.content_types)
} catch (error) {
  console.error(error.errorMessage)
}

delete

delete removes the variant group whose UID you passed to variantGroup('<VARIANT_GROUP_UID>'), with every variant in it.

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}

Returns: Promise<Response>. The API response with a notice.

Warning A successful delete removes the variant group and every variant inside it. The API unpublishes the entry variants of those variants and removes them from your entries. The SDK has no method that restores a deleted variant group.

Validation

  • There is no client-side validation.
  • delete exists only on variantGroup('<VARIANT_GROUP_UID>') and on the objects in the items of query().find(). On variantGroup() it is undefined, and calling it throws TypeError.
  • The API rejects the request while a Personalize experience uses the group. Delete the experience in Personalize first, as Delete variant group states.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends DELETE /v3/variant_groups/{variant_group_uid} with every key of param as a query parameter, as Delete variant group describes.
  • Resolves to the response body, which carries notice. When the API answers with an empty body, it resolves to { status, statusText } instead.

Example

Basic usage: delete a variant group

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const response = await stack.variantGroup('<VARIANT_GROUP_UID>').delete()
  console.log(response.notice)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: delete a variant group with an empty parameter object

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  // The API reference lists no query parameters for this request
  const response = await stack.variantGroup('<VARIANT_GROUP_UID>').delete({})
  console.log(response.notice)
} catch (error) {
  console.error(error.errorMessage)
}

query

query builds a request for the variant groups of the stack. It sends nothing until you call a method of the returned query.

NameTypeDescription
paramsobject

Query parameters for the request.

Default: {}
params.content_typestring

Returns the groups linked to this content type.

Default: API default
params.include_variant_infoboolean

Adds the variants of each group.

Default: API default
params.include_variant_countboolean

Adds the variant count of each group.

Default: API default
params.include_countboolean

Adds the total number of variant groups.

Default: API default
params.ascstring

Sorts ascending by created_at or name.

Default: API default
params.descstring

Sorts descending by created_at or name.

Default: API default
params.limitnumber

Maximum number of variant groups to return.

Default: API default
params.skipnumber

Number of variant groups to skip.

Default: API default

Returns: Query. A query for variant groups, sent when you call find(), findOne() or count().

Validation

  • There is no client-side validation.
  • query exists only on variantGroup(). On variantGroup('<VARIANT_GROUP_UID>') it is undefined, and calling it throws TypeError.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Client-side only. query copies the headers of this object and params, and returns a Query object.
  • find and findOne send GET /v3/variant_groups and resolve to VariantGroup objects in items, as Get all variant groups describes. count resolves to the response body.
  • Each VariantGroup in items is the single-group form, with update, delete and variants.
  • To read one variant group, call find and pick the item whose uid matches. The SDK has no fetch for a variant group.

Example

Basic usage: list the variant groups of a stack

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const result = await stack.variantGroup().query().find()
  for (const group of result.items) {
    console.log(group.uid, group.name)
  }
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: list the groups of one content type with their variants

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const result = await stack.variantGroup()
    .query({
      content_type: '<CONTENT_TYPE_UID>',
      include_variant_info: true,
      include_variant_count: true,
      include_count: true,
      asc: 'name',
      limit: 30,
      skip: 0
    })
    .find()
  console.log(result.count)
  for (const group of result.items) {
    console.log(group.uid, group.variant_count)
  }
} catch (error) {
  console.error(error.errorMessage)
}

Sort in descending order: list the newest groups first

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const result = await stack.variantGroup().query({ desc: 'created_at', limit: 5 }).find()
  for (const group of result.items) {
    console.log(group.uid, group.created_at)
  }
} catch (error) {
  console.error(error.errorMessage)
}

removeHeader

removeHeader removes one header from the requests that this variant group object sends.

NameTypeDescription
key (required)string

Name of the header to remove.

Default: Not applicable

Returns: VariantGroup. The same variant group, for chaining.

Validation

  • There is no client-side validation. A null or undefined key, or a key that the object does not hold, leaves the headers unchanged.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. removeHeader sends no request.
  • Removing a header that the object shares with the stack first copies the shared headers, so the stack and other objects keep the header.
  • The SDK adds some headers at request time, for example the authorization header of the client. removeHeader cannot remove those.

Example

Basic usage: send requests from one variant group object without the branch header

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>', branch_uid: '<BRANCH>' })

const variantGroup = stack.variantGroup('<VARIANT_GROUP_UID>').removeHeader('branch')
// This object now works with the default branch
console.log(variantGroup.stackHeaders.branch)

update

update renames the variant group whose UID you passed to variantGroup('<VARIANT_GROUP_UID>'), changes its description, or links and unlinks content types.

NameTypeDescription
data (required)object

Request body with the fields to change.

Default: Not applicable
data.namestring

New unique name of the variant group.

Default: API default (unchanged)
data.descriptionstring

New description of the variant group.

Default: API default (unchanged)
data.content_typesobject[]

Content types to link or unlink.

Default: API default (unchanged)
data.content_types[].uid (required)string

UID of one content type.

Default: Not applicable
data.content_types[].status (required)string

linked or unlinked.

Default: Not applicable

Returns: Promise<Response>. The updated variant group, as plain data.

Validation

  • There is no client-side validation. update sends data as the JSON body as it is, without a wrapper key.
  • update exists only on variantGroup('<VARIANT_GROUP_UID>') and on the objects in the items of query().find(). On variantGroup() it is undefined, and calling it throws TypeError.
  • The API reference asks for at least one of name, description and content_types.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends PUT /v3/variant_groups/{variant_group_uid} with data as the body, as Update variant group describes.
  • update reads none of the fields of this object. Pass every change in data.
  • Unlinking a content type does not delete its entry variants, as the API reference states.
  • Resolves to the response body as plain data, not to a VariantGroup object.

Example

Basic usage: rename a variant group

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const group = await stack.variantGroup('<VARIANT_GROUP_UID>').update({ name: 'Colors and finishes' })
  console.log(group.uid, group.name)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: rename a group and link a content type

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const group = await stack.variantGroup('<VARIANT_GROUP_UID>').update({
    name: 'Colors and finishes',
    description: 'Color and finish variants for product pages',
    content_types: [{ uid: '<CONTENT_TYPE_UID>', status: 'linked' }]
  })
  console.log(group.name, group.content_types)
} catch (error) {
  console.error(error.errorMessage)
}

variants

variants creates a Variants object for one variant of this group, or for all its variants.

NameTypeDescription
uidstring

UID of the variant to open.

Default: null (returns the collection form)

Returns: Variants. A new variants object.

Validation

  • There is no client-side validation. An empty string returns the collection form, as null does.
  • variants exists only on variantGroup('<VARIANT_GROUP_UID>') and on the objects in the items of query().find(). On variantGroup() it is undefined, and calling it throws TypeError.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Client-side only. variants sends no request.
  • With a UID, the object has fetch, update and delete. Without one, it has create and query. The Variants page lists every method of each form.
  • The new object takes the variant group UID of this object and shares its headers until either object changes its own.

Example

Basic usage: rename one variant of a group

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const variant = await stack.variantGroup('<VARIANT_GROUP_UID>').variants('<VARIANT_UID>').update({ name: 'Ivory' })
  console.log(variant.uid, variant.name)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

Collection form: list the variants of a group

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const result = await stack.variantGroup('<VARIANT_GROUP_UID>').variants().query().find()
  console.log(result.items.length)
} catch (error) {
  console.error(error.errorMessage)
}