---
title: "Branch"
description: "Branch"
url: "https://www.contentstack.com/docs/developers/sdks/content-management-sdk/dot-net/reference/branch"
product: "Contentstack"
doc_type: "guide"
audience:
  - developers
  - admins
version: "current"
last_updated: "2026-11-07"
---

# Branch

## Branch

The Branch class creates, fetches, lists, and deletes the [branches](/docs/headless-cms/about-branches) of a stack.

**When to Use This Class:** Use this class when your code creates or removes an isolated copy of stack content, for example a branch for a test run.

**Conceptual Role:** Acts as the Content Management API (CMA) client for the /stacks/branches endpoint. Call stack.Branch() to get an instance.

**Returns:** Branch. A handle for branch operations.

## Instance State

The UID you pass to stack.Branch() decides which methods you can call on the instance:

*   Call stack.Branch() without a UID to work with the branch collection, for example Create or Query.
*   Call stack.Branch("<BRANCH\_UID>") to work with one branch, for example Fetch or Delete.

If you call a method from the other group, it throws before any request leaves the SDK. A collection method on an instance that has a UID throws InvalidOperationException, and a single-branch method on an instance with no UID throws ArgumentException.

The Method Index below lists every method in each group.

**Warning:** The SDK checks for an empty string as if it were no UID, so stack.Branch("") allows Create and Query, and Fetch and Delete throw ArgumentException. Pass null, or call stack.Branch() with no argument, when you mean the collection.

**Warning:** Set the branch UID only through stack.Branch("<BRANCH\_UID>"). The instance also has a settable Uid property, but the SDK builds the request path when you call stack.Branch(). Setting Uid later changes which methods the SDK allows without changing which branch the request targets.

## Class-Level Notes

**Authentication.**

*   stack.Branch() throws InvalidOperationException when the client has no authtoken and the Stack has no management token.
*   The CMA accepts only an authtoken for Create and Delete. The SDK does not check the token type, so a request authenticated with a management token passes the SDK check and the API rejects it.
*   When the Stack has a management token, the SDK sends it instead of the client's authtoken. Create the Stack without a management token before you call Create or Delete.
*   Only stack owners, admins, and developers can create a branch.

**The branch UID comes from the instance.**

*   Every method sends its request to /stacks/branches or /stacks/branches/<BRANCH\_UID>, using the UID you passed to stack.Branch().
*   The branchUid argument of client.Stack() adds a branch header to every request from that Stack. Branch methods act on the UID in the request path, so the header does not change which branch they fetch or delete.

**Errors.**

*   The SDK throws ContentstackErrorException when the API returns an error status. Read StatusCode, ErrorCode, ErrorMessage, and Errors on the exception to see what the API rejected.
*   A method that returns without throwing returns a ContentstackResponse with a success status. Read its body with OpenJsonObjectResponse() or OpenTResponse<T>().

**Rate Limiting & Retry.**

*   This SDK automatically retries a request that returns 429, 500, 502, 503, or 504, up to RetryLimit times (default 5). It waits longer before each retry, starting from RetryDelay (default 300 ms), and follows the API's Retry-After header when one is present.
*   The SDK does not retry 422. This matters right after Create, as the next note explains.

**Additional Resources:** Refer to [Retry Mechanism](/docs/developers/sdks/content-management-sdk/dot-net/retry-mechanism) to configure retry limits and delay, and [Management API Errors](/docs/developers/apis/content-management-api#errors) for the error codes the API returns.

**The API creates a branch in the background.**

*   Create returns as soon as the API accepts the request. The API then copies the source branch content into the new branch.
*   Until the copy finishes, Fetch and Delete on the new branch fail with 422 and an error message such as "branch is not valid". Retry those calls with a delay in your own code. The CreateAsync page shows a retry loop.
*   The API creates one branch at a time across an organization. Other create requests wait in the organization's bulk task queue. A new branch takes longer to become ready when other requests are ahead of it.

**Async methods.**

*   A task you read through .Result or .Wait() wraps an API error in AggregateException, so a catch (ContentstackErrorException) block does not catch it. await every async method at the call site.

## Capability Matrix

Capability

Supported

Notes / Alternative

Rename or update a branch

No

The CMA has no update endpoint for branches. Update and UpdateAsync exist on the class through inheritance, and the API rejects the request. Create a new branch instead.

Select the environments a new branch clones

No

BranchModel has no field for publish\_config, so the new branch clones all environments. Create the branch in the Contentstack UI, or send the Create a Branch request of the [Content Management API](/docs/developers/apis/content-management-api) with publish\_config, to clone a subset.

Compare or merge branches

No

Use the [compare and merge](/docs/headless-cms/about-compare-and-merge-branches) feature through the CLI or the CMA.

Create, update, or delete a branch alias

No

BranchModel.Alias lists the aliases a fetched branch has, and nothing in this SDK changes them.

Delete a branch that another branch uses as its source

No

Delete the child branches first.

## Method Index

**Work with the branch collection.** Available on stack.Branch() when you pass no UID.

Method Name

Returns

Description

[Create](/docs/developers/sdks/content-management-sdk/dot-net/reference/branch#branch-create)

The new branch's details.

Creates a branch from a source branch.

[CreateAsync](/docs/developers/sdks/content-management-sdk/dot-net/reference/branch#branch-createasync)

Task<ContentstackResponse>. The new branch's details.

Creates a branch from a source branch asynchronously.

[Query](/docs/developers/sdks/content-management-sdk/dot-net/reference/branch#branch-query)

A query for the branches in the stack.

Builds a query that lists branches.

**Work with one branch.** Available on stack.Branch("<BRANCH\_UID>").

Method Name

Returns

Description

[Delete](/docs/developers/sdks/content-management-sdk/dot-net/reference/branch#branch-delete)

The deletion notice.

Deletes a branch and all its content.

[DeleteAsync](/docs/developers/sdks/content-management-sdk/dot-net/reference/branch#branch-deleteasync)

Task<ContentstackResponse>. The deletion notice.

Deletes a branch and all its content asynchronously.

[Fetch](/docs/developers/sdks/content-management-sdk/dot-net/reference/branch#branch-fetch)

The requested branch.

Retrieves one branch.

[FetchAsync](/docs/developers/sdks/content-management-sdk/dot-net/reference/branch#branch-fetchasync)

Task<ContentstackResponse>. The requested branch.

Retrieves one branch asynchronously.

## Class-Level Snippet

This snippet creates a branch from main, lists the branches in the stack, and deletes an existing branch.

```
using System;
using System.Threading.Tasks;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");
Stack stack = client.Stack("<API_KEY>");

try
{
    // Branch UIDs are lowercase, use "_" between words, and have at most 15 characters.
    BranchModel model = new BranchModel() { Uid = "<BRANCH_UID>", Source = "main" };
    await stack.Branch().CreateAsync(model);

    ContentstackResponse list = await stack.Branch().Query().IncludeCount().FindAsync();
    JsonObject branches = list.OpenJsonObjectResponse();
    Console.WriteLine($"Branches in the stack: {branches["count"]}");

    // The API deletes a branch only when the request carries force=true.
    ParameterCollection force = new ParameterCollection();
    force.Add("force", true);
    await stack.Branch("<OLD_BRANCH_UID>").DeleteAsync(force);
}
catch (ContentstackErrorException ex)
{
    // The API rejected the request, for example a duplicate UID or an unknown source branch
    Console.WriteLine($"API error {(int)ex.StatusCode} ({ex.ErrorCode}): {ex.ErrorMessage}");
}
```

## Methods

Each method of the Branch class has its own section below, with its parameters, validation rules, behavior, and examples.

## Create

Create creates a branch in the stack from the source branch you name.

```
The new branch's details.
ValidationThrows InvalidOperationException if the instance has a branch UID, because Create posts to the branch collection, not to one branch. Call stack.Branch() with no UID.Throws ArgumentNullException (parameter dataModel) if model is null, because the SDK builds the request body from the model.The SDK does not check the fields of model. The API rejects the following four cases, and the SDK throws each rejection as ContentstackErrorException:A null or empty Uid or Source fails API validation.A Uid that is uppercase, contains characters other than letters, digits, and _, or has more than 15 characters fails API validation.A Source that names no existing branch fails API validation.A Uid that already exists in the stack fails API validation.collection set to null sends no extra query parameters.Additional Resource: Refer to Management API Errors for the error codes the API returns.
BehaviorSends one POST request to /stacks/branches, with model serialized under a branch key.Reads only Uid and Source from model in a useful way. CreatedBy, UpdatedBy, CreatedAt, UpdatedAt, and Alias are response fields, and the API sets them.Returns as soon as the API accepts the request, and the API copies the source branch content in the background. The response holds a notice and the new branch under the branch key.Clones all environments of the source branch into the new branch, because BranchModel cannot send the publish_config setting that selects environments.LimitationsDoes not wait for the branch to be ready. Retry the Fetch method with a delay until it succeeds.Does not accept a management token. The API requires an authtoken to create a branch.ExampleBasic usage: create a branch from mainusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

BranchModel model = new BranchModel()
{
    Uid = "<BRANCH_UID>",
    Source = "main"
};

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Branch().Create(model);
    Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException ex)
{
    // The API rejected the request, for example a duplicate UID or an unknown source branch
    Console.WriteLine($"API error {(int)ex.StatusCode} ({ex.ErrorCode}): {ex.ErrorMessage}");
}All parameters: create a branch with a query parameter collectionusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

BranchModel model = new BranchModel()
{
    Uid = "<BRANCH_UID>",
    Source = "<SOURCE_BRANCH_UID>"
};

ParameterCollection collection = new ParameterCollection();
collection.Add("<PARAMETER_NAME>", "<PARAMETER_VALUE>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Branch().Create(model, collection);
}
catch (ContentstackErrorException ex)
{
    Console.WriteLine($"API error {(int)ex.StatusCode}: {ex.ErrorMessage}");
}Edge case: calling Create on an instance that has a UIDusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

BranchModel model = new BranchModel() { Uid = "<BRANCH_UID>", Source = "main" };

try
{
    // The UID belongs in the model, not in Branch().
    client.Stack("<API_KEY>").Branch("<BRANCH_UID>").Create(model);
}
catch (InvalidOperationException ex)
{
    // Fires before any request, because the instance has a UID
    Console.WriteLine(ex.Message);
}
```

Sets the new branch UID and its source branch.

Adds query parameters to the request.

## CreateAsync

CreateAsync creates a branch in the stack from the source branch you name, without blocking the calling thread.

```
The new branch's details.
ValidationThrows InvalidOperationException if the instance has a branch UID, because CreateAsync posts to the branch collection, not to one branch. Call stack.Branch() with no UID.Throws ArgumentNullException (parameter dataModel) if model is null, because the SDK builds the request body from the model.The SDK throws the two exceptions above when you call CreateAsync, before it returns a task.The SDK does not check the fields of model. The API rejects the following four cases, and each rejection surfaces as ContentstackErrorException when you await the task:A null or empty Uid or Source fails API validation.A Uid that is uppercase, contains characters other than letters, digits, and _, or has more than 15 characters fails API validation.A Source that names no existing branch fails API validation.A Uid that already exists in the stack fails API validation.collection set to null sends no extra query parameters.Additional Resource: Refer to Management API Errors for the error codes the API returns.
BehaviorSends one POST request to /stacks/branches, with model serialized under a branch key.Reads only Uid and Source from model in a useful way. CreatedBy, UpdatedBy, CreatedAt, UpdatedAt, and Alias are response fields, and the API sets them.Completes the task as soon as the API accepts the request, and the API copies the source branch content in the background. The response holds a notice and the new branch under the branch key.Clones all environments of the source branch into the new branch, because BranchModel cannot send the publish_config setting that selects environments.LimitationsDoes not wait for the branch to be ready. Retry the FetchAsync method with a delay until it succeeds.Does not accept a management token. The API requires an authtoken to create a branch.ExampleBasic usage: create a branch from mainusing System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

BranchModel model = new BranchModel()
{
    Uid = "<BRANCH_UID>",
    Source = "main"
};

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").Branch().CreateAsync(model);
    Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException ex)
{
    // The API rejected the request, for example a duplicate UID or an unknown source branch
    Console.WriteLine($"API error {(int)ex.StatusCode} ({ex.ErrorCode}): {ex.ErrorMessage}");
}All parameters: create a branch with a query parameter collectionusing System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

BranchModel model = new BranchModel()
{
    Uid = "<BRANCH_UID>",
    Source = "<SOURCE_BRANCH_UID>"
};

ParameterCollection collection = new ParameterCollection();
collection.Add("<PARAMETER_NAME>", "<PARAMETER_VALUE>");

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").Branch().CreateAsync(model, collection);
}
catch (ContentstackErrorException ex)
{
    Console.WriteLine($"API error {(int)ex.StatusCode}: {ex.ErrorMessage}");
}Edge case: wait until the new branch is readyusing System;
using System.Net;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");
Stack stack = client.Stack("<API_KEY>");

BranchModel model = new BranchModel() { Uid = "<BRANCH_UID>", Source = "main" };

try
{
    await stack.Branch().CreateAsync(model);

    // The API copies content in the background and returns 422 until the copy finishes.
    for (int attempt = 1; attempt <= 10; attempt++)
    {
        try
        {
            await stack.Branch("<BRANCH_UID>").FetchAsync();
            Console.WriteLine("The branch is ready.");
            break;
        }
        catch (ContentstackErrorException ex) when (ex.StatusCode == (HttpStatusCode)422 && attempt < 10)
        {
            await Task.Delay(TimeSpan.FromSeconds(2));
        }
    }
}
catch (ContentstackErrorException ex)
{
    Console.WriteLine($"API error {(int)ex.StatusCode}: {ex.ErrorMessage}");
}
```

Sets the new branch UID and its source branch.

Adds query parameters to the request.

## Delete

Delete deletes the branch whose UID you passed to stack.Branch(), together with all its content.

```
The deletion notice.
ValidationThrows ArgumentException (parameter uid) if the instance has no UID or an empty string, because Delete removes one branch. Call stack.Branch("<BRANCH_UID>").The SDK does not add force=true for you. Without it in collection, the API does not delete the branch. collection set to null sends no query parameters.The SDK does not check the UID format. A UID that names no branch reaches the API and fails there.The API rejects the request, even with force=true, if another branch uses this branch as its source, because deleting it would remove the source of that branch. Delete each child branch first, starting from the branches that no other branch uses as a source.The API rejects the request with 422 if you created the branch moments ago, because the API is still copying its content into it. Retry Delete with a delay until it succeeds.Additional Resource: Refer to Management API Errors for the error codes the API returns.
BehaviorSends one DELETE request to /stacks/branches/<BRANCH_UID>, with the entries of collection as query parameters.Returns as soon as the API accepts the request, and the API deletes the branch in the background through the organization's bulk task queue. The response holds a notice and the branch under the branch key.Deletes the content of the branch and every alias that points to it.Requires an authtoken. The API rejects a request that carries a management token.Warning: Deleting a branch is irreversible. The SDK and the API offer no way to restore the branch, its content, or its aliases.
ExampleBasic usage: delete a branchusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

// The API deletes a branch only when the request carries force=true.
ParameterCollection collection = new ParameterCollection();
collection.Add("force", true);

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Branch("<BRANCH_UID>").Delete(collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException ex)
{
    // The API rejected the request, for example an unknown UID or a branch with child branches
    Console.WriteLine($"API error {(int)ex.StatusCode} ({ex.ErrorCode}): {ex.ErrorMessage}");
}Error handling: deleting a branch that has child branchesusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

ParameterCollection collection = new ParameterCollection();
collection.Add("force", true);

try
{
    client.Stack("<API_KEY>").Branch("<PARENT_BRANCH_UID>").Delete(collection);
}
catch (ContentstackErrorException ex)
{
    // Fires when another branch uses this branch as its source. Delete those branches first.
    Console.WriteLine($"API error {(int)ex.StatusCode}: {ex.ErrorMessage}");
}
```

Adds query parameters. Pass force=true to confirm deletion.

## DeleteAsync

DeleteAsync deletes the branch whose UID you passed to stack.Branch(), together with all its content, without blocking the calling thread.

```
The deletion notice.
ValidationThrows ArgumentException (parameter uid) if the instance has no UID or an empty string, because DeleteAsync removes one branch. Call stack.Branch("<BRANCH_UID>").The SDK throws the exception above when you call DeleteAsync, before it returns a task.The SDK does not add force=true for you. Without it in collection, the API does not delete the branch. collection set to null sends no query parameters.The SDK does not check the UID format. A UID that names no branch reaches the API and fails there.The API rejects the request, even with force=true, if another branch uses this branch as its source, because deleting it would remove the source of that branch. Delete each child branch first, starting from the branches that no other branch uses as a source.The API rejects the request with 422 if you created the branch moments ago, because the API is still copying its content into it. Retry DeleteAsync with a delay until it succeeds.Additional Resource: Refer to Management API Errors for the error codes the API returns.
BehaviorSends one DELETE request to /stacks/branches/<BRANCH_UID>, with the entries of collection as query parameters.Returns as soon as the API accepts the request, and the API deletes the branch in the background through the organization's bulk task queue. The response holds a notice and the branch under the branch key.Deletes the content of the branch and every alias that points to it.Requires an authtoken. The API rejects a request that carries a management token.Warning: Deleting a branch is irreversible. The SDK and the API offer no way to restore the branch, its content, or its aliases.
ExampleBasic usage: delete a branchusing System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

// The API deletes a branch only when the request carries force=true.
ParameterCollection collection = new ParameterCollection();
collection.Add("force", true);

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").Branch("<BRANCH_UID>").DeleteAsync(collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException ex)
{
    // The API rejected the request, for example an unknown UID or a branch with child branches
    Console.WriteLine($"API error {(int)ex.StatusCode} ({ex.ErrorCode}): {ex.ErrorMessage}");
}Edge case: delete a branch right after creating itusing System;
using System.Net;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");
Stack stack = client.Stack("<API_KEY>");

ParameterCollection collection = new ParameterCollection();
collection.Add("force", true);

// The API returns 422 until it finishes copying content into the new branch.
for (int attempt = 1; attempt <= 10; attempt++)
{
    try
    {
        await stack.Branch("<BRANCH_UID>").DeleteAsync(collection);
        break;
    }
    catch (ContentstackErrorException ex) when (ex.StatusCode == (HttpStatusCode)422 && attempt < 10)
    {
        await Task.Delay(TimeSpan.FromSeconds(2));
    }
    catch (ContentstackErrorException ex)
    {
        Console.WriteLine($"API error {(int)ex.StatusCode}: {ex.ErrorMessage}");
        break;
    }
}
```

Adds query parameters. Pass force=true to confirm deletion.

## Fetch

Fetch retrieves the details of the branch whose UID you passed to stack.Branch().

```
The requested branch.
ValidationThrows ArgumentException (parameter uid) if the instance has no UID or an empty string, because Fetch reads one branch. Call stack.Branch("<BRANCH_UID>").The SDK does not check the UID format. A UID that names no branch reaches the API and fails there. The SDK throws the API rejection as ContentstackErrorException.collection set to null sends no extra query parameters.The API rejects the request with 422 if you created the branch moments ago, because the API is still copying its content into it. Retry Fetch with a delay until it succeeds.Additional Resource: Refer to Management API Errors for the error codes the API returns.
BehaviorSends one GET request to /stacks/branches/<BRANCH_UID>.Returns the raw API response. The branch details sit under the branch key and include the fields that BranchModel describes.ExampleBasic usage: fetch a branch by UIDusing System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Branch("<BRANCH_UID>").Fetch();
    JsonObject json = response.OpenJsonObjectResponse();
    Console.WriteLine($"Source branch: {json["branch"]?["source"]}");
}
catch (ContentstackErrorException ex)
{
    // The API rejected the request, for example an unknown branch UID
    Console.WriteLine($"API error {(int)ex.StatusCode} ({ex.ErrorCode}): {ex.ErrorMessage}");
}All parameters: fetch a branch with a query parameter collectionusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

ParameterCollection collection = new ParameterCollection();
collection.Add("<PARAMETER_NAME>", "<PARAMETER_VALUE>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Branch("<BRANCH_UID>").Fetch(collection);
}
catch (ContentstackErrorException ex)
{
    Console.WriteLine($"API error {(int)ex.StatusCode}: {ex.ErrorMessage}");
}Edge case: read the response into BranchModelusing System;
using System.Text.Json;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Branch("<BRANCH_UID>").Fetch();

    // The branch sits under the "branch" key, so deserialize that node, not the whole body.
    BranchModel? branch = response.OpenJsonObjectResponse()["branch"]?.Deserialize<BranchModel>();
    Console.WriteLine($"{branch?.Uid} was created from {branch?.Source} at {branch?.CreatedAt}");
}
catch (ContentstackErrorException ex)
{
    Console.WriteLine($"API error {(int)ex.StatusCode}: {ex.ErrorMessage}");
}
```

Adds query parameters to the request.

## FetchAsync

FetchAsync retrieves the details of the branch whose UID you passed to stack.Branch(), without blocking the calling thread.

```
The requested branch.
ValidationThrows ArgumentException (parameter uid) if the instance has no UID or an empty string, because FetchAsync reads one branch. Call stack.Branch("<BRANCH_UID>").The SDK throws the exception above when you call FetchAsync, before it returns a task.The SDK does not check the UID format. A UID that names no branch reaches the API and fails there. The rejection surfaces when you await the task, as ContentstackErrorException.collection set to null sends no extra query parameters.The API rejects the request with 422 if you created the branch moments ago, because the API is still copying its content into it. Retry FetchAsync with a delay until it succeeds.Additional Resource: Refer to Management API Errors for the error codes the API returns.
BehaviorSends one GET request to /stacks/branches/<BRANCH_UID>.Returns the raw API response. The branch details sit under the branch key and include the fields that BranchModel describes.ExampleBasic usage: fetch a branch by UIDusing System;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").Branch("<BRANCH_UID>").FetchAsync();
    JsonObject json = response.OpenJsonObjectResponse();
    Console.WriteLine($"Source branch: {json["branch"]?["source"]}");
}
catch (ContentstackErrorException ex)
{
    // The API rejected the request, for example an unknown branch UID
    Console.WriteLine($"API error {(int)ex.StatusCode} ({ex.ErrorCode}): {ex.ErrorMessage}");
}All parameters: fetch a branch with a query parameter collectionusing System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

ParameterCollection collection = new ParameterCollection();
collection.Add("<PARAMETER_NAME>", "<PARAMETER_VALUE>");

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").Branch("<BRANCH_UID>").FetchAsync(collection);
}
catch (ContentstackErrorException ex)
{
    Console.WriteLine($"API error {(int)ex.StatusCode}: {ex.ErrorMessage}");
}Edge case: calling FetchAsync without awaiting itusing System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

Task<ContentstackResponse> task = client.Stack("<API_KEY>").Branch("<BRANCH_UID>").FetchAsync();

try
{
    // Reading .Result wraps an API rejection in AggregateException.
    ContentstackResponse response = task.Result;
}
catch (AggregateException ex) when (ex.InnerException is ContentstackErrorException apiError)
{
    Console.WriteLine($"API error {(int)apiError.StatusCode}: {apiError.ErrorMessage}");
}
```

Adds query parameters to the request.

## Query

Query returns a query object that lists the branches in the stack when you call Find or FindAsync on it.

This method takes no parameters. Chain Limit, Skip, and IncludeCount on the query object to page through the results, then call Find or FindAsync to send the request.

```
A query for the branches in the stack.
ValidationThrows InvalidOperationException if the instance has a branch UID, because Query lists the branch collection. Call stack.Branch() with no UID.Query sends no request, so it raises no API error. Errors that do occur come from the Find or FindAsync call that follows, not from Query. The SDK throws an API rejection as ContentstackErrorException.Limit, Skip, and IncludeCount each add a query parameter, and the SDK stores parameters in a dictionary that rejects duplicate keys. Two cases throw ArgumentException before any request:chaining the same method twicepassing a key in the Find collection that a chained method already setA query object keeps every parameter it has sent. If you call Find or FindAsync on it again with a collection that repeats one of those keys, it throws ArgumentException. Build a new query with stack.Branch().Query() for each request.Additional Resource: Refer to Management API Errors for the error codes the API returns.
BehaviorFind and FindAsync send one GET request to /stacks/branches, with every parameter you set as a query parameter.Returns the raw API response. The branches sit under the branches key, and count holds the total when you call IncludeCount.Does not page through the results for you. Without Limit and Skip, the API applies its own page size. To read the next page, build a new query and pass a higher Skip value.The query object has five methods:
MethodTypeDescriptionLimit(double value)QuerySets the number of branches per page.Skip(double value)QuerySets the number of branches to skip.IncludeCount()QueryAdds the total branch count.Find(ParameterCollection collection = null)ContentstackResponseSends the request and returns the branches.FindAsync(ParameterCollection collection = null)Task<ContentstackResponse>Sends the request without blocking the thread.LimitationsDoes not filter branches by field from a chained method. Pass a query parameter in the Find collection instead, as the Get All Branches request of the Content Management API describes.ExampleBasic usage: list the branches in a stackusing System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Branch().Query().Find();
    JsonArray? branches = response.OpenJsonObjectResponse()["branches"]?.AsArray();

    foreach (JsonNode? branch in branches ?? new JsonArray())
    {
        Console.WriteLine($"{branch?["uid"]} (source: {branch?["source"]})");
    }
}
catch (ContentstackErrorException ex)
{
    Console.WriteLine($"API error {(int)ex.StatusCode} ({ex.ErrorCode}): {ex.ErrorMessage}");
}Paging: read one page of branches with a countusing System;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

try
{
    ContentstackResponse response = await client
        .Stack("<API_KEY>")
        .Branch()
        .Query()
        .Limit(5)
        .Skip(0)
        .IncludeCount()
        .FindAsync();

    JsonObject json = response.OpenJsonObjectResponse();
    Console.WriteLine($"Showing {json["branches"]?.AsArray().Count} of {json["count"]} branches");
}
catch (ContentstackErrorException ex)
{
    Console.WriteLine($"API error {(int)ex.StatusCode}: {ex.ErrorMessage}");
}Edge case: setting a query parameter twice throwsusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");

Query query = client.Stack("<API_KEY>").Branch().Query().Limit(5);

ParameterCollection collection = new ParameterCollection();
collection.Add("limit", 10);

try
{
    // "limit" is already set by Limit(5), so adding it again fails.
    query.Find(collection);
}
catch (ArgumentException ex)
{
    // Fires before any request, when a query parameter is set twice
    Console.WriteLine(ex.Message);
}
```

## Branch | .NET Management SDK | Contentstack

The Branch class in the .NET Management SDK creates, fetches, lists, and deletes the branches of a stack through the Content Management API.