Contentstack Management Java SDK

View as Markdown

Overview

This reference covers the public API of the com.contentstack.sdk:cms package, with one page per class. Use it to look up method signatures, parameters, return types, validation behavior, and worked examples for every object you reach from the Contentstack client.

Before you begin This reference assumes you have installed and initialized the SDK. If you have not, complete the Java Management SDK Get Started guide first. This SDK requires Java 8 or later, because the package targets Java 1.8. This reference documents version 1.16.0, and the changelog lists behavior changes between releases.

Minimum Working Example

The program below builds a client, opens a stack with a management token, fetches one entry, and prints the response.

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

import java.io.IOException;

public class FetchEntry {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        Entry entry = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType("<CONTENT_TYPE_UID>")
                .entry("<ENTRY_UID>");

        Response<ResponseBody> response = entry.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());
    }
}

SDK Structure

The SDK uses a builder pattern. Contentstack.Builder creates the client. Each call from the client returns an object for a narrower scope, such as a stack, a content type, an entry, or an asset. A request method, such as fetch, find, create, update, publish, or delete, builds the request. It returns a Retrofit Call without sending it. You send it with execute(), or with enqueue() to run it in the background. Every chain starts at the Contentstack client.

A request method does not throw when the API rejects the request. execute() returns a Response whose isSuccessful() is false, with the error in errorBody(). execute() throws an IOException only when the request does not complete, for example after a timeout. Header and parameter methods such as addParam store a value and send nothing, so an invalid value surfaces in the response of the request you send next. Some methods check their input first and throw, and each method page lists its own checks.

Class Overview

Build the client and sign in. The classes in the table below create and configure the client and handle sign-in.

ClassRoleAccessed via
ContentstackThe client that logs in and opens stacks, organizations, and the user account.new Contentstack.Builder().build()
Contentstack.BuilderThe settings of a client, such as host, region, timeouts, proxy, retry, and Open Authorization (OAuth).new Contentstack.Builder()
UserThe logged-in Contentstack account.client.user()
OrganizationOne organization, with its users, roles, stacks, and audit log.client.organization(uid)
OAuthHandlerThe OAuth sign-in flow of a client.client.getOAuthHandler()
OAuthConfigThe app, client, redirect, and scope settings of an OAuth sign-in.OAuthConfig.builder()
OAuthTokensThe tokens and account details from an OAuth sign-in.client.getOAuthTokens()
RetryConfigHow many times the SDK retries a failed request, and which failures trigger a retry.RetryConfig.builder()
RetryDelayOptionsHow long the SDK waits before each retry.RetryDelayOptions.builder()
ErrorMaps the JSON error body of a rejected request to a message, a code, and details.new Gson().fromJson(body, Error.class)

Work with a stack and its settings. The classes in the table below cover the stack, its tokens, environments, and languages.

ClassRoleAccessed via
StackOne stack, and the start of every module chain.client.stack(apiKey, managementToken)
TokensThe token modules of a stack.stack.tokens()
DeliveryTokenThe delivery tokens of a stack.tokens.deliveryTokens()
ManagementTokenThe management tokens of a stack.tokens.managementToken()
EnvironmentThe publishing environments of a stack.stack.environment()
LocaleThe languages of a stack and their fallback languages.stack.locale()

Model and edit content. The classes in the table below cover content types, entries, global fields, assets, and extensions.

ClassRoleAccessed via
ContentTypeOne content type and its schema.stack.contentType(uid)
EntryThe entries of one content type, including entry variants.contentType.entry(uid)
GlobalFieldThe reusable global fields of a stack.stack.globalField(uid)
AssetThe files of a stack.stack.asset(uid)
FolderThe asset folders of a stack.asset.folder(uid)
ExtensionsThe custom field extensions of a stack.stack.extensions(uid)
LabelThe labels that group content types.stack.label(uid)
TaxonomyThe taxonomies of a stack.stack.taxonomy(uid)
TermsThe terms of one taxonomy.taxonomy.terms()
VariantGroupThe variant groups of a stack and their linked content types.stack.variantGroup(uid)

Branch, release, and publish. The classes in the table below cover branches, Releases, bulk actions, and the publish queue.

ClassRoleAccessed via
BranchThe branches of a stack.stack.branch(uid)
AliasThe branch aliases of a stack.stack.alias(uid)
CompareA comparison between two branches.branch.compare()
MergeA branch merge and its merge jobs.branch.mergeQueue()
ReleaseThe Releases of a stack.stack.releases(uid)
ReleaseItemThe entries and assets of one Release.release.item()
BulkOperationPublish, unpublish, delete, and workflow changes for many items in one request.stack.bulkOperation()
PublishQueueThe publish queue of a stack.stack.publishQueue(uid)

Govern the stack. The classes in the table below cover workflows, roles, webhooks, and the audit log.

ClassRoleAccessed via
WorkflowThe workflows and publish rules of a stack.stack.workflow(uid)
RolesThe roles of a stack.stack.roles(uid)
WebhookThe webhooks of a stack and their executions.stack.webhook(uid)
AuditLogThe audit log of a stack.stack.auditLog(uid)

Task Index

TaskStart hereClass
Open a stack with a management tokenstackContentstack
Log in with an email and passwordloginContentstack
Fetch one entry by UIDfetchEntry
List the entries of a content typefindEntry
Create an entrycreateEntry
Publish an entry to an environmentpublishEntry
Upload a file as an assetuploadAssetAsset
Publish many entries and assets at oncepublishBulkOperation
Create a branchcreateBranch
Deploy a ReleasedeployRelease
Point the client at another regionsetRegionContentstack.Builder
Change the retry settings for failed requestssetRetryConfigContentstack.Builder
Sign in with OAuthsetOAuthContentstack.Builder

Key Usage Patterns

The examples below assume the imports from the Minimum Working Example, a main that declares throws IOException, and a client built with new Contentstack.Builder().build(). Each example lists any extra import it needs.

Create an entry, then publish it

// Extra imports: org.json.simple.JSONArray, org.json.simple.JSONObject
Entry entries = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .contentType("<CONTENT_TYPE_UID>")
        .entry();

JSONObject fields = new JSONObject();
fields.put("title", "docs-test-blog-post");
fields.put("url", "/docs-test-blog-post");
JSONObject createBody = new JSONObject();
createBody.put("entry", fields);

Response<ResponseBody> created = entries.create(createBody).execute();
if (!created.isSuccessful()) { System.out.println(created.errorBody().string()); return; }
System.out.println(created.body().string());

// Read the new entry's UID from the response, then publish it
JSONArray environments = new JSONArray();
environments.add("<ENVIRONMENT>");
JSONObject details = new JSONObject();
details.put("environments", environments);
JSONObject publishBody = new JSONObject();
publishBody.put("entry", details);

Response<ResponseBody> published = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .contentType("<CONTENT_TYPE_UID>")
        .entry("<ENTRY_UID>")
        .publish(publishBody)
        .execute();
if (!published.isSuccessful()) { System.out.println(published.errorBody().string()); return; }
System.out.println(published.body().string());

Upload a file as an asset

// Extra import: com.contentstack.cms.stack.Asset
Asset asset = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").asset();

Response<ResponseBody> response = asset.uploadAsset("<FILE_PATH>", "Hero image for the spring campaign").execute();
if (!response.isSuccessful()) { System.out.println(response.errorBody().string()); return; }
System.out.println(response.body().string());

Log in and list the stacks of an organization

// Extra import: com.contentstack.cms.organization.Organization
client.login("<EMAIL>", "<PASSWORD>");

Organization organization = client.organization("<ORGANIZATION_UID>");
Response<ResponseBody> response = organization.stacks().execute();
if (!response.isSuccessful()) { System.out.println(response.errorBody().string()); return; }
System.out.println(response.body().string());

Target another region with longer timeouts and more retries

// Extra import: com.contentstack.cms.core.RetryConfig
RetryConfig retry = RetryConfig.builder()
        .retryLimit(5)
        .retryDelay(1000)
        .build();

Contentstack euClient = new Contentstack.Builder()
        .setRegion("eu")
        .setTimeout(60)
        .setRetryConfig(retry)
        .build();
System.out.println(euClient.getHost());

Read a rejected request as an Error object

// Extra imports: com.contentstack.cms.models.Error, com.google.gson.Gson
Response<ResponseBody> response = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .contentType("<CONTENT_TYPE_UID>")
        .entry("<ENTRY_UID>")
        .fetch()
        .execute();
if (!response.isSuccessful()) {
    Error error = new Gson().fromJson(response.errorBody().string(), Error.class);
    System.out.println(response.code() + " " + error.getErrorCode() + ": " + error.getErrorMessage());
    System.out.println(error.getErrors());
    return;
}
System.out.println(response.body().string());

SDK-Wide Notes

ConcernBehaviorDefault when unset
Authenticationclient.stack(apiKey, managementToken) sends the API key and management token as the api_key and authorization headers on every request from that stack. login stores an authtoken on the client for requests that need a user session, such as Organization and User requests. setOAuth on the Builder signs in with OAuth instead.No credentials. user(), organization(), and stack() without arguments throw IllegalStateException until you log in or configure OAuth.
Error surfacingA rejected request does not throw. response.isSuccessful() is false, and response.errorBody() holds error_message, error_code, and errors, which Error maps. execute() throws IOException when the request does not complete.Not applicable.
Regions and endpointsCall setRegion on the Builder with na (also us), eu, au, azure-na, azure-eu, gcp-na, or gcp-eu. setHost sets a host directly, and the last of the two you call wins.api.contentstack.io, the North America region.
BranchesPass the branch to client.stack(apiKey, managementToken, branch), and the SDK sends it as the branch header on every request from that stack.No branch header, so the API uses the main branch.
Rate limiting and retryThis SDK automatically retries on 429 with configurable delay and attempt limits. It also retries 408, 500, 502, 503, 504, and timeouts. See RetryConfig.3 retries, 300 milliseconds apart.
TimeoutssetTimeout on the Builder sets the connect, read, and write timeouts in seconds. setConnectTimeout, setReadTimeout, and setWriteTimeout set one each.30 seconds each.
Proxy configurationCall setProxy on the Builder with a java.net.Proxy.No proxy set on the client, so the JVM's default proxy settings apply.
Request bodiesMethods that send a body take an org.json.simple.JSONObject from the json-simple library, which the SDK includes. The SDK leaves out fields set to null unless you call setSerializeNulls(true) on the Builder.The SDK drops null fields.

Warning Stack, organization, and user-account requests need a user session, so these requests reject a management token alone. Log in with login or OAuth before you call them, as each method page states. Refer to Content Management API Errors for the full error code list.

SDK Limitations

CapabilitySupportedNotes / Alternative
Read the error body of a failed request on an OAuth clientNoAn OAuth client closes the body of an error it does not retry, such as 404, so execute() throws. Set retryLimit(0) on RetryConfig and retry in your own code.
Read the error details of a failed loginNoThe SDK reads the error body before login returns. Use response.code() and response.message().
Import entries, content types, or webhooks from a fileNoThe import methods send no file. Send the import request with your own HTTP client, as each import method page describes.
Compare two branchesNoCompare has no public method that sends a request. Send the Compare branches request with your own HTTP client.