Term

View as Markdown

Term

The Term class represents a taxonomy term (a node in a hierarchy) in the .NET Management SDK. It operates on API paths rooted at /taxonomies/{taxonomy_uid}/terms and /taxonomies/{taxonomy_uid}/terms/{term_uid} when scoped to a single term.

Initialization

Access a Term instance through stack.Taxonomy("TAXONOMYUID").Terms(...) rather than constructing it directly. Once obtained, use the instance to perform create, read, update, delete, hierarchy, move, locale, or search operations.

Syntax: stack.Taxonomy("<TAXONOMY_UID>").Terms(string termUid = null)

Method Index

Method NameDescription
Find() / FindAsync()Queries and retrieves terms within the specific taxonomy.
Create() / CreateAsync()Creates a new term in the taxonomy.
Update() / UpdateAsync()Updates an existing term's details.
Fetch() / FetchAsync()Fetches details of a single term.
Delete() / DeleteAsync()Deletes a term from the taxonomy.
Ancestors() / AncestorsAsync()Retrieves the ancestor terms of a specific term.
Descendants() / DescendantsAsync()Retrieves the descendant terms of a specific term.
Move() / MoveAsync()Moves a term to a new parent and/or changes its sibling order.
Locales() / LocalesAsync()Gets locales information for the term.
Localize() / LocalizeAsync()Creates or updates a localized version of the term.
Search() / SearchAsync()Performs a typeahead search across terms in all taxonomies.

Synchronous vs Asynchronous Methods

Synchronous

  • Blocks the executing thread until the API responds.
  • Use for simple console scripts or background workers where blocking is acceptable.

Asynchronous (Async)

  • Releases the thread while waiting for the network response.
  • Recommended for modern .NET apps (e.g., ASP.NET Core) and UI apps.
  • Ensures better scalability and responsiveness.

Common Usage Example

The following example demonstrates a complete asynchronous workflow to create a new term under a specific taxonomy.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Exceptions;

namespace ContentstackExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            try 
            {
                // Initialize the Contentstack client with the authentication token
                ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

                // Target the specific stack using its API key
                Stack stack = client.Stack("<API_KEY>");

                // Define the payload for the new term, indicating its relationship
                TermModel model = new TermModel
                {
                    Uid = "<TERM_UID>",
                    Name = "Electronics",
                    ParentUid = null // Set to null for a root term
                };

                // Target the taxonomy and execute the term creation request asynchronously
                ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms().CreateAsync(model);

                // Output success message
                Console.WriteLine("Term Created Successfully");
            } 
            catch (ContentstackException ex) 
            {
                Console.WriteLine($"Contentstack Error: {ex.ErrorMessage}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"System Error: {ex.Message}");
            }
        }
    }
}

Find/FindAsync

The Find and FindAsync actions retrieve all terms within a taxonomy.

Note Results are paginated, so a single Find() may not return all items. Use limit and skip to retrieve additional pages.

Validation

  • If you omit collection or pass null, the SDK sends only the parameters defined by fluent Query methods (for example Limit, Skip, IncludeCount).
  • The SDK forwards all entries in ParameterCollection as query parameters without validation. The API validates parameter names and values and returns errors for invalid or unsupported inputs.

Behavior

  • The API returns a JSON response based on the Management API for listing terms. The structure depends on the query parameters you send. Responses typically include a terms array, and may include a total count when you use IncludeCount.
  • Each Find or FindAsync call sends one HTTP GET request to /taxonomies/{taxonomy_uid}/terms with query parameters.
  • The SDK returns one page per call. It does not automatically retrieve all results. Control pagination using Query.Limit, Query.Skip, and optionally Query.IncludeCount, or pass equivalent parameters through collection. The SDK merges collection with the fluent query before sending the request.
  • Use Terms(termUid).Ancestors() or Terms(termUid).Descendants() to retrieve hierarchy data for a specific term instead of Query().Find().
  • The SDK does not provide a fluent Depth() method on Query. When the API includes hierarchy data, deserialize it using TermModel, which exposes optional Depth, Ancestors, and Descendants properties.
NameTypeDescription
collectionParameterCollection

Defines optional query parameters for Query().Find(). Provide explicit values to control retrieval results using filters.

Default: null

The following example lists taxonomy terms with optional pagination and count. It uses OpenTResponse<TermsQueryResponse> with a matching DTO, and demonstrates handling HTTP failures, API errors, and SDK preconditions.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Exceptions;
using Newtonsoft.Json;

// Matches a common list-terms shape: { "terms": [ ... ], "count": ... } when include_count is used.
public sealed class TermsQueryResponse
{
    [JsonProperty("terms")]
    public List<TermModel> Terms { get; set; }

    [JsonProperty("count")]
    public int? Count { get; set; }
}

public static class TermsFindExample
{
    public static async Task RunAsync()
    {
        try
        {
            ContentstackClient client = new ContentstackClient("AUTHTOKEN");
            Stack stack = client.Stack("APIKEY");

            ContentstackResponse response = await stack
                .Taxonomy("TAXONOMYUID")
                .Terms()
                .Query()
                .Limit(50)
                .Skip(0)
                .IncludeCount()
                .FindAsync(collection: null);

            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine($"Terms query failed: HTTP {(int)response.StatusCode}");
                return;
            }

            var data = response.OpenTResponse<TermsQueryResponse>();
            if (data?.Terms != null)
            {
                foreach (var term in data.Terms)
                {
                    Console.WriteLine(term.Name);
                }
            }

            if (data?.Count is int total)
            {
                Console.WriteLine($"Total terms (per API): {total}");
            }

            Console.WriteLine("Terms retrieved.");
        }
        catch (ContentstackErrorException ex)
        {
            Console.WriteLine($"API error ({(int)ex.StatusCode}): {ex.ErrorMessage}");
        }
        catch (ContentstackException ex)
        {
            Console.WriteLine($"Contentstack error: {ex.Message}");
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine($"Invalid operation: {ex.Message}");
        }
    }
}

Create / CreateAsync

The Create and CreateAsync actions add a new term node under the designated taxonomy hierarchy.

Validation

  • Passing a null model throws ArgumentNullException before the request.
  • Call Create / CreateAsync on Terms() (collection scope). Calling it on Terms(termUid) throws InvalidOperationException.
  • You can set ParentUid = null to create a root term. The SDK omits null properties from the request body.

Behavior

  • Each call sends one HTTP POST to /taxonomies/{taxonomy_uid}/terms with the body { "term": … }.
  • The SDK serializes TermModel under the term key and does not derive uid from Name.
  • The API returns a JSON response, commonly wrapping the created term under a term field. Define a matching DTO when using OpenTResponse<T>().
  • Pass collection to include query parameters. The SDK forwards them without validation and the API defines supported keys.
NameTypeDescription
model (required)TermModel

Defines the term payload (Name, ParentUid, etc.) for Create(). Provide values to create a term node.

Default: NA
collectionParameterCollection

Defines query parameters for the creation request. Provide values to control the default API behavior.

Default: null

The following example:

  • Creates a root term (ParentUid = null) and a child term using the root’s Uid as ParentUid.
  • Calls CreateAsync on collection-scoped Terms().
  • Uses unique term UIDs to avoid collisions, and requires valid AUTHTOKEN, APIKEY, and an existing TAXONOMYUID.
using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Exceptions;
using Newtonsoft.Json;

// Matches a common create-term response body: { "term": { ... } }.
public sealed class TermCreateResponse
{
    [JsonProperty("term")]
    public TermModel Term { get; set; }
}

public static class TermCreateExample
{
    public static async Task RunAsync()
    {
        try
        {
            ContentstackClient client = new ContentstackClient("AUTHTOKEN");
            Stack stack = client.Stack("APIKEY");
            string taxonomyUid = "TAXONOMYUID";

            // Root term — ParentUid null (same pattern as SDK integration tests).
            string rootUid = "term_root_" + Guid.NewGuid().ToString("N").Substring(0, 8);
            var rootModel = new TermModel
            {
                Uid = rootUid,
                Name = "Electronics",
                ParentUid = null
            };

            ContentstackResponse rootResponse = await stack.Taxonomy(taxonomyUid).Terms()
                .CreateAsync(rootModel, collection: null);

            if (!rootResponse.IsSuccessStatusCode)
            {
                Console.WriteLine($"Root term create failed: HTTP {(int)rootResponse.StatusCode}");
                return;
            }

            // Child term — ParentUid must reference an existing term in this taxonomy.
            string childUid = "term_child_" + Guid.NewGuid().ToString("N").Substring(0, 8);
            var childModel = new TermModel
            {
                Uid = childUid,
                Name = "Smartphones",
                ParentUid = rootUid
            };

            ContentstackResponse childResponse = await stack.Taxonomy(taxonomyUid).Terms()
                .CreateAsync(childModel, collection: null);

            if (!childResponse.IsSuccessStatusCode)
            {
                Console.WriteLine($"Child term create failed: HTTP {(int)childResponse.StatusCode}");
                return;
            }

            TermCreateResponse created = childResponse.OpenTResponse<TermCreateResponse>();
            if (created?.Term != null)
            {
                Console.WriteLine($"Created child term '{created.Term.Name}' (uid: {created.Term.Uid}).");
            }
            else
            {
                Console.WriteLine("Child term create succeeded; response did not deserialize with the sample DTO.");
            }
        }
        catch (ContentstackErrorException ex)
        {
            Console.WriteLine($"API error ({(int)ex.StatusCode}): {ex.ErrorMessage}");
        }
        catch (ContentstackException ex)
        {
            Console.WriteLine($"Contentstack error: {ex.Message}");
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine($"Invalid operation: {ex.Message}");
        }
    }
}

Update / UpdateAsync

The Update and UpdateAsync actions modify the metadata of an existing term.

NameTypeDescription
model (required)TermModel

Defines the fields to update (e.g., Name) for Update(). Provide values to overwrite existing term data.

Default: NA
collectionParameterCollection

Defines optional query parameters for the update request. Provide values to control the API response.

Default: null

The following example shows how to target a specific term and update its display name.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Exceptions;

try 
{
    // Initialize the Contentstack client and target the stack
    ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
    Stack stack = client.Stack("<API_KEY>");


    // Set the updated term values
    TermModel model = new TermModel { Name = "<UPDATED_NAME>" };


    // Apply updates asynchronously to the targeted term within the specific taxonomy
    ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms("<TERM_UID>").UpdateAsync(model);


    // Output success message
    Console.WriteLine("Term updated.");
} 
catch (ContentstackException ex) 
{
    Console.WriteLine($"Error: {ex.ErrorMessage}");
}

Fetch / FetchAsync

The Fetch and FetchAsync actions retrieve the properties and configuration of a single targeted term.

NameTypeDescription
collectionParameterCollection

Defines optional query parameters for Fetch(). Provide values to customize the returned payload.

Default: null

The following example shows how to fetch the precise details of a specific term node.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

try 
{
    // Initialize the Contentstack client and target the stack
    ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
    Stack stack = client.Stack("<API_KEY>");


    // Asynchronously retrieve the payload of a specific term node
    ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms("<TERM_UID>").FetchAsync();


    // Output success message
    Console.WriteLine("Term fetched.");
} 
catch (ContentstackException ex) 
{
    Console.WriteLine($"Error: {ex.ErrorMessage}");
}

Delete / DeleteAsync

The Delete and DeleteAsync actions remove a specific term from the taxonomy hierarchy.

NameTypeDescription
collectionParameterCollection

Defines optional query parameters (e.g., force) for Delete(). Provide values to control deletion behavior.

Default: null

The following example shows how to force-delete a term node even if dependencies exist.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Queryable;
using Contentstack.Management.Core.Exceptions;

try 
{
    // Initialize the Contentstack client and target the stack
    ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
    Stack stack = client.Stack("<API_KEY>");


    // Setup a query parameter collection with the "force" delete setting enabled
    ParameterCollection collection = new ParameterCollection();
    collection.Add("force", true);


    // Asynchronously delete the specified term, enforcing the deletion operation
    ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms("<TERM_UID>").DeleteAsync(collection);


    // Output success message
    Console.WriteLine("Term deleted.");
} 
catch (ContentstackException ex) 
{
    Console.WriteLine($"Error: {ex.ErrorMessage}");
}

Ancestors / AncestorsAsync

The Ancestors and AncestorsAsync actions return all parent nodes upward in the taxonomy hierarchy for the given term.

NameTypeDescription
collectionParameterCollection

Defines optional query parameters for Ancestors(). Provide explicit values to customize the retrieved ancestor payload.

Default: null

The following example shows how to query all parent hierarchy structures above the specified term.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

try 
{
    // Initialize the Contentstack client and target the stack
    ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
    Stack stack = client.Stack("<API_KEY>");


    // Query for all hierarchical parent terms connected to the specific term node
    ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms("<TERM_UID>").AncestorsAsync();


    // Output success message
    Console.WriteLine("Ancestors fetched.");
} 
catch (ContentstackException ex) 
{
    Console.WriteLine($"Error: {ex.ErrorMessage}");
}

Descendants / DescendantsAsync

The Descendants and DescendantsAsync actions return all child nodes downward in the taxonomy hierarchy for the given term.

NameTypeDescription
collectionParameterCollection

Defines query parameters for Descendants(). Provide values to customize the retrieved descendant payload.

Default: null

The following example shows how to query all underlying child nodes beneath the specified term.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

try 
{
    // Initialize the Contentstack client and target the stack
    ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
    Stack stack = client.Stack("<API_KEY>");


    // Asynchronously retrieve all child term hierarchies attached to the specific term node
    ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms("<TERM_UID>").DescendantsAsync();


    // Output success message
    Console.WriteLine("Descendants fetched.");
} 
catch (ContentstackException ex) 
{
    Console.WriteLine($"Error: {ex.ErrorMessage}");
}

Move / MoveAsync

The Move and MoveAsync actions change the parent and/or sibling order of a specific term within the taxonomy hierarchy.

Note The SDK uses a TermMoveModel (not separate parameters) for move operations. Set ParentUid to the target parent term and optionally Order for sibling position. The SDK serializes this model under the term key in the request body. You can pass optional query parameters (for example, force) using a ParameterCollection as the second argument to Move / MoveAsync.

NameTypeDescription
moveModel (required)TermMoveModel

Defines the target parent UID and optional sibling order for Move(). Provide values to restructure the term hierarchy.

Default: NA
collectionParameterCollection

Defines optional query parameters (for example, force) for Move(). Provide values to control move behavior.

Default: null

The following example shows how to move a specific term to a new parent ID at order rank 1.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;
using Contentstack.Management.Core.Exceptions;

try 
{
    // Initialize the Contentstack client and target the stack
    ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
    Stack stack = client.Stack("<API_KEY>");


    // Configure the restructuring behavior, outlining the target parent and sibling order
    TermMoveModel moveModel = new TermMoveModel 
    { 
        ParentUid = "<NEW_PARENT_TERM_UID>", 
        Order = 1 
    };


    // Add 'force' condition to safely allow move bypassing certain dependency constraints
    ParameterCollection collection = new ParameterCollection();
    collection.Add("force", true);


    // Execute the asynchronous term move update applying the configuration
    ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms("<TERM_UID>").MoveAsync(moveModel, collection);


    // Output success message
    Console.WriteLine("Term moved successfully.");
} 
catch (ContentstackException ex) 
{
    Console.WriteLine($"Error: {ex.ErrorMessage}");
}

Locales / LocalesAsync

The Locales and LocalesAsync actions return locale information strictly for the specified term.

NameTypeDescription
collectionParameterCollection

Query parameters for Locales(). Provide values to customize the returned locale list.

Default: null

The following example shows how to retrieve all locales under which this exact term has been localized.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

try 
{
    // Initialize the Contentstack client and target the stack
    ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
    Stack stack = client.Stack("<API_KEY>");


    // Request a fetch array representing the localized variants for a specific term
    ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms("<TERM_UID>").LocalesAsync();


    // Output success message
    Console.WriteLine("Term Locales fetched.");
} 
catch (ContentstackException ex) 
{
    Console.WriteLine($"Error: {ex.ErrorMessage}");
}

Localize / LocalizeAsync

The Localize and LocalizeAsync actions create or update a localized version of a term node.

NameTypeDescription
model (required)TermModel

Localized term data for Localize(). Provide values to submit the localized payload.

Default: NA
collection (required)ParameterCollection

Query parameters for Localize() to designate the target locale. Provide values to assign the term to the correct locale code.

Default: null

The following example shows how to create a localized entry for the specific term targeting the "fr-fr" locale.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;
using Contentstack.Management.Core.Exceptions;

try 
{
    // Initialize the Contentstack client and target the stack
    ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
    Stack stack = client.Stack("<API_KEY>");


    // Set up the localized name or properties for the specific term node
    TermModel model = new TermModel { Name = "Électronique" };


    // Configure the localization target (in this case, french mapping via 'fr-fr')
    ParameterCollection collection = new ParameterCollection();
    collection.Add("locale", "fr-fr");


    // Push the updated translation payload specific to the targeted term
    ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms("<TERM_UID>").LocalizeAsync(model, collection);


    // Output success message
    Console.WriteLine("Term localized.");
} 
catch (ContentstackException ex) 
{
    Console.WriteLine($"Error: {ex.ErrorMessage}");
}

Search / SearchAsync

The Search and SearchAsync actions perform a typeahead search across terms in all taxonomies globally within the stack.

NameTypeDescription
typeahead (required)string

The typeahead search string for Search(). Provide values to locate matching terms globally.

Default: NA
collectionParameterCollection

Query parameters for Search(). Provide values to refine search results.

Default: null

The following example shows how to execute a typeahead search to find terms matching a designated string across the stack's taxonomies.

using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

try 
{
    // Initialize the Contentstack client and target the stack
    ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
    Stack stack = client.Stack("<API_KEY>");


    // Note: Called on the collection context without a specific term UID.
    // Conducts an asynchronous typeahead search through all term collections globally
    ContentstackResponse response = await stack.Taxonomy("<TAXONOMY_UID>").Terms().SearchAsync("<TYPEAHEAD_STRING>");


    // Output success message
    Console.WriteLine("Search completed.");
} 
catch (ContentstackException ex) 
{
    Console.WriteLine($"Error: {ex.ErrorMessage}");
}