Ungrouped Variant

View as Markdown

Ungrouped Variant

A variant is one version of content for an audience, for example a White variant of a product page. This Variants class works with the variants of one stack by their UIDs through the Content Management API (CMA), without naming a variant group. Use this class to

  • list and create variants at the stack level
  • read several variants by UID in one call
  • read and delete one variant

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

How this class differs from the variant group's Variants class. Both classes have the name Variants.

  • This class comes from stack.variants() and sends its requests to /v3/variants. It needs no variant group UID, and it can read several variants in one call with fetchByUIDs. It has no update.
  • The Variants class of a variant group comes from stack.variantGroup('<VARIANT_GROUP_UID>').variants() and sends its requests to /v3/variant_groups/{variant_group_uid}/variants. It can rename a variant.

Instance State

  • Call variants() without a UID to work with the variants of the stack, for example create and fetchByUIDs.
  • Call variants('<VARIANT_UID>') to work with one variant, for example fetch and delete.
  • 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 fetchByUIDs 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.

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
Rename a variantNoUse the update method of the variant group's Variants class
Get a Variants object back from create or fetchNoThey resolve to plain data. Call stack.variants(variant.uid) for an object

Method Index

Work with the variants of a stack. Available on stack.variants().

Method NameReturnsDescription
queryA query for variants, sent when you call find(), findOne() or count().Builds a variant query.
createThe new variant, as plain data.Creates a variant.
fetchByUIDsThe API response with the requested variants.Retrieves several variants by UID.

Read and delete one variant. Available on stack.variants('<VARIANT_UID>').

Method NameReturnsDescription
fetchThe requested variant, as plain data.Retrieves one 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 reads one variant, and then reads it again together with any other variants you list, in one call.

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.variants('<VARIANT_UID>').fetch()
  console.log(variant)

  const response = await stack.variants().fetchByUIDs(['<VARIANT_UID>'])
  console.log(response.variants)
} 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.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.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 at the stack level, without naming a variant group.

NameTypeDescription
data (required)object

Request body with the variant details.

Default: Not applicable
data.name (required)string

Name of the variant.

Default: Not applicable
data.uidstring

Custom unique ID of the variant.

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/variants with data as the body.
  • To create a variant inside a variant group, use the create method of stack.variantGroup('<VARIANT_GROUP_UID>').variants(), as Create variant describes.
  • Resolves to the response body as plain data, not to a Variants object.

Example

Basic usage: create 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.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.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>').

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 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/variants/{variant_uid} with every key of param as a query parameter, as Delete variant describes.
  • Deletes the variant only. The variant group it belongs to stays.
  • 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

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.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.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>').

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/variants/{variant_uid} with every key of param as a query parameter, as Get single variant describes.
  • When the variant belongs to a variant group, the API adds a summary of the group under variant_group, as the API reference states.
  • Resolves to the response body as plain data, not to a Variants object.

Example

Basic usage: read one 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.variants('<VARIANT_UID>').fetch()
  console.log(variant.uid, variant.name, variant.variant_group)
} 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.variants('<VARIANT_UID>').fetch({})
  console.log(variant.uid)
} catch (error) {
  console.error(error.errorMessage)
}

fetchByUIDs

fetchByUIDs retrieves several variants of the stack by their UIDs in one request. The following table lists its parameters:

NameTypeDescription
variantUids (required)string[]

UIDs of the variants to read.

Default: Not applicable

Returns: Promise<Response>. The API response with the requested variants.

Validation

  • There is no client-side validation. Without variantUids, the SDK sends the request with no uids parameter.
  • fetchByUIDs 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 GET /v3/variants with one uids[] query parameter per UID, for example ?uids[]=a&uids[]=b. Get single variant describes this request with the parameter name uids.
  • The API returns the matching variants in a variants array, as Get single variant states.
  • Resolves to the response body as plain data, not to Variants objects.

Example

Basic usage: read two variants in one call

import contentstack from '@contentstack/management'

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

try {
  // Add one UID per variant you want to read
  const response = await stack.variants().fetchByUIDs(['<VARIANT_UID>', 'docs_test_white'])
  for (const variant of response.variants) {
    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)
}

query

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

NameTypeDescription
paramsobject

Query parameters for the request.

Default: {}
params.queryobject

Condition on variant fields, sent as JSON.

Default: API default

Returns: Query. A query for variants, 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/variants and resolve to Variants objects in items. count resolves to the response body.
  • Each Variants object in items is the single-variant form, with fetch and delete.
  • The SDK sends params.query as query=<JSON>, and every other key of params as a query parameter.

Example

Basic usage: list the variants 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.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: find variants 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.variants().query({ query: { name: 'White' } }).find()
  for (const variant of result.items) {
    console.log(variant.uid, variant.name)
  }
} 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.variants('<VARIANT_UID>').removeHeader('branch')
// This object now works with the default branch
console.log(variants.stackHeaders.branch)