Contentstack Management Java SDK
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.
| Class | Role | Accessed via |
|---|---|---|
| Contentstack | The client that logs in and opens stacks, organizations, and the user account. | new Contentstack.Builder().build() |
| Contentstack.Builder | The settings of a client, such as host, region, timeouts, proxy, retry, and Open Authorization (OAuth). | new Contentstack.Builder() |
| User | The logged-in Contentstack account. | client.user() |
| Organization | One organization, with its users, roles, stacks, and audit log. | client.organization(uid) |
| OAuthHandler | The OAuth sign-in flow of a client. | client.getOAuthHandler() |
| OAuthConfig | The app, client, redirect, and scope settings of an OAuth sign-in. | OAuthConfig.builder() |
| OAuthTokens | The tokens and account details from an OAuth sign-in. | client.getOAuthTokens() |
| RetryConfig | How many times the SDK retries a failed request, and which failures trigger a retry. | RetryConfig.builder() |
| RetryDelayOptions | How long the SDK waits before each retry. | RetryDelayOptions.builder() |
| Error | Maps 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.
| Class | Role | Accessed via |
|---|---|---|
| Stack | One stack, and the start of every module chain. | client.stack(apiKey, managementToken) |
| Tokens | The token modules of a stack. | stack.tokens() |
| DeliveryToken | The delivery tokens of a stack. | tokens.deliveryTokens() |
| ManagementToken | The management tokens of a stack. | tokens.managementToken() |
| Environment | The publishing environments of a stack. | stack.environment() |
| Locale | The 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.
| Class | Role | Accessed via |
|---|---|---|
| ContentType | One content type and its schema. | stack.contentType(uid) |
| Entry | The entries of one content type, including entry variants. | contentType.entry(uid) |
| GlobalField | The reusable global fields of a stack. | stack.globalField(uid) |
| Asset | The files of a stack. | stack.asset(uid) |
| Folder | The asset folders of a stack. | asset.folder(uid) |
| Extensions | The custom field extensions of a stack. | stack.extensions(uid) |
| Label | The labels that group content types. | stack.label(uid) |
| Taxonomy | The taxonomies of a stack. | stack.taxonomy(uid) |
| Terms | The terms of one taxonomy. | taxonomy.terms() |
| VariantGroup | The 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.
| Class | Role | Accessed via |
|---|---|---|
| Branch | The branches of a stack. | stack.branch(uid) |
| Alias | The branch aliases of a stack. | stack.alias(uid) |
| Compare | A comparison between two branches. | branch.compare() |
| Merge | A branch merge and its merge jobs. | branch.mergeQueue() |
| Release | The Releases of a stack. | stack.releases(uid) |
| ReleaseItem | The entries and assets of one Release. | release.item() |
| BulkOperation | Publish, unpublish, delete, and workflow changes for many items in one request. | stack.bulkOperation() |
| PublishQueue | The 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.
| Class | Role | Accessed via |
|---|---|---|
| Workflow | The workflows and publish rules of a stack. | stack.workflow(uid) |
| Roles | The roles of a stack. | stack.roles(uid) |
| Webhook | The webhooks of a stack and their executions. | stack.webhook(uid) |
| AuditLog | The audit log of a stack. | stack.auditLog(uid) |
Task Index
| Task | Start here | Class |
|---|---|---|
| Open a stack with a management token | stack | Contentstack |
| Log in with an email and password | login | Contentstack |
| Fetch one entry by UID | fetch | Entry |
| List the entries of a content type | find | Entry |
| Create an entry | create | Entry |
| Publish an entry to an environment | publish | Entry |
| Upload a file as an asset | uploadAsset | Asset |
| Publish many entries and assets at once | publish | BulkOperation |
| Create a branch | create | Branch |
| Deploy a Release | deploy | Release |
| Point the client at another region | setRegion | Contentstack.Builder |
| Change the retry settings for failed requests | setRetryConfig | Contentstack.Builder |
| Sign in with OAuth | setOAuth | Contentstack.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
| Concern | Behavior | Default when unset |
|---|---|---|
| Authentication | client.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 surfacing | A 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 endpoints | Call 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. |
| Branches | Pass 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 retry | This 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. |
| Timeouts | setTimeout on the Builder sets the connect, read, and write timeouts in seconds. setConnectTimeout, setReadTimeout, and setWriteTimeout set one each. | 30 seconds each. |
| Proxy configuration | Call setProxy on the Builder with a java.net.Proxy. | No proxy set on the client, so the JVM's default proxy settings apply. |
| Request bodies | Methods 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
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Read the error body of a failed request on an OAuth client | No | An 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 login | No | The SDK reads the error body before login returns. Use response.code() and response.message(). |
| Import entries, content types, or webhooks from a file | No | The import methods send no file. Send the import request with your own HTTP client, as each import method page describes. |
| Compare two branches | No | Compare has no public method that sends a request. Send the Compare branches request with your own HTTP client. |