Variant

View as Markdown

Variant

A variant is one version of content for an audience, for example a White variant in a Colors variant group. This Variants class manages the variants inside one variant group through the Content Management API (CMA). Use this class to

  • list and create the variants of a variant group
  • read, rename and delete one variant of the group

Call the variants method of a VariantGroup object that has a UID to get an object, for example stack.variantGroup('<VARIANT_GROUP_UID>').variants('<VARIANT_UID>').

The stack also has a Variants class of its own, from stack.variants(). That class works with any variant by its UID at /v3/variants, without naming a group, and it has no update. This class works under /v3/variant_groups/{variant_group_uid}/variants.

Instance State

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

Warning variants('') 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.

  • Every request sends the headers of this object, which start as the headers of the variant group object. Change them for this object only with addHeader, addHeaderDict and removeHeader.

Personalize.

  • When a Personalize experience uses the variant group, Personalize owns its variants, as the Variant Groups API reference states. You cannot rename or delete those variants through this class.

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
Read several variants by UID in one callNoUse the fetchByUIDs method of stack.variants()
Get a Variants object back from create, fetch or updateNoThey resolve to plain data. Call variants(variant.uid) for an object

Method Index

Work with the variants of a group. Available on stack.variantGroup('<VARIANT_GROUP_UID>').variants().

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

Read and change one variant. Available on stack.variantGroup('<VARIANT_GROUP_UID>').variants('<VARIANT_UID>').

Method NameReturnsDescription
fetchThe requested variant, as plain data.Retrieves one variant.
updateThe updated variant, as plain data.Renames the variant.
deleteThe API response with a notice.Deletes the variant.

Set request headers. Available on both forms.

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

Class-Level Snippet

The snippet below creates a variant in a group, renames 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>' })
const group = stack.variantGroup('<VARIANT_GROUP_UID>')

try {
  const created = await group.variants().create({ name: 'docs-test-white' })
  await group.variants(created.uid).update({ name: 'docs-test-ivory' })

  const result = await group.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 Variants class has its own section below, with its parameters, validation rules, behavior, and examples.

addHeader

addHeader adds one header to every request that this variants 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: Variants. The same variants object, 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.

Example

Basic usage: tag the requests of one variants object

import contentstack from '@contentstack/management'

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

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

addHeaderDict

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

NameTypeDescription
headerDict (required)object

Header names and values to add.

Default: Not applicable

Returns: Variants. The same variants object, 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 variants object

import contentstack from '@contentstack/management'

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

const variants = stack.variantGroup('<VARIANT_GROUP_UID>').variants('<VARIANT_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(variants.stackHeaders)

create

create creates a variant inside the variant group whose UID you passed to variantGroup('<VARIANT_GROUP_UID>').

NameTypeDescription
data (required)object

Request body with the variant details.

Default: Not applicable
data.name (required)string

Name of the variant, unique in the group.

Default: Not applicable
data.uidstring

Custom unique ID. You cannot change it later.

Default: API default (generated UID)

Returns: Promise<Response>. The new variant, 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 variants(). On variants('<VARIANT_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/{variant_group_uid}/variants with data as the body, as Create variant describes.
  • The new variant inherits every content type linked to the group, so it is available on the entries of those content types.
  • Resolves to the response body as plain data, not to a Variants object.

Example

Basic usage: create a variant in 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().create({ name: 'docs-test-white' })
  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)
}

All parameters: create a variant with a custom UID

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().create({
    name: 'docs-test-white',
    uid: 'docs_test_white'
  })
  console.log(variant.uid, variant.name)
} catch (error) {
  console.error(error.errorMessage)
}

delete

delete removes the variant whose UID you passed to variants('<VARIANT_UID>') from its variant group.

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}

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

Warning A successful delete removes the variant. The API unpublishes the entry variants that editors created for it and removes them from your entries. The variant group stays. The SDK has no method that restores a deleted variant.

Validation

  • There is no client-side validation.
  • delete exists only on variants('<VARIANT_UID>') and on the objects in the items of query().find(). On variants() it is undefined, and calling it throws TypeError.
  • The API rejects the request while a variation in a Personalize experience uses the variant. Delete the variation in Personalize first, as Delete variant 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}/variants/{variant_uid} with every key of param as a query parameter, as Delete variant 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 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 response = await stack.variantGroup('<VARIANT_GROUP_UID>').variants('<VARIANT_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 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>').variants('<VARIANT_UID>').delete({})
  console.log(response.notice)
} catch (error) {
  console.error(error.errorMessage)
}

fetch

fetch retrieves the variant whose UID you passed to variants('<VARIANT_UID>'), from its variant group.

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}

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

Validation

  • There is no client-side validation.
  • fetch exists only on variants('<VARIANT_UID>') and on the objects in the items of query().find(). On variants() 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 GET /v3/variant_groups/{variant_group_uid}/variants/{variant_uid} with every key of param as a query parameter.
  • The API reference documents the single-variant read at GET /v3/variants/{variant_uid}, in Get single variant. The fetch method of stack.variants('<VARIANT_UID>') sends that request.
  • Resolves to the response body as plain data, not to a Variants object.

Example

Basic usage: read 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>').fetch()
  console.log(variant)
} 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: read one variant 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 {
  // Every key of this object is sent as a query parameter
  const variant = await stack.variantGroup('<VARIANT_GROUP_UID>').variants('<VARIANT_UID>').fetch({})
  console.log(variant)
} catch (error) {
  console.error(error.errorMessage)
}

query

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

NameTypeDescription
paramsobject

Query parameters for the request.

Default: {}
params.include_countboolean

Adds the total number of variants in the group.

Default: API default
params.ascstring

Sorts ascending by name, created_at or updated_at.

Default: API default
params.descstring

Sorts descending by name, created_at or updated_at.

Default: API default
params.limitnumber

Maximum number of variants to return.

Default: API default
params.skipnumber

Number of variants to skip.

Default: API default

Returns: Query. A query for the variants of the group, sent when you call find(), findOne() or count().

Validation

  • There is no client-side validation.
  • query exists only on variants(). On variants('<VARIANT_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/{variant_group_uid}/variants and resolve to Variants objects in items, as Get all variants in a variant group describes. count resolves to the response body.
  • The API returns the variant group with its variants. Each Variants object in items takes the group UID from the uid of the response, and has fetch, update and delete.

Example

Basic usage: 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()
  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)
}

All parameters: read the second page of variants sorted by name

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({ include_count: true, asc: 'name', limit: 10, skip: 10 })
    .find()
  console.log(result.count)
  for (const variant of result.items) {
    console.log(variant.uid, variant.name)
  }
} catch (error) {
  console.error(error.errorMessage)
}

Sort in descending order: list the most recently changed variants 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('<VARIANT_GROUP_UID>').variants().query({ desc: 'updated_at' }).find()
  for (const variant of result.items) {
    console.log(variant.uid, variant.updated_at)
  }
} catch (error) {
  console.error(error.errorMessage)
}

removeHeader

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

NameTypeDescription
key (required)string

Name of the header to remove.

Default: Not applicable

Returns: Variants. The same variants object, 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 variants 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 variants = stack.variantGroup('<VARIANT_GROUP_UID>').variants('<VARIANT_UID>').removeHeader('branch')
// This object now works with the default branch
console.log(variants.stackHeaders.branch)

update

update renames the variant whose UID you passed to variants('<VARIANT_UID>').

NameTypeDescription
data (required)object

Request body with the new name.

Default: Not applicable
data.name (required)string

New name of the variant, unique in the group.

Default: Not applicable

Returns: Promise<Response>. The updated variant, 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 variants('<VARIANT_UID>') and on the objects in the items of query().find(). On variants() 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 PUT /v3/variant_groups/{variant_group_uid}/variants/{variant_uid} with data as the body, as Update variant describes.
  • The name is the only property of a variant that the API lets you change. The UID stays fixed after you create the variant.
  • update reads none of the fields of this object. Pass the new name in data.
  • Resolves to the response body as plain data, not to a Variants object.

Example

Basic usage: rename a variant

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)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}