Branch

View as Markdown

Branch

A branch is an isolated copy of the content types, global fields, and content of a stack. Use this class to

  • list the branches of a stack, or read one branch
  • create a branch from a source branch, and choose the environments it clones
  • delete a branch
  • start a branch comparison or a branch merge from a base branch

stack.branch() and stack.branch("<BRANCH>") return a Branch. Branch has no public constructor.

NameTypeDescription
branchUidStringUID of the branch. Pass it to stack.branch() for methods that act on one branch.

addHeader

addHeader adds one request header to this branch.

NameTypeDescription
key (required)String

Name of the header.

Default: Not applicable
value (required)String

Value of the header.

Default: Not applicable

Returns: Branch. The same branch, for chaining.

Validation

  • There is no client-side validation. A null key or value does not throw here.
  • execute() throws IllegalArgumentException for a null key or value, because Retrofit rejects null entries in a header map.
  • An invalid value surfaces as an API error in the response when you call execute() on the request this method feeds.

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

Behavior

  • addHeader stores the header in the header map of this object and sends nothing.
  • A later call with the same name replaces the value.
  • The header goes on every request of this branch object: find, fetch, create, and delete, and stays there for every later request.
  • The Compare and Merge objects from compare and mergeQueue do not receive these headers.

Example

Basic usage: list branches with an authtoken in place of a management token

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

public class ListBranchesWithAuthtoken {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();

        // client.stack(key) sends a key that starts with "blt" as the api_key header
        Response<ResponseBody> response = client.stack("<API_KEY>")
                .branch()
                .addHeader("authtoken", "<AUTHTOKEN>")
                .find()
                .execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

addHeaders

addHeaders adds every entry of a map to the request headers of this branch.

NameTypeDescription
headers (required)HashMap

Header names mapped to their values.

Default: Not applicable

Returns: Branch. The same branch, for chaining.

Validation

  • Throws NullPointerException if headers is null, because addHeaders copies every entry of the map.
  • execute() throws IllegalArgumentException for a null key or value in the map, because Retrofit rejects null entries in a header map.
  • An invalid value surfaces as an API error in the response when you call execute() on the request this method feeds.

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

Behavior

  • addHeaders copies the entries into the header map of this object and sends nothing.
  • An entry replaces a header with the same name.
  • The headers go on every request of this branch object: find, fetch, create, and delete, and stay there for every later request.
  • The Compare and Merge objects from compare and mergeQueue do not receive these headers.

Example

Basic usage: add an authtoken header from a map

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;
import java.util.HashMap;

public class ListBranchesWithHeaderMap {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();

        HashMap<String, String> headers = new HashMap<>();
        headers.put("authtoken", "<AUTHTOKEN>");

        Response<ResponseBody> response = client.stack("<API_KEY>")
                .branch()
                .addHeaders(headers)
                .find()
                .execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

addParam

addParam adds one query parameter to this branch.

NameTypeDescription
key (required)String

Name of the query parameter.

Default: Not applicable
value (required)Object

Value of the query parameter, sent as its string form.

Default: Not applicable

Returns: Branch. The same branch, for chaining.

Validation

  • There is no client-side validation. A null key or value does not throw here.
  • execute() throws IllegalArgumentException for a null key or value, because Retrofit rejects null entries in a query map.
  • An invalid value surfaces as an API error in the response when you call execute() on the request this method feeds.

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

Behavior

  • addParam stores the pair in the query parameter map of this object and sends nothing.
  • A later call with the same key replaces the value.
  • The parameter goes on find and delete. fetch and create send no query parameters.
  • The parameter stays on the object for every later request.
  • The Compare and Merge objects from compare and mergeQueue do not receive these parameters.

Example

Basic usage: add the total count to the branch list

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

public class CountBranches {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();

        Response<ResponseBody> response = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .branch()
                .addParam("include_count", true)
                .find()
                .execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

addParams

addParams adds every entry of a map to the query parameters of this branch.

NameTypeDescription
params (required)HashMap

Query parameter names mapped to their values.

Default: Not applicable

Returns: Branch. The same branch, for chaining.

Validation

  • Throws NullPointerException if params is null, because addParams copies every entry of the map.
  • execute() throws IllegalArgumentException for a null key or value in the map, because Retrofit rejects null entries in a query map.
  • An invalid value surfaces as an API error in the response when you call execute() on the request this method feeds.

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

Behavior

  • addParams copies the entries into the query parameter map of this object and sends nothing.
  • An entry replaces a parameter with the same name.
  • The parameters go on find and delete. fetch and create send no query parameters.
  • The parameters stay on the object for every later request.
  • The Compare and Merge objects from compare and mergeQueue do not receive these parameters.

Example

Basic usage: page through branches with several parameters

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;
import java.util.HashMap;

public class PageBranches {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();

        HashMap<String, Object> params = new HashMap<>();
        params.put("limit", 10);
        params.put("skip", 0);
        params.put("include_count", true);

        Response<ResponseBody> response = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .branch()
                .addParams(params)
                .find()
                .execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

compare

compare returns a Compare object that holds this branch as the base branch and the branch you name as the compare branch.

NameTypeDescription
compareBranchId (required)String

UID of the branch to compare with this branch.

Default: Not applicable

Returns: Compare. A new comparison between this branch and another branch.

Validation

  • Throws NullPointerException if you call it on stack.branch() without a UID, because only stack.branch("<BRANCH>") keeps the connection that the Compare object needs.
  • There is no check on compareBranchId. A null value goes into the compare_branch query parameter unchanged.

Behavior

  • compare sends no request. It stores the UID of this branch as base_branch and compareBranchId as compare_branch in the query parameters of the new Compare object.
  • The new object starts with its own headers and parameters. The headers and parameters of this branch object do not carry over.

Example

Basic usage: hold a comparison between two branches

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Compare;

public class CompareBranches {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder().build();

        // base_branch is "main" and compare_branch is "docs-test-branch"
        Compare compare = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .branch("main")
                .compare("docs-test-branch");

        // Compare has no public request method in 1.16.0, so nothing is sent
        compare.addParam("limit", 50);
        System.out.println("Stored base_branch main and compare_branch docs-test-branch.");
    }
}

create

create builds the request that creates a branch from the source branch you name, and can limit which environments the new branch clones.

NameTypeDescription
body (required)JSONObject

Request body with the branch details under a branch key.

Default: Not applicable
body.branch.uid (required)String

Sets the UID of the new branch.

Default: Not applicable
body.branch.source (required)String

Names the branch to copy, for example main.

Default: Not applicable
body.branch.publish_config.environmentsList<String>

Lists the environment names, not UIDs, to clone.

Default: Not set (clones all environments)

Returns: Call<ResponseBody>. The request for the new branch, sent when you call execute().

Validation

  • There is no client-side validation of body. The SDK sends the object unchanged, including the environment list, and does not check the names or the list length.
  • execute() throws IllegalArgumentException if body is null, because Retrofit cannot build a request without a body.
  • An API rejection does not throw. response.isSuccessful() is false and the error details are in response.errorBody().
  • The API rejects the following three cases and creates no branch:
    • An environment name that does not exist in the stack, alone or mixed with valid names, fails with HTTP 422 and error code 912.
    • An environment list longer than the API maximum fails with error code 911.
    • A missing or invalid uid or source, or a uid that already exists in the stack, fails API validation.

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

Behavior

  • One execute() sends one Create a branch request (POST /stacks/branches) with body as the JSON request body. create sends no query parameters.
  • The publish_config.environments list decides which environments the API clones into the new branch, in one of the following three ways:
    • A list of environment names clones only those environments.
    • An empty list ([]) clones no environments.
    • When you omit publish_config, the API clones all environments.
  • The API returns the resolved environment list under branch.publish_config.environments in the response. The API removes duplicate names, and the order can differ from the order you sent.
  • The API copies the source branch content in the background, so the response returns before the new branch is ready.

Limitations

  • Does 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, so log in with client.login() first.

Example

Basic usage: create a branch from main

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import org.json.simple.JSONObject;
import retrofit2.Response;

import java.io.IOException;

public class CreateBranch {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        // Creating a branch needs an authtoken, not a management token
        client.login("<EMAIL>", "<PASSWORD>");

        JSONObject branch = new JSONObject();
        branch.put("uid", "docs-test-branch");
        branch.put("source", "main");
        JSONObject body = new JSONObject();
        body.put("branch", branch);

        Response<ResponseBody> response = client.stack("<API_KEY>").branch().create(body).execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

All parameters: create a branch that clones only development and staging

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import org.json.simple.JSONObject;
import retrofit2.Response;

import java.io.IOException;
import java.util.Arrays;

public class CreateBranchWithEnvironments {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        client.login("<EMAIL>", "<PASSWORD>");

        // List the environments by name, not by UID
        JSONObject publishConfig = new JSONObject();
        publishConfig.put("environments", Arrays.asList("development", "staging"));

        JSONObject branch = new JSONObject();
        branch.put("uid", "docs-test-branch");
        branch.put("source", "main");
        branch.put("publish_config", publishConfig);
        JSONObject body = new JSONObject();
        body.put("branch", branch);

        Response<ResponseBody> response = client.stack("<API_KEY>").branch().create(body).execute();
        if (!response.isSuccessful()) { System.out.println(response.errorBody().string()); return; }
        System.out.println(response.body().string());
    }
}

Edge case: create a branch that clones no environments

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import org.json.simple.JSONObject;
import retrofit2.Response;

import java.io.IOException;
import java.util.Collections;

public class CreateBranchWithoutEnvironments {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        client.login("<EMAIL>", "<PASSWORD>");

        // An empty list clones no environments. Omitting publish_config clones all of them.
        JSONObject publishConfig = new JSONObject();
        publishConfig.put("environments", Collections.emptyList());

        JSONObject branch = new JSONObject();
        branch.put("uid", "docs-test-branch");
        branch.put("source", "main");
        branch.put("publish_config", publishConfig);
        JSONObject body = new JSONObject();
        body.put("branch", branch);

        Response<ResponseBody> response = client.stack("<API_KEY>").branch().create(body).execute();
        if (!response.isSuccessful()) { System.out.println(response.errorBody().string()); return; }
        System.out.println(response.body().string());
    }
}

Error handling: an environment name that does not exist

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import org.json.simple.JSONObject;
import retrofit2.Response;

import java.io.IOException;
import java.util.Arrays;

public class CreateBranchUnknownEnvironment {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        client.login("<EMAIL>", "<PASSWORD>");

        JSONObject publishConfig = new JSONObject();
        publishConfig.put("environments", Arrays.asList("development", "docs-test-missing-environment"));

        JSONObject branch = new JSONObject();
        branch.put("uid", "docs-test-branch");
        branch.put("source", "main");
        branch.put("publish_config", publishConfig);
        JSONObject body = new JSONObject();
        body.put("branch", branch);

        Response<ResponseBody> response = client.stack("<API_KEY>").branch().create(body).execute();
        if (!response.isSuccessful()) {
            // 422 with error code 912: one name does not exist, and the API creates no branch
            System.out.println("API error " + response.code() + ": " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

delete

delete builds the request that deletes the branch whose UID you passed to stack.branch(), with all the content in it.

Returns: Call<ResponseBody>. The request that deletes the branch, sent when you call execute().

Validation

  • Throws NullPointerException if the branch has no UID, as on stack.branch(), because the request path needs the branch UID.
  • Throws IllegalStateException if the UID is an empty string, for the same reason.
  • An API rejection does not throw. response.isSuccessful() is false and the error details are in response.errorBody().
  • The API refuses the deletion in the following cases:
    • The request has no force=true query parameter. Add it with addParam.
    • The branch is the source of another branch. Delete the child branches first.
    • The request carries a management token and no authtoken.

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

Behavior

  • One execute() sends one Delete a branch request (DELETE /stacks/branches/{branch_uid}) with the headers and query parameters of this branch object.
  • The SDK does not add force=true for you. The API reference marks force as required, to confirm the deletion.
  • The API accepts only an authtoken for this request. Log in with client.login() and build the stack with client.stack("<API_KEY>").

Example

Basic usage: delete a branch

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

public class DeleteBranch {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        // Deleting a branch needs an authtoken, not a management token
        client.login("<EMAIL>", "<PASSWORD>");

        Response<ResponseBody> response = client.stack("<API_KEY>")
                .branch("docs-test-branch")
                .addParam("force", true)
                .delete()
                .execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

fetch

fetch builds the request that reads one branch by the UID you passed to stack.branch().

Returns: Call<ResponseBody>. The request for the branch, sent when you call execute().

Validation

  • Throws NullPointerException if the branch has no UID, as on stack.branch(), because the request path needs the branch UID.
  • Throws IllegalStateException if the UID is an empty string, for the same reason.
  • An API rejection does not throw. response.isSuccessful() is false and the error details are in response.errorBody().

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

Behavior

  • One execute() sends one Get a single branch request (GET /stacks/branches/{branch_uid}) with the headers of this branch object.
  • fetch sends no query parameters. Values from addParam and addParams stay on the object for find and delete.
  • The API copies the source branch in the background after create. Until the copy finishes, fetch on the new branch returns an error response. Retry with a delay until response.isSuccessful() is true.

Example

Basic usage: read one branch

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

public class FetchBranch {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();

        Response<ResponseBody> response = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .branch("<BRANCH>")
                .fetch()
                .execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

Edge case: wait until a new branch is ready

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Branch;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

public class WaitForBranch {
    public static void main(String[] args) throws IOException, InterruptedException {
        Contentstack client = new Contentstack.Builder().build();
        Branch branch = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").branch("<BRANCH>");

        for (int attempt = 1; attempt <= 10; attempt++) {
            // Build a new request on each attempt. A Retrofit call runs only once.
            Response<ResponseBody> response = branch.fetch().execute();
            if (response.isSuccessful()) {
                System.out.println(response.body().string());
                return;
            }
            System.out.println("Not ready yet: " + response.errorBody().string());
            Thread.sleep(5000);
        }
        System.out.println("The branch was not ready after 10 attempts.");
    }
}

find

find builds the request that lists the branches of the stack, with the query parameters on this branch object.

Returns: Call<ResponseBody>. The request for all branches in the stack, sent when you call execute().

Validation

  • There is no client-side validation. find works on stack.branch() and on stack.branch("<BRANCH>"), and ignores the UID.
  • An API rejection does not throw. response.isSuccessful() is false and the error details are in response.errorBody().

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

Behavior

  • One execute() sends one Get all branches request (GET /stacks/branches) with the headers of this branch object.
  • find sends every query parameter from addParam and addParams. The API reference lists the following four:
    • limit: the maximum number of branches to return.
    • skip: the number of branches to skip.
    • include_count: true adds the total number of branches to the response.
    • query: a query in JSON format that filters the branches.
  • The SDK does not page through the results. Without limit and skip, the API applies its own page size.
  • The response body is the raw JSON of the API. Read it with response.body().string().

Example

Basic usage: list the branches of a stack

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

public class ListBranches {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();

        Response<ResponseBody> response = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .branch()
                .find()
                .execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

Pagination: read the second page of ten branches with the total count

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

public class ListBranchesPage {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();

        Response<ResponseBody> response = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .branch()
                .addParam("limit", 10)
                .addParam("skip", 10)
                .addParam("include_count", true)
                .find()
                .execute();
        if (!response.isSuccessful()) { System.out.println(response.errorBody().string()); return; }
        System.out.println(response.body().string());
    }
}

mergeQueue

mergeQueue returns a Merge object with this branch as the base branch, for merging another branch into it and reading merge jobs.

Returns: Merge. A new merge object with this branch as the base branch.

Validation

  • Throws NullPointerException if you call it on stack.branch() without a UID, because only stack.branch("<BRANCH>") keeps the connection that the Merge object needs.
  • There is no other client-side validation. Errors come from execute() on the requests of the Merge object.

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

Behavior

  • mergeQueue sends no request. It stores the UID of this branch as the base_branch query parameter of the new Merge object.
  • The new object starts with its own headers and parameters. The headers and parameters of this branch object, including the api_key and authorization headers of the stack, do not carry over. Add them on the Merge object with its addHeader method.
  • Use the branch method of Merge to merge, and its find and fetch methods to read merge jobs.

Example

Basic usage: merge a branch into main

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Merge;
import okhttp3.ResponseBody;
import org.json.simple.JSONObject;
import retrofit2.Response;

import java.io.IOException;

public class MergeIntoMain {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();

        // The Merge object does not inherit the stack credentials, so add them here
        Merge merge = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .branch("main")
                .mergeQueue()
                .addHeader("api_key", "<API_KEY>")
                .addHeader("authorization", "<MANAGEMENT_TOKEN>");

        Response<ResponseBody> response = merge
                .branch("docs-test-branch", new JSONObject(), "merge_prefer_base", "Merge docs-test-branch into main")
                .execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}