TermQuery

View as Markdown

TermQuery

TermQuery lists the published terms of one taxonomy. Use this class to read every term of a taxonomy in a chosen locale, a page at a time, down to a chosen depth.

A TermQuery takes one UID:

NameTypeDescription
taxonomyUidstringUID of the taxonomy whose terms to list.

stack.taxonomy('<TAXONOMY_UID>').term() returns a TermQuery. Pass a term UID to term() to get a Term instead, for one term. The two are separate classes with separate methods, so TypeScript rejects fetch on a TermQuery with TS2339.

addParams

addParams adds several query parameters to the term list request in one call.

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

Parameter names and values to add.

Default: Not applicable

Returns: TermQuery. The same query, 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.
  • The API ignores a parameter name it does not know and returns the list as if the parameter were absent.
  • A missing argument, or a value that is neither a string nor a number, fails to compile.
  • Errors surface on the find() call that follows, not on addParams(). find() 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 query's parameters and makes no request. find sends them.
  • Keeps every parameter you set earlier. A key in paramObj that the query already holds takes the new value.
  • Has the same effect as one param call per key.

Example

Basic usage: locale, fallback, and page size in one call

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()
    .addParams({ locale: 'fr-fr', include_fallback: 'true', limit: 20 })
    .find<BaseTerm>();
  console.log(result.terms?.map((term) => term.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 the term list covers.

NameTypeDescription
depth (required)number

Maximum number of hierarchy levels to return.

Default: Not applicable

Returns: TermQuery. The same query, 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 find() call that follows, not on depth(). find() 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. find sends the value.
  • Without depth, the SDK sends no depth parameter. For the parameters the request accepts, refer to Get all terms in the Content Delivery API reference.
  • depth(2) returns the top-level terms and their children. depth(0) returns an empty terms array. A value larger than the number of levels returns every term.
  • Each returned term carries its own depth field, which BaseTerm declares. A top-level term has depth 1. Read the field to group the terms by level.
  • skip and limit page through the whole list that depth selects.
  • A second depth call replaces the first value.

Example

Basic usage: the terms of the first two levels

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().depth(2).find<BaseTerm>();
  for (const term of result.terms ?? []) {
    console.log('level', term.depth, term.uid);
  }
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

find

find lists the published terms of the taxonomy.

Returns: Promise<FindResponse<T>>. The published terms of the taxonomy.

Validation

  • find validates nothing itself. The SDK checks no UID format and sends the taxonomy UID you passed as given.
  • find 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.

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

Behavior

  • Calls GET /taxonomies/{taxonomy_uid}/terms and makes one HTTP request per call.
  • Returns the response body unchanged. The terms are in its terms array. The body has no count field, even when you chain includeCount.
  • Chain depth to set the depth of the term hierarchy that the Get all terms request retrieves.
  • An unknown taxonomy UID does not fail. The API returns an empty terms array.
  • Sends every query parameter that the other nine methods recorded on the instance. A second find call on the same instance sends the same request again.
  • Does not page automatically. The SDK sets no limit, so the API returns up to 100 terms. Combine skip and limit to read further pages, and stop when a page returns fewer terms than the limit.
  • The generic T types each item of terms. The SDK exports BaseTerm, which declares the common term fields.

Example

Basic usage: list the terms of a taxonomy

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().find<BaseTerm>();
  for (const term of result.terms ?? []) {
    console.log(term.uid, term.name, 'depth', term.depth);
  }
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

Paging: read every term, one page at a time

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

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

const pageSize = 50;
const all: BaseTerm[] = [];

try {
  let done = false;
  while (!done) {
    const page = await stack
      .taxonomy('<TAXONOMY_UID>')
      .term()
      // depth sets how many levels of the term hierarchy to retrieve.
      .depth(10)
      .skip(all.length)
      .limit(pageSize)
      .find<BaseTerm>();
    const terms = page.terms ?? [];
    all.push(...terms);
    // The API returns no count here, so a short page marks the end of the list.
    done = terms.length < pageSize;
  }
  console.log('Read', all.length, 'terms');
} catch (error: any) {
  console.error(error);
}

includeBranch

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

Returns: TermQuery. The same query, for chaining.

Validation

  • There is nothing to validate. includeBranch takes no arguments and cannot fail.
  • Errors surface on the find() call that follows, not on includeBranch(). find() 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. find sends the flag.
  • The API sets _branch on each term to the branch name, for example main.
  • BaseTerm declares no _branch field. Extend it in your own type to read the field without a type error.

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 each 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().includeBranch().find<BranchedTerm>();
  for (const term of result.terms ?? []) {
    console.log(term.uid, 'served from branch', term._branch);
  }
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

includeCount

includeCount sends the include_count flag on the term list request. GET /taxonomies/{taxonomy_uid}/terms ignores the flag and returns no count.

Returns: TermQuery. The same query, for chaining.

Validation

  • There is nothing to validate. includeCount takes no arguments and cannot fail.
  • Errors surface on the find() call that follows, not on includeCount(). find() 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. includeCount sets include_count to the string 'true' and makes no request. find sends the flag.
  • The find result has no count field, so result.count is undefined. FindResponse declares count because other endpoints return it. For the parameters the term list accepts, refer to Get all terms in the Content Delivery API reference.
  • A second includeCount call has no further effect. No method removes the flag.

Limitations

  • Does not return a total. To find the end of the list, read pages with limit and skip until a page returns fewer terms than the limit.

Example

Basic usage: check for a count before you rely on it

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().limit(25).includeCount().find<BaseTerm>();
  const returned = result.terms?.length ?? 0;
  // The term list returns no count, so result.count is undefined.
  if (result.count === undefined) {
    console.log(`Returned ${returned} terms. The response has no total count.`);
  } else {
    console.log(`Returned ${returned} of ${result.count} terms`);
  }
} 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 each term that lacks a published version in the requested locale in an earlier locale in the hierarchy instead.

Returns: TermQuery. The same query, for chaining.

Validation

  • There is nothing to validate. includeFallback takes no arguments and cannot fail.
  • A call without locale raises no error. Chain locale as well, because the flag acts only on a requested locale.
  • Errors surface on the find() call that follows, not on includeFallback(). find() 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. find sends the flag.
  • Changes which terms the response contains, with the two outcomes below:
    • Without the flag, find returns only the terms that have a published version in the requested locale.
    • With the flag, find also returns the other terms, each in an earlier locale in the hierarchy.
  • The API resolves the fallback through the locale fallback hierarchy of the branch, not the SDK. Compare each term's locale field with the locale you requested to find the terms that fell back.
  • The flag stays on the instance for every later find. No method removes it.

Example

Basic usage: every term, in French where available

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()
    .locale('fr-fr')
    .includeFallback()
    .find<BaseTerm>();
  console.log('Terms returned:', result.terms?.length ?? 0);
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

Edge case: find the terms that fell back

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

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()
    .locale(requested)
    .includeFallback()
    .find<LocalizedTerm>();
  const fellBack = (result.terms ?? []).filter((term) => term.locale !== requested);
  console.log(`${fellBack.length} terms have no ${requested} version:`, fellBack.map((term) => term.uid));
} catch (error: any) {
  console.error(error);
}

limit

limit caps the number of terms the response contains.

NameTypeDescription
limit (required)number

Maximum number of terms to return.

Default: Not applicable

Returns: TermQuery. The same query, 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 limit is a required number.
  • Errors surface on the find() call that follows, not on limit(). find() 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. limit sets the limit query parameter and makes no request. find sends the value.
  • Without limit, the SDK sends no limit parameter, and the API returns up to 100 terms.
  • The API treats limit(0) as no limit and returns the whole list.
  • A second limit call replaces the first value. A later param('limit', ...) call also replaces it, because both write the same key.

Example

Basic usage: return at most ten terms

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().limit(10).find<BaseTerm>();
  console.log('Returned', result.terms?.length ?? 0, 'terms');
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

locale

locale sets the locale of the terms the query returns.

NameTypeDescription
locale (required)string

Locale code of the terms, for example fr-fr.

Default: Not applicable

Returns: TermQuery. The same query, for chaining.

Validation

  • There is no client-side validation. The SDK sends an empty string, an unknown code, or a code in the wrong case as given.
  • An unknown locale code fails with HTTP status 422 and error code 141.
  • A missing argument fails to compile, because locale is a required string.
  • Errors surface on the find() call that follows, not on locale(). find() 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. locale sets the locale query parameter and makes no request. find sends the value.
  • Without includeFallback, the response leaves out every term that has no published version in this locale. See that method for the fallback behavior.
  • Each returned term carries a locale field that names the locale of that version. BaseTerm declares no locale field, so extend it in your own type.
  • A second locale call replaces the first value. param with the key locale writes the same key, so the later call wins.
  • Without locale, the request carries the locale of the stack configuration when you set one there, and the API returns the terms in that locale. With no locale in either place, the request carries no locale parameter.

Example

Basic usage: list the French versions of the terms

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

interface LocalizedTerm extends BaseTerm {
  locale?: string;
}

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

try {
  const result = await stack.taxonomy('<TAXONOMY_UID>').term().locale('fr-fr').find<LocalizedTerm>();
  for (const term of result.terms ?? []) {
    console.log(term.uid, term.name, term.locale);
  }
} 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 the term list request.

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: TermQuery. The same query, 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.
  • The API ignores a parameter name it does not know and returns the list as if the parameter were absent.
  • A missing argument, or a value that is neither a string nor a number, fails to compile.
  • Errors surface on the find() call that follows, not on param(). find() 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 query's parameters and makes no request. find sends it.
  • Shares one set of keys with the dedicated setters. param('locale', 'en-us') and locale('en-us') write the same key, so the later call wins.
  • Use param for a Delivery API query parameter that has no dedicated method. Prefer the dedicated method when one exists, because its name states the intent.
  • 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: send the locale as a raw parameter

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().param('locale', 'fr-fr').find<BaseTerm>();
  console.log('Terms in French:', result.terms?.length ?? 0);
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

Edge case: a later param call replaces the locale

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

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

try {
  // Both calls write the locale key, so this request sends locale=en-us.
  const result = await stack.taxonomy('<TAXONOMY_UID>').term().locale('fr-fr').param('locale', 'en-us').find<BaseTerm>();
  console.log('Terms returned:', result.terms?.length ?? 0);
} catch (error: any) {
  console.error(error);
}

skip

skip sets the number of terms the response leaves out from the start of the list.

NameTypeDescription
skip (required)number

Number of terms to skip before the first one returned.

Default: Not applicable

Returns: TermQuery. The same query, 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 skip is a required number.
  • Errors surface on the find() call that follows, not on skip(). find() 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. skip sets the skip query parameter and makes no request. find sends the value.
  • Without skip, the SDK sends no skip parameter.
  • A second skip call replaces the first value. TermQuery has no next or previous, so move between pages by setting skip yourself.
  • A skip value past the end of the list returns an empty terms array.
  • Pair skip with limit to read one fixed-size page at a time. The API returns no count on this endpoint, so stop when a page returns fewer terms than the limit. The find method shows a loop that reads every page.

Example

Basic usage: read the second page of twenty terms

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().skip(20).limit(20).find<BaseTerm>();
  console.log('Page 2:', result.terms?.map((term) => term.uid));
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}