Term

View as Markdown

Term

A term is one node in the hierarchy of a taxonomy. Use this class for the three tasks below:

  • read one published term by its UID
  • list the localized versions of that term
  • retrieve the ancestors or the descendants of that term

A Term takes two UIDs:

NameTypeDescription
taxonomyUidstringUID of the taxonomy that holds the term.
termUidstringUID of the term.

stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>') supplies both UIDs and returns a Term. Omit the term UID to get a TermQuery instead, which lists the terms of the taxonomy. The two are separate classes with separate methods, so TypeScript rejects find on a Term and fetch on a TermQuery with TS2339.

Known issue In 5.x, term('') compiles as a Term, but an empty UID returns a TermQuery, so a later read method throws a TypeError. Check that a term UID variable is non-empty before you pass it. See the term method on the Taxonomy class.

addParams

addParams adds several query parameters to every request the term makes, in one call.

NameTypeDescription
paramObj (required){ [key: string]: string | number }

Parameter names and values to add.

Default: Not applicable

Returns: Term. The same term, for chaining.

Validation

  • There is no client-side validation. The SDK sends an empty object, empty keys, or parameter names the API does not know as given.
  • A missing argument, or a value that is neither a string nor a number, fails to compile.
  • Errors surface on the read method that follows, not on addParams(). That call throws an APIError when the request fails, carrying the HTTP status, the API error_code, and the error_message.

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

Behavior

  • Client-side only. addParams merges the object into the instance's query parameters and makes no request.
  • Keeps every parameter you set earlier. A key in paramObj that the instance already holds takes the new value.
  • Has the same effect as one param call per key.

Example

Basic usage: locale and depth in one call

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

interface TermList {
  terms?: BaseTerm[];
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack
    .taxonomy('<TAXONOMY_UID>')
    .term('<TERM_UID>')
    .addParams({ locale: 'fr-fr', depth: 2 })
    .descendants<TermList>();
  console.log(result.terms?.map((child) => child.name));
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

ancestors

ancestors retrieves the terms above this one in the taxonomy hierarchy, up to the root.

Returns: Promise<T>. The ancestor terms of this term.

Validation

  • ancestors validates nothing itself. The SDK checks no UID format and sends the UIDs you passed as given.
  • term('') never reaches this method, because it returns a TermQuery, which has no ancestors. See the Warning on the Term class page.
  • ancestors throws an APIError when the request fails, carrying the HTTP status, the API error_code, and the error_message. A network failure throws an APIError with status set to 0.
  • An unknown term UID or taxonomy UID fails with HTTP status 404, error code 404, and the error message errors.term.not_found.

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

Behavior

  • Calls GET /taxonomies/{taxonomy_uid}/terms/{term_uid}/ancestors and makes one HTTP request per call.
  • Returns the whole response body. The ancestors are in its terms array.
  • An empty terms array is a valid result. A term at the top of the hierarchy has no ancestors.
  • Lists terms only. The taxonomy itself is not an item in terms. Each returned term also carries an ancestors array whose first item is the taxonomy, with type set to TAXONOMY.
  • Returns the ancestors in the locale the term resolves to. Without includeFallback, a term that has no version in the requested locale fails with HTTP status 404.
  • Returns every ancestor up to the root. The SDK also sends a depth value you set, and the Get ancestors of a term request accepts it.
  • Sends every query parameter recorded on the instance as well.
  • The generic T types the result for your code. Pass the shape of the whole body, for example { terms?: BaseTerm[] }.

Limitations

  • Does not return this term itself. Use the fetch method for the term.
  • Does not filter entries. To match entries tagged with a term or its ancestors, pass TaxonomyQueryOperation.EQ_ABOVE to the where method on an entry query.

Example

Basic usage: list the ancestors of a term

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

interface TermList {
  terms?: BaseTerm[];
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>').ancestors<TermList>();
  const ancestors = result.terms ?? [];
  if (ancestors.length === 0) {
    console.log('This term sits at the top of the hierarchy.');
  }
  for (const ancestor of ancestors) {
    console.log(ancestor.uid, ancestor.name);
  }
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

depth

depth caps the number of hierarchy levels below the term that descendants returns.

NameTypeDescription
depth (required)number

Maximum number of hierarchy levels to return.

Default: Not applicable

Returns: Term. The same term, for chaining.

Validation

  • There is no client-side validation. The SDK sends zero, a negative number, or a fraction as given.
  • A missing argument or a string argument fails to compile, because depth is a required number.
  • Errors surface on the read method that follows, not on depth(). That call throws an APIError when the request fails, carrying the HTTP status, the API error_code, and the error_message.

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

Behavior

  • Client-side only. depth sets the depth query parameter and makes no request.
  • Governs the descendants method. depth(1) returns the direct children only, depth(2) adds their children, and depth(3) adds one more level. depth(0) returns an empty terms array.
  • Every read method sends it, so it also travels on ancestors, fetch, and locales from the same instance. The Get ancestors of a term and Get a single term requests accept depth. The locales request ignores it.
  • Without depth, the SDK sends no depth parameter, and descendants returns the direct children only, the same as depth(1).
  • Each returned term carries a numeric depth field, which gives its level in the taxonomy.
  • A second depth call replaces the first value. No method removes it, so call depth again to read a different number of levels.

Example

Basic usage: descendants within two levels

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

interface TermList {
  terms?: BaseTerm[];
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>').depth(2).descendants<TermList>();
  for (const child of result.terms ?? []) {
    console.log(child.uid, 'at depth', child.depth);
  }
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

Edge case: change the depth on the same instance

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

interface TermList {
  terms?: BaseTerm[];
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const term = stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>');
  const near = await term.depth(1).descendants<TermList>();

  // The instance keeps depth=1 until a second depth call replaces it.
  const deeper = await term.depth(3).descendants<TermList>();
  console.log('Within one level:', near.terms?.length ?? 0, 'Within three levels:', deeper.terms?.length ?? 0);
} catch (error: any) {
  console.error(error);
}

descendants

descendants retrieves the terms below this one in the taxonomy hierarchy.

Returns: Promise<T>. The descendant terms of this term.

Validation

  • descendants validates nothing itself. The SDK checks no UID format and sends the UIDs you passed as given.
  • term('') never reaches this method, because it returns a TermQuery, which has no descendants. See the Warning on the Term class page.
  • descendants throws an APIError when the request fails, carrying the HTTP status, the API error_code, and the error_message. A network failure throws an APIError with status set to 0.
  • An unknown term UID or taxonomy UID fails with HTTP status 404, error code 404, and the error message errors.term.not_found.

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

Behavior

  • Calls GET /taxonomies/{taxonomy_uid}/terms/{term_uid}/descendants and makes one HTTP request per call.
  • Returns the whole response body. The descendants are in its terms array.
  • An empty terms array is a valid result. A term at the bottom of the hierarchy has no descendants.
  • Without depth, the SDK sends no depth parameter, and the API returns the direct children only. Chain depth to include more levels. depth(2) returns two levels below the term, and depth(0) returns an empty terms array.
  • Each returned term carries a numeric depth field, which gives its level in the taxonomy.
  • Without includeFallback, a term that has no version in the requested locale fails with HTTP status 404.
  • Sends every query parameter recorded on the instance as well.
  • The generic T types the result for your code. Pass the shape of the whole body, for example { terms?: BaseTerm[] }.

Limitations

  • Does not return this term itself. Use the fetch method for the term.
  • Does not filter entries. To match entries tagged with a term or its descendants, pass TaxonomyQueryOperation.EQ_BELOW to the where method on an entry query.

Example

Basic usage: list the descendants of a term

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

interface TermList {
  terms?: BaseTerm[];
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>').descendants<TermList>();
  for (const child of result.terms ?? []) {
    console.log(child.uid, child.name, 'depth', child.depth);
  }
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

Depth: two levels below the term

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

interface TermList {
  terms?: BaseTerm[];
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>').depth(2).descendants<TermList>();
  console.log('Descendants within two levels:', result.terms?.length ?? 0);
} catch (error: any) {
  console.error(error);
}

fetch

fetch retrieves one published term by its UID.

Returns: Promise<T>. The requested term.

Validation

  • fetch validates nothing itself. The SDK checks no UID format and sends the UIDs you passed as given.
  • fetch takes no arguments. Code written for SDK versions earlier than 5.4.0 that passes a locale, as in fetch('fr-fr'), fails to compile with TS2554. Set the locale with the param method instead.
  • term('') never reaches this method, because it returns a TermQuery, which has no fetch. See the Warning on the Term class page.
  • fetch throws an APIError when the request fails, carrying the HTTP status, the API error_code, and the error_message. A network failure throws an APIError with status set to 0.
  • An unknown term UID or taxonomy UID fails with HTTP status 404, error code 404, and the error message errors.term.not_found. A term that has no version in the requested locale fails the same way, unless you chain includeFallback.

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

Behavior

  • Calls GET /taxonomies/{taxonomy_uid}/terms/{term_uid} and makes one HTTP request per call.
  • Returns the contents of the term key of the response body. When the body has no term key, fetch returns the whole body.
  • Sends every query parameter recorded on the instance, including a depth you set for ancestors or descendants. The Get a single term request accepts depth. A second fetch call on the same instance sends the same request again.
  • The term carries a locale field that names the locale the API served. BaseTerm declares no locale field, so extend it in your own type.
  • The generic T types the result for your code. The SDK does not check the response against it. The SDK exports BaseTerm, which declares the common term fields.

Limitations

  • Does not return the descendants of the term. Use the descendants method for them.

Example

Basic usage: read one term by UID

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>').fetch<BaseTerm>();
  console.log(result.uid, result.name, 'in taxonomy', result.taxonomy_uid);
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

Localized fetch: locale, fallback, and branch on one request

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

// BaseTerm declares neither field, so add the two this request asks for.
interface LocalizedTerm extends BaseTerm {
  locale?: string;
  _branch?: string;
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack
    .taxonomy('<TAXONOMY_UID>')
    .term('<TERM_UID>')
    .param('locale', 'fr-fr')
    .includeFallback()
    .includeBranch()
    .fetch<LocalizedTerm>();
  console.log(result.name, 'served in', result.locale, 'from branch', result._branch);
} catch (error: any) {
  console.error(error);
}

includeBranch

includeBranch asks the API to add the _branch field, which names the branch that served the term, to the response.

Returns: Term. The same term, for chaining.

Validation

  • There is nothing to validate. includeBranch takes no arguments and cannot fail.
  • Errors surface on the read method that follows, not on includeBranch(). That call throws an APIError when the request fails, carrying the HTTP status, the API error_code, and the error_message.

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

Behavior

  • Client-side only. includeBranch sets include_branch to the string 'true' and makes no request. Every read method sends the flag.
  • The API sets _branch to the branch name, for example main. On locales, ancestors, and descendants, each item in terms carries the field.
  • BaseTerm declares no _branch field. Extend it in your own type to read the field without a type error.
  • The flag stays on the instance for every later read. No method removes it.

Limitations

  • Does not choose a branch. The branch option of the stack configuration does, and the SDK sends it as a branch header on every request.

Example

Basic usage: read the branch that served the term

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

interface BranchedTerm extends BaseTerm {
  _branch?: string;
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>').includeBranch().fetch<BranchedTerm>();
  console.log(result.uid, 'served from branch', result._branch);
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

includeFallback

includeFallback returns the term in an earlier locale in the hierarchy when the term has no published version in the requested locale.

Returns: Term. The same term, for chaining.

Validation

  • There is nothing to validate. includeFallback takes no arguments and cannot fail.
  • Errors surface on the read method that follows, not on includeFallback(). That call throws an APIError when the request fails, carrying the HTTP status, the API error_code, and the error_message.

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

Behavior

  • Client-side only. includeFallback sets include_fallback to the string 'true' and makes no request. Every read method sends the flag.
  • The flag matters only with a locale. Term has no locale method, so send one through the param method, for example param('locale', 'fr-fr').
  • The API resolves the fallback through the locale fallback hierarchy of the branch, not the SDK. The locale field of the returned term names the locale the API served.
  • Without the flag, fetch, ancestors, and descendants fail with HTTP status 404 for a term that has no version in the requested locale. locales ignores the flag.
  • The flag stays on the instance for every later read. No method removes it, so build a new instance to read without it.

Limitations

  • A flag chained on the Taxonomy does not reach the term. Chain includeFallback on the Term itself.

Example

Basic usage: accept an earlier locale when the French version is missing

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack
    .taxonomy('<TAXONOMY_UID>')
    .term('<TERM_UID>')
    .param('locale', 'fr-fr')
    .includeFallback()
    .fetch<BaseTerm>();
  console.log(result.uid, result.name);
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

Edge case: detect a fallback

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

// BaseTerm declares no locale field, so add the one the response carries.
interface LocalizedTerm extends BaseTerm {
  locale?: string;
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

const requested = 'fr-fr';

try {
  const result = await stack
    .taxonomy('<TAXONOMY_UID>')
    .term('<TERM_UID>')
    .param('locale', requested)
    .includeFallback()
    .fetch<LocalizedTerm>();
  if (result.locale && result.locale !== requested) {
    console.log(`No ${requested} version, served ${result.locale} instead`);
  }
} catch (error: any) {
  console.error(error);
}

locales

locales retrieves every published localized version of the term.

Returns: Promise<T>. The localized versions of this term.

Validation

  • locales validates nothing itself. The SDK checks no UID format and sends the UIDs you passed as given.
  • term('') never reaches this method, because it returns a TermQuery, which has no locales. See the Warning on the Term class page.
  • locales throws an APIError when the request fails, carrying the HTTP status, the API error_code, and the error_message. A network failure throws an APIError with status set to 0.
  • An unknown term UID does not fail. The API returns an empty terms array, so check the array length before you use the result.

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

Behavior

  • Calls GET /taxonomies/{taxonomy_uid}/terms/{term_uid}/locales and makes one HTTP request per call.
  • Returns the whole response body. The versions are in its terms array.
  • Each item in terms is one version of the term, and its locale field names the locale of that version. BaseTerm declares no locale field, so extend it in your own type.
  • Sends every query parameter recorded on the instance as well. The API ignores locale, include_fallback, and depth here and always lists every version. include_branch adds the _branch field to each item.
  • The generic T types the result for your code. Pass the shape of the whole body, for example { terms?: LocalizedTerm[] }.

Example

Basic usage: list the locales a term exists in

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

interface LocalizedTerm extends BaseTerm {
  locale?: string;
}

interface TermVersions {
  terms?: LocalizedTerm[];
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>').locales<TermVersions>();
  for (const version of result.terms ?? []) {
    console.log(version.locale, version.name);
  }
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

param

param adds one query parameter to every request the term makes.

NameTypeDescription
key (required)string

Name of the query parameter to send.

Default: Not applicable
value (required)string | number

Value of that query parameter.

Default: Not applicable

Returns: Term. The same term, for chaining.

Validation

  • There is no client-side validation. The SDK sends an empty key, an empty value, or a parameter name the API does not know as given.
  • A missing argument, or a value that is neither a string nor a number, fails to compile.
  • Errors surface on the read method that follows, not on param(). That call throws an APIError when the request fails, carrying the HTTP status, the API error_code, and the error_message.

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

Behavior

  • Client-side only. param records the pair in the instance's query parameters and makes no request.
  • The way to set the locale, because Term has no locale method: param('locale', 'fr-fr').
  • Shares one set of keys with the dedicated setters. param('depth', 3) and depth(3) write the same key, so the later call wins.
  • Every read method sends the parameter, so it travels on fetch, locales, ancestors, and descendants from the same instance.
  • The SDK encodes the value for the URL, so a value with a space or an ampersand needs no encoding from you.

Example

Basic usage: read a term in another locale

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack
    .taxonomy('<TAXONOMY_UID>')
    .term('<TERM_UID>')
    .param('locale', 'fr-fr')
    .fetch<BaseTerm>();
  console.log('Name in French:', result.name);
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

Number value: one level of ancestors

import contentstack, { type BaseTerm } from '@contentstack/delivery-sdk';

interface TermList {
  terms?: BaseTerm[];
}

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  // param writes the same depth key that depth() writes.
  const result = await stack.taxonomy('<TAXONOMY_UID>').term('<TERM_UID>').param('depth', 1).ancestors<TermList>();
  console.log(result.terms?.map((ancestor) => ancestor.uid));
} catch (error: any) {
  console.error(error);
}