Contentstack
Contentstack
Contentstack is the client of the Java Management SDK. It holds the connection settings, the session credentials and the HTTP client that every Content Management API (CMA) request uses. Create it with Contentstack.Builder.
Use the client for the four jobs below:
- log in with an email and password, and keep the authtoken for later requests
- create the Stack, Organization and User objects that build requests
- run the Open Authorization (OAuth) flow on an OAuth client
- look up the Contentstack host of a service in a region
exchangeOAuthCode
exchangeOAuthCode exchanges the authorization code from the Open Authorization (OAuth) redirect for an access token and a refresh token, and stores them on the client.
| Name | Type | Description |
|---|---|---|
| code (required) | String | Authorization code from the redirect URI's code parameter. |
Returns: CompletableFuture<OAuthTokens>. A future that completes with the new tokens.
Validation
- exchangeOAuthCode throws IllegalStateException if the client has no OAuth settings, because the exchange needs the OAuth settings.
- When code is null, empty or only spaces, exchangeOAuthCode sends no request and returns a future that fails with IllegalArgumentException.
- When the token request fails, the future fails with a RuntimeException whose cause holds the details. get() wraps it in an ExecutionException, and join() wraps it in a CompletionException.
Behavior
- exchangeOAuthCode sends the token request on another thread and returns at once. Call get() or join() on the future to wait for the tokens.
- The request is a form POST to the OAuth token endpoint, for example https://developerhub-api.contentstack.com/token. It sends grant_type=authorization_code, the trimmed code, redirect_uri, client_id and app_id.
- With a client secret, the request adds client_secret. Without one, it adds the PKCE code_verifier that the client created at build(), so the exchange works only on the client that built the authorization URL.
- On success, the client stores the tokens, which getOAuthTokens returns. Every later request carries the access token in an Authorization: Bearer header.
- The client sets the token expiry from the expires_in value of the response.
- When the builder set a TokenCallback, the SDK calls its onTokensUpdated method with the new tokens. See Contentstack.Builder.
Example
Basic usage: authorize the app and exchange the code
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
public class ExchangeAuthorizationCode {
public static void main(String[] args) throws IOException, InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
System.out.println("Open this URL and authorize the app: " + client.getOAuthAuthorizationUrl());
System.out.print("Paste the code parameter from the redirect URI: ");
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
try {
OAuthTokens tokens = client.exchangeOAuthCode(code).get();
System.out.println("Authorized for organization " + tokens.getOrganizationUid());
} catch (ExecutionException e) {
// The code was empty, or the token endpoint rejected the request
System.out.println("Token exchange failed: " + e.getCause().getMessage());
}
}
}getBaseUrl
getBaseUrl returns the base URL that the client puts in front of every request path, so you can confirm the host and API version in use.
Returns: String. The base URL of every request.
Validation
- There is no client-side validation. getBaseUrl does not throw on a client created with build().
Behavior
- Client-side only. getBaseUrl sends no request.
- build() creates the base URL from three parts: https://, the host, and the API version, and a closing /. With the defaults, getBaseUrl returns https://api.contentstack.io/v3/.
- The version comes from setVersion, default v3.
- The base URL never contains the value of setPort. It contains a port only when the host from setHost includes one.
Example
Basic usage: print the base URL
import com.contentstack.cms.Contentstack;
public class PrintBaseUrl {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setRegion("eu")
.build();
System.out.println(client.getBaseUrl());
}
}getContentstackEndpoint
getContentstackEndpoint returns the endpoint of one Contentstack service in a region, as a full URL or as a bare host.
| Name | Type | Description |
|---|---|---|
| region (required) | String | Region ID or alias, such as "eu". |
| service (required) | String | Service key, such as "contentManagement". |
| omitHttps (required) | boolean | true returns the host without https://. |
Returns: String. The endpoint URL or host for the service.
Validation
- getContentstackEndpoint throws IllegalArgumentException in the four cases below, because it cannot return an endpoint it does not know:
- service is null, empty or only spaces.
- region is null, empty or only spaces.
- region matches no region ID or alias in the registry.
- The region has no endpoint for service. Service keys are case-sensitive.
- It also throws IllegalArgumentException when the registry entry is not an https URL on a contentstack.com or contentstack.io host.
- It throws RuntimeException only when the jar has no bundled registry and the download fails.
Behavior
- getContentstackEndpoint is static. Call it on the class.
- getContentstackEndpoint(region, service) returns the full URL, for example https://eu-api.contentstack.com for ("eu", "contentManagement").
- With omitHttps set to true, it removes the leading https:// or http://. Pass the result to setHost, which expects a host without a scheme.
- Client-side lookup in the region registry. See Region endpoints on the Contentstack class page for the matching rules and the region IDs.
- service must match a key of the region's endpoint list exactly, for example contentManagement, contentDelivery or images. Use the getContentstackEndpoints method to list the keys of a region.
Example
Basic usage: get the management URL for a region
import com.contentstack.cms.Contentstack;
public class GetManagementUrl {
public static void main(String[] args) {
try {
String url = Contentstack.getContentstackEndpoint("eu", "contentManagement");
System.out.println(url);
} catch (IllegalArgumentException e) {
// Thrown for an empty or unknown region, or a service the region does not have
System.out.println("Lookup failed: " + e.getMessage());
}
}
}All parameters: get a bare host and use it as the client host
import com.contentstack.cms.Contentstack;
public class SetHostFromRegion {
public static void main(String[] args) {
// omitHttps = true returns the host without the https:// scheme
String host = Contentstack.getContentstackEndpoint("azure-na", "contentManagement", true);
Contentstack client = new Contentstack.Builder()
.setHost(host)
.build();
System.out.println("Base URL: " + client.getBaseUrl());
}
}getContentstackEndpoints
getContentstackEndpoints returns the endpoint of every Contentstack service in a region, with the service name as the key.
| Name | Type | Description |
|---|---|---|
| region (required) | String | Region ID or alias, such as "eu". |
| omitHttps (required) | boolean | true returns hosts without https://. |
Returns: Map. The endpoint of every service in the region.
Validation
- getContentstackEndpoints throws IllegalArgumentException if region is null, empty or only spaces, or matches no region ID or alias, because it cannot pick a region.
- It also throws IllegalArgumentException when any registry entry of the region is not an https URL on a contentstack.com or contentstack.io host.
- It throws RuntimeException only when the jar has no bundled registry and the download fails.
Behavior
- getContentstackEndpoints is static. Call it on the class.
- The result is a Map<String, String>. The keys are the service names of the registry, for example contentManagement, contentDelivery and images. The map keeps the order of the registry.
- getContentstackEndpoints(region) returns full URLs. With omitHttps set to true, every value is a bare host.
- Client-side lookup in the region registry. See Region endpoints on the Contentstack class page for the matching rules.
- The map is a new copy on each call. A change to it does not change the registry.
Example
Basic usage: list the services of a region
import com.contentstack.cms.Contentstack;
import java.util.Map;
public class ListRegionEndpoints {
public static void main(String[] args) {
try {
Map<String, String> endpoints = Contentstack.getContentstackEndpoints("eu");
for (Map.Entry<String, String> endpoint : endpoints.entrySet()) {
System.out.println(endpoint.getKey() + ": " + endpoint.getValue());
}
} catch (IllegalArgumentException e) {
// Thrown for an empty or unknown region
System.out.println("Lookup failed: " + e.getMessage());
}
}
}All parameters: list bare hosts
import com.contentstack.cms.Contentstack;
import java.util.Map;
public class ListRegionHosts {
public static void main(String[] args) {
// omitHttps = true removes the https:// scheme from every value
Map<String, String> hosts = Contentstack.getContentstackEndpoints("gcp-na", true);
System.out.println("Management host: " + hosts.get("contentManagement"));
}
}getHost
getHost returns the API host that the client sends its requests to, as the builder set it.
Returns: String. The host the client sends requests to.
Validation
- There is no client-side validation. getHost does not throw.
Behavior
- Client-side only. getHost sends no request.
- getHost returns the host from the last setHost or setRegion call on the builder, or api.contentstack.io when you called neither.
- The value has no scheme and no path. It includes a port when you passed one to setHost, for example example.contentstack.com:8443.
- Use the getBaseUrl method for the full URL with the API version.
Example
Basic usage: print the host of a regional client
import com.contentstack.cms.Contentstack;
public class PrintHost {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setRegion("au")
.build();
System.out.println(client.getHost());
}
}getOAuthAuthorizationUrl
getOAuthAuthorizationUrl builds the URL of the Contentstack page where the user authorizes your Open Authorization (OAuth) app. The first step of the OAuth flow is to send the user to this URL.
Returns: String. The URL of the OAuth authorization page.
Validation
- getOAuthAuthorizationUrl throws IllegalStateException if the client has no OAuth settings, because the URL needs the app ID, client ID and redirect URI from the OAuth settings.
- It throws IllegalArgumentException if the OAuth settings hold a custom authorization endpoint that is not an https URL.
Behavior
- Client-side only. getOAuthAuthorizationUrl sends no request.
- The URL carries the query parameters response_type (default code), client_id, redirect_uri and app_id, plus scope when the OAuth settings set scopes.
- Without a client secret, the client uses Proof Key for Code Exchange (PKCE). The URL then also carries code_challenge and code_challenge_method=S256.
- The client creates the PKCE code verifier once, when you call build(), and keeps it in memory. Exchange the code with exchangeOAuthCode on the same client that built the URL.
- The page host follows the OAuth host. For example, api.contentstack.io gives app.contentstack.com, and eu-api.contentstack.com gives eu-app.contentstack.com. See the OAuthConfig class for the host rules.
Example
Basic usage: print the authorization URL
import com.contentstack.cms.Contentstack;
public class PrintAuthorizationUrl {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
try {
String url = client.getOAuthAuthorizationUrl();
System.out.println("Open this URL to authorize the app: " + url);
} catch (IllegalStateException e) {
// Thrown when the client was built without OAuth
System.out.println("OAuth is not configured: " + e.getMessage());
}
}
}getOAuthHandler
getOAuthHandler returns the OAuthHandler that runs the Open Authorization (OAuth) flow for the client, for tasks the client methods do not cover.
Returns: OAuthHandler. The client's OAuth handler, or null.
Validation
- There is no client-side validation. getOAuthHandler does not throw.
Behavior
- Client-side only. getOAuthHandler sends no request.
- getOAuthHandler returns null on a client without OAuth settings.
- The client creates one handler at build() and returns the same object on every call. The client methods getOAuthAuthorizationUrl, exchangeOAuthCode, refreshOAuthToken, getOAuthTokens and oauthLogout call this handler.
Example
Basic usage: read the access token from the handler
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadAccessToken {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
System.out.println("Open this URL and authorize the app: " + client.getOAuthAuthorizationUrl());
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
client.exchangeOAuthCode(code).join();
OAuthHandler handler = client.getOAuthHandler();
if (handler == null) {
System.out.println("The client was built without OAuth.");
return;
}
System.out.println("Access token present: " + (handler.getAccessToken() != null));
}
}getOAuthTokens
getOAuthTokens returns the Open Authorization (OAuth) tokens that the client holds, so you can store them or read their expiry and scope.
Returns: OAuthTokens. The client's current OAuth tokens, or null.
Validation
- There is no client-side validation. getOAuthTokens does not throw.
Behavior
- Client-side only. getOAuthTokens sends no request.
- getOAuthTokens returns null in three cases:
- The client has no OAuth settings.
- The client has not exchanged a code yet.
- oauthLogout cleared the tokens.
- The returned object is the one the client uses, not a copy. A later exchange or refresh replaces it with a new object, so call getOAuthTokens again after one.
- See the OAuthTokens class for the fields, for example the access token, the expiry and the organization UID.
Example
Basic usage: read the token expiry after the exchange
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadTokenExpiry {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
System.out.println("Open this URL and authorize the app: " + client.getOAuthAuthorizationUrl());
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
client.exchangeOAuthCode(code).join();
OAuthTokens tokens = client.getOAuthTokens();
if (tokens == null) {
System.out.println("The client holds no OAuth tokens.");
return;
}
System.out.println("Expires at " + tokens.getExpiresAt() + ", user " + tokens.getUserUid());
}
}getRetryConfig
getRetryConfig returns the retry settings that the builder gave the client, so you can read the retry limit and delay in use.
Returns: RetryConfig. The client's retry settings.
Validation
- There is no client-side validation. getRetryConfig does not throw.
Behavior
- Client-side only. getRetryConfig sends no request.
- getRetryConfig returns the object passed to setRetryConfig, or the default settings when you did not call it. The default allows 3 retries with a 300-millisecond delay.
- When you passed null to setRetryConfig, getRetryConfig returns null, while the client still retries with the default settings.
- See the RetryConfig class for the getters.
Example
Basic usage: print the retry limit and delay
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.core.RetryConfig;
public class PrintRetrySettings {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setRetryConfig(RetryConfig.builder().retryLimit(5).build())
.build();
RetryConfig retry = client.getRetryConfig();
System.out.println("Retries: " + retry.getRetryLimit() + ", delay: " + retry.getRetryDelay() + " ms");
}
}hasValidOAuthTokens
hasValidOAuthTokens checks whether the client holds an Open Authorization (OAuth) access token that has not expired.
Returns: boolean. Whether the client holds an unexpired access token.
Validation
- There is no client-side validation. hasValidOAuthTokens does not throw, and returns false on a client without OAuth settings.
Behavior
- Client-side only. hasValidOAuthTokens sends no request.
- hasValidOAuthTokens returns true only when the client holds tokens with an access token, and the access token has more than two minutes left before it expires.
- It returns false before the code exchange, after oauthLogout, and within two minutes of the expiry.
- A false result does not block requests. When the token has expired, the client refreshes it before the next request if it holds a refresh token.
Example
Basic usage: refresh only when the token is no longer valid
import com.contentstack.cms.Contentstack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CheckTokenValidity {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
System.out.println("Open this URL and authorize the app: " + client.getOAuthAuthorizationUrl());
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
client.exchangeOAuthCode(code).join();
if (!client.hasValidOAuthTokens()) {
client.refreshOAuthToken().join();
}
System.out.println("Valid token: " + client.hasValidOAuthTokens());
}
}isOAuthConfigured
isOAuthConfigured checks whether the client has Open Authorization (OAuth) settings, so that you can choose between the OAuth flow and login.
Returns: boolean. Whether the client uses OAuth.
Validation
- There is no client-side validation. isOAuthConfigured does not throw.
Behavior
- Client-side only. isOAuthConfigured sends no request.
- isOAuthConfigured returns true when the builder received OAuth settings from setOAuth or setOAuthConfig. It does not check whether the client holds tokens. Use the hasValidOAuthTokens method for that.
- The OAuth methods of the client throw IllegalStateException when isOAuthConfigured returns false.
Example
Basic usage: choose the sign-in flow
import com.contentstack.cms.Contentstack;
import java.io.IOException;
public class ChooseSignInFlow {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
if (client.isOAuthConfigured()) {
System.out.println("Authorize the app: " + client.getOAuthAuthorizationUrl());
} else {
client.login("<EMAIL>", "<PASSWORD>");
}
}
}login
login signs in to Contentstack with an email address and password, and stores the returned authtoken on the client for every later request.
| Name | Type | Description |
|---|---|---|
| emailId (required) | String | Email address of the Contentstack account. |
| password (required) | String | Password of the account. |
| params (required) | Map<String, String> | Two-factor value under tfaToken or mfaSecret. |
| params.tfaToken (required) | String | Current two-factor authentication code. |
| params.mfaSecret (required) | String | Authenticator secret the SDK generates the code from. |
Returns: Response<LoginDetails>. The login response.
Overloads
- login(String emailId, String password)
- login(String emailId, String password, Map<String, String> params)
Validation
- login throws IllegalStateException if the client already holds an authtoken, from an earlier login or from setAuthtoken, because one client keeps one session.
- The three-argument overload checks its input before it sends anything. It throws IllegalArgumentException in the four cases below:
- emailId or password is empty or holds only spaces.
- params is empty.
- params holds both a tfaToken and an mfaSecret value, or neither of them.
- The SDK cannot generate a code from mfaSecret.
- The three-argument overload throws NullPointerException if emailId, password or params is null.
- The two-argument overload does not check emailId or password. The API rejects a wrong or missing value.
- login declares IOException. It throws it for a network failure or a timeout that remains after the SDK retries.
- An API rejection does not throw. response.isSuccessful() is false.
- Known issue: In 1.16.0, a failed login reads the error body before it returns, so response.errorBody() no longer holds the error details. Use response.code() and response.message() to identify the failure.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- login sends the request itself and waits for the response. It returns a Response, not a Call.
- login sends POST /user-session with a body of the form {"user": {"email": "...", "password": "..."}}. The three-argument overload adds the two-factor code as tfa_token.
- With mfaSecret, the SDK generates the current six-digit time-based one-time password (TOTP) from the secret and sends it as tfa_token. The secret itself does not leave your application.
- login reads only the tfaToken and mfaSecret keys of params and ignores any other key.
- On success, login stores the authtoken from response.body().getUser().getAuthtoken() on the client. Every later request from the client, and from the Stack, Organization and User objects it creates, carries it in the authtoken header.
- response.body() is a LoginDetails with a notice message and a user of type UserModel. The User class page lists the UserModel fields.
- The client never clears the authtoken. To log in as another user, build a new client.
- On an Open Authorization (OAuth) client, login throws IOException when the client holds no OAuth tokens yet. The SDK does not attach the returned authtoken to later requests. Use either OAuth or login on one client, not both.
Example
Basic usage: log in with an email address and password
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.LoginDetails;
import retrofit2.Response;
import java.io.IOException;
public class LogIn {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
Response<LoginDetails> response = client.login("<EMAIL>", "<PASSWORD>");
if (!response.isSuccessful()) {
// The API rejected the login. The SDK has already read the error body, so use the status.
System.out.println("Login failed: " + response.code() + " " + response.message());
return;
}
System.out.println("Logged in as " + response.body().getUser().getEmail());
}
}All parameters: log in with a two-factor authentication code
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.LoginDetails;
import retrofit2.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class LogInWithTwoFactorCode {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
Map<String, String> params = new HashMap<>();
params.put("tfaToken", "<TFA_TOKEN>");
Response<LoginDetails> response = client.login("<EMAIL>", "<PASSWORD>", params);
if (!response.isSuccessful()) { System.out.println(response.code() + " " + response.message()); return; }
System.out.println(response.body().getNotice());
}
}Two-factor login from an authenticator secret
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.LoginDetails;
import retrofit2.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class LogInWithMfaSecret {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
// The SDK generates the six-digit code from the secret
Map<String, String> params = new HashMap<>();
params.put("mfaSecret", System.getenv("CONTENTSTACK_MFA_SECRET"));
Response<LoginDetails> response = client.login("<EMAIL>", "<PASSWORD>", params);
if (!response.isSuccessful()) { System.out.println(response.code() + " " + response.message()); return; }
System.out.println(response.body().getNotice());
}
}Error handling: catch invalid two-factor input and a second login
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.LoginDetails;
import retrofit2.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CatchLoginErrors {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
Map<String, String> params = new HashMap<>();
try {
client.login("<EMAIL>", "<PASSWORD>", params);
} catch (IllegalArgumentException e) {
// Thrown before any request, because params is empty
System.out.println("Invalid two-factor input: " + e.getMessage());
}
Response<LoginDetails> response = client.login("<EMAIL>", "<PASSWORD>");
if (!response.isSuccessful()) { System.out.println(response.code() + " " + response.message()); return; }
try {
client.login("<EMAIL>", "<PASSWORD>");
} catch (IllegalStateException e) {
// Thrown because the client already holds an authtoken
System.out.println("Already logged in: " + e.getMessage());
}
}
}oauthLogout
oauthLogout clears the Open Authorization (OAuth) tokens from the client, and can first ask Contentstack to revoke the app's authorization.
| Name | Type | Description |
|---|---|---|
| revokeAuthorization (required) | boolean | true revokes the app's authorization before clearing tokens. |
Returns: CompletableFuture<Void>. A future that completes when the logout finishes.
Overloads
- oauthLogout(): This overload takes no parameters.
- oauthLogout(boolean revokeAuthorization)
Validation
- oauthLogout throws IllegalStateException if the client has no OAuth settings, because there are no OAuth tokens to clear.
- With revokeAuthorization set to true, the future fails with a RuntimeException when the revoke request fails. The client then keeps its tokens.
- Known issue: In 1.16.0, oauthLogout(true) sends the revoke request to the Contentstack web app address instead of the OAuth revoke endpoint. The authorization can stay in place even when the future completes. Revoke the app's authorization in the Contentstack web app to be sure.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- oauthLogout runs on another thread and returns at once. Call get() or join() on the future to wait for it.
- oauthLogout() is the same as oauthLogout(false). It sends no request and clears the tokens from memory.
- With revokeAuthorization set to true and tokens present, oauthLogout first sends a revoke request with the access token, then clears the tokens.
- After the logout, getOAuthTokens returns null, and every request from the client throws IOException until you exchange a new code.
- oauthLogout does not call the onTokensCleared method of a TokenCallback. Delete any tokens your callback stored yourself.
Warning oauthLogout discards the access token and the refresh token from the client. You cannot restore them. To use the client again, send the user through the authorization URL and exchange a new code.
Example
Basic usage: clear the tokens
import com.contentstack.cms.Contentstack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
public class ClearOAuthTokens {
public static void main(String[] args) throws IOException, InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
System.out.println("Open this URL and authorize the app: " + client.getOAuthAuthorizationUrl());
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
client.exchangeOAuthCode(code).join();
try {
client.oauthLogout().get();
System.out.println("Tokens cleared: " + (client.getOAuthTokens() == null));
} catch (ExecutionException e) {
System.out.println("Logout failed: " + e.getCause().getMessage());
}
}
}All parameters: revoke the authorization and clear the tokens
import com.contentstack.cms.Contentstack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
public class RevokeAndLogOut {
public static void main(String[] args) throws IOException, InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
System.out.println("Open this URL and authorize the app: " + client.getOAuthAuthorizationUrl());
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
client.exchangeOAuthCode(code).join();
try {
client.oauthLogout(true).get();
System.out.println("Logged out");
} catch (ExecutionException e) {
// The revoke request failed. The client still holds its tokens.
System.out.println("Revoke failed: " + e.getCause().getMessage());
}
}
}organization
organization creates an Organization object, for all the organizations of the account or for one organization by its UID.
| Name | Type | Description |
|---|---|---|
| organizationUid (required) | String | UID of the organization to work with. |
Returns: Organization. A new organization object.
Overloads
- organization(): This overload takes no parameters.
- organization(String organizationUid)
Validation
- organization throws IllegalStateException if the client has neither an authtoken nor Open Authorization (OAuth), because organization requests need a signed-in session. Call login first.
- organization(organizationUid) throws IllegalStateException if organizationUid is an empty string, and NullPointerException if it is null. The SDK needs the UID to build the request path.
- organization(organizationUid) does not check that the organization exists. A wrong UID surfaces as an API error when you call execute() on a request.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Client-side only. organization sends no request.
- organization() returns an object with no organization UID. Use it for requests across all organizations of the account, such as find(). Methods that need a UID, such as fetch(), throw NullPointerException on it.
- On an OAuth client, organization() reads the organization UID from the current OAuth tokens. When the tokens hold one, it returns the same object as organization(organizationUid) with that UID.
- organization(organizationUid) returns an object for one organization. Use it for requests such as fetch() and stacks().
Example
Basic usage: fetch one organization
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.organization.Organization;
import okhttp3.ResponseBody;
import retrofit2.Response;
import java.io.IOException;
public class FetchOrganization {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
client.login("<EMAIL>", "<PASSWORD>");
Organization organization = client.organization("<ORGANIZATION_UID>");
Response<ResponseBody> response = organization.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());
}
}List every organization of the account
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.organization.Organization;
import okhttp3.ResponseBody;
import retrofit2.Response;
import java.io.IOException;
public class ListOrganizations {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
client.login("<EMAIL>", "<PASSWORD>");
Organization organizations = client.organization();
Response<ResponseBody> response = organizations.find().execute();
if (!response.isSuccessful()) { System.out.println(response.errorBody().string()); return; }
System.out.println(response.body().string());
}
}Error handling: catch an empty organization UID
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.organization.Organization;
import java.io.IOException;
public class CatchEmptyOrganizationUid {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
client.login("<EMAIL>", "<PASSWORD>");
String organizationUid = System.getenv().getOrDefault("CONTENTSTACK_ORG_UID", "");
try {
Organization organization = client.organization(organizationUid);
System.out.println("Organization object ready: " + organization);
} catch (IllegalStateException e) {
// Thrown when the UID is empty, or when the client is not logged in
System.out.println("Cannot create the organization: " + e.getMessage());
}
}
}refreshOAuthToken
refreshOAuthToken gets a new access token with the client's refresh token when the current access token has expired.
Returns: CompletableFuture<OAuthTokens>. A future that completes with the current or refreshed tokens.
Validation
- refreshOAuthToken throws IllegalStateException if the client has no Open Authorization (OAuth) settings, because the refresh needs the OAuth settings.
- When the client holds no tokens, or the tokens have no refresh token, refreshOAuthToken sends no request and returns a future that fails with IllegalStateException. Call exchangeOAuthCode first.
- When the token request fails, the future fails with a RuntimeException whose cause holds the details.
Behavior
- When the access token has more than two minutes left, refreshOAuthToken sends no request and returns a future that is already complete with the current tokens.
- Otherwise it sends a form POST to the OAuth token endpoint on another thread. The body includes grant_type=refresh_token, the refresh token, client_id, app_id, and either client_secret or the PKCE code_verifier.
- On success, the client stores the new tokens. When the response has no refresh token, the client keeps the old one.
- When the builder set a TokenCallback, the SDK calls its onTokensUpdated method with the new tokens.
- The client also refreshes the token without this call: before a request when the access token has expired, and after a request returns 401.
Example
Basic usage: refresh the access token before a batch of requests
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
public class RefreshAccessToken {
public static void main(String[] args) throws IOException, InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
System.out.println("Open this URL and authorize the app: " + client.getOAuthAuthorizationUrl());
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
try {
client.exchangeOAuthCode(code).get();
OAuthTokens tokens = client.refreshOAuthToken().get();
System.out.println("Token expires at " + tokens.getExpiresAt());
} catch (ExecutionException e) {
// No tokens, no refresh token, or the token endpoint rejected the request
System.out.println("Refresh failed: " + e.getCause().getMessage());
}
}
}refreshRegions
refreshRegions downloads the current Contentstack region registry and replaces the copy in memory, so that region lookups see regions and services added after the SDK release.
Returns: int. The number of regions in the downloaded registry.
Validation
- refreshRegions throws RuntimeException if the download fails or the response is not a valid registry. The cause holds the original exception. The registry in memory stays as it was.
Behavior
- refreshRegions is static. Call it on the class: Contentstack.refreshRegions().
- refreshRegions sends a GET request to https://artifacts.contentstack.com/regions.json on the calling thread and waits for it, with a 10-second connect timeout and a 10-second read timeout. The request does not use the client's proxy, timeout or retry settings.
- On success, every later call to getContentstackEndpoint, getContentstackEndpoints and Builder.setRegion in the same Java Virtual Machine (JVM) reads the downloaded registry.
- A client that build() already created keeps its host. Build a new client to use a refreshed host.
Example
Basic usage: refresh the registry before a region lookup
import com.contentstack.cms.Contentstack;
public class RefreshRegionRegistry {
public static void main(String[] args) {
try {
int count = Contentstack.refreshRegions();
System.out.println("Regions loaded: " + count);
} catch (RuntimeException e) {
// Thrown when the download fails. The bundled registry stays in use.
System.out.println("Refresh failed: " + e.getMessage());
}
System.out.println(Contentstack.getContentstackEndpoint("eu", "contentManagement"));
}
}stack
stack creates the Stack object that every stack-level request starts from, and sets the credentials and branch it sends.
| Name | Type | Description |
|---|---|---|
| apiKey (required) | String | API key of the stack. |
| managementToken (required) | String | Management token of the stack. |
| branch (required) | String | Branch UID or alias that requests target. |
| key (required) | String | Stack API key, or a branch UID. |
| header (required) | Map<String, Object> | Headers that every stack request sends. |
Returns: Stack. A new stack object.
Overloads
- stack(String apiKey, String managementToken)
- stack(String apiKey, String managementToken, String branch)
- stack(String key)
- stack(Map<String, Object> header)
- stack(): This overload takes no parameters.
Validation
- stack() and stack(header) throw IllegalStateException if the client has neither an authtoken nor Open Authorization (OAuth), because without a management token the requests need a signed-in session. stack(header) skips this check when header holds an authorization key.
- stack(key) throws NullPointerException if key is null.
- The overloads that take an API key, a management token or a branch do not check the values. A wrong value surfaces as an API error when you call execute() on a request.
- stack stores a null API key, management token or branch as is. Retrofit rejects a null header value with an IllegalArgumentException when execute() builds the request.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Client-side only. stack sends no request. It stores headers that every request from the stack, and from the objects it creates, sends.
- stack(apiKey, managementToken) sets two headers, api_key and authorization. It needs no login, so use it for scripts and server code.
- stack(apiKey, managementToken, branch) also sets the branch header.
- stack(key) reads the first characters of key:
- A value that starts with blt becomes the api_key header.
- Any other value becomes the branch header.
- stack(key) sets no management token, so requests need the authtoken from login.
- stack(header) copies every entry of header. Use the keys api_key, authorization and branch to set the API key, the management token and the branch.
- stack() sets no header. Use it with a logged-in client for requests across stacks, such as find(), which lists every stack the account can access.
- On a logged-in client, each request also carries the client's authtoken header, in addition to the headers stack sets.
Example
Basic usage: create a stack with a management token
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Stack;
import okhttp3.ResponseBody;
import retrofit2.Response;
import java.io.IOException;
public class FetchStack {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
Stack stack = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>");
Response<ResponseBody> response = stack.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());
}
}All parameters: target a branch with a management token
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Stack;
import okhttp3.ResponseBody;
import retrofit2.Response;
import java.io.IOException;
public class FetchContentTypesOnBranch {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
Stack stack = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>", "<BRANCH>");
Response<ResponseBody> response = stack.contentType().find().execute();
if (!response.isSuccessful()) { System.out.println(response.errorBody().string()); return; }
System.out.println(response.body().string());
}
}Logged-in client: use an API key, a header map, or no credentials
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Stack;
import okhttp3.ResponseBody;
import retrofit2.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class StacksAfterLogin {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
client.login("<EMAIL>", "<PASSWORD>");
// stack(): list every stack the account can access
Response<ResponseBody> all = client.stack().find().execute();
if (!all.isSuccessful()) { System.out.println(all.errorBody().string()); return; }
System.out.println(all.body().string());
// stack(key): a key that starts with "blt" becomes the api_key header
Stack byKey = client.stack("<API_KEY>");
Response<ResponseBody> one = byKey.find().execute();
if (!one.isSuccessful()) { System.out.println(one.errorBody().string()); return; }
System.out.println(one.body().string());
// stack(header): set the API key and the branch yourself
Map<String, Object> header = new HashMap<>();
header.put("api_key", "<API_KEY>");
header.put("branch", "<BRANCH>");
Stack onBranch = client.stack(header);
Response<ResponseBody> types = onBranch.contentType().find().execute();
if (!types.isSuccessful()) { System.out.println(types.errorBody().string()); return; }
System.out.println(types.body().string());
}
}Error handling: call stack() before login
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Stack;
public class StackWithoutLogin {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder().build();
try {
Stack stack = client.stack();
System.out.println("Stack object ready: " + stack);
} catch (IllegalStateException e) {
// Thrown because stack() needs an authtoken or OAuth. Use stack(apiKey, managementToken) instead.
System.out.println("Log in first: " + e.getMessage());
}
}
}user
user creates the User object that reads and updates the account of the client's session.
Returns: User. A new user object.
Validation
- user throws IllegalStateException if the client has neither an authtoken nor Open Authorization (OAuth), because every User request except login needs a signed-in session. Call login first.
- user sends no request. Errors from the API come from execute() on the requests that the User object builds.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Client-side only. user sends no request.
- Each call returns a new User object that shares the client's HTTP client, so its requests carry the client's authtoken or OAuth token.
Example
Basic usage: log in and read the account details
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.user.User;
import okhttp3.ResponseBody;
import retrofit2.Response;
import java.io.IOException;
public class ReadAccount {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder().build();
client.login("<EMAIL>", "<PASSWORD>");
User user = client.user();
Response<ResponseBody> response = user.getUser().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());
}
}Error handling: call user before login
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.user.User;
public class UserWithoutLogin {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder().build();
try {
User user = client.user();
System.out.println("User object ready: " + user);
} catch (IllegalStateException e) {
// Thrown because the client has no authtoken and no OAuth
System.out.println("Log in first: " + e.getMessage());
}
}
}