Contentstack

View as Markdown

Contentstack

The Contentstack class is the entry point of the Java Delivery SDK. It creates the Stack object that holds your credentials and settings, and it looks up the Contentstack endpoint URLs for a region. A stack holds the entries and assets of one project.

Use this class to

  • create a Stack from an API key, a delivery token and an environment
  • create a Stack with extra settings from a Config object, such as a region or a branch
  • look up the host of a Contentstack service in a region, for example to set a custom host or call another API

Every method of Contentstack is static. Call it on the class, for example Contentstack.stack(...).

getContentstackEndpoint

getContentstackEndpoint returns the endpoint of one Contentstack service in a region, as a full URL or as a bare host.

NameTypeDescription
region (required)String

Region ID or alias, such as "eu".

Default: Not applicable
service (required)String

Service key, such as "contentDelivery".

Default: Not applicable
omitHttps (required)boolean

true returns the host without https://.

Default: Not applicable

Returns: String. The endpoint URL or host for the service.

Validation

  • getContentstackEndpoint throws IllegalArgumentException in three cases, because it cannot return an endpoint it does not know:
    • region is empty or holds only spaces.
    • region matches no region ID or alias, even after the one-time download described in Behavior.
    • The region has no endpoint for service. Service keys are case-sensitive, and some services exist only in some regions.
  • getContentstackEndpoint throws NullPointerException if region is null.
  • Catch IllegalArgumentException when the region or service comes from user input or a configuration file.

Behavior

  • getContentstackEndpoint(region, service) returns the full URL.
  • Client-side lookup. getContentstackEndpoint calls Endpoint.getContentstackEndpoint with the same arguments. See Endpoint lookup on the Contentstack class page.
  • getContentstackEndpoint reads the regions.json file that the SDK jar bundles. It downloads the current file once per JVM only when the bundled file has no match for region.
  • region matches a region ID or alias. Matching ignores case and treats - and _ as the same character.
  • service must match a key in the region's endpoint list exactly. Use the getContentstackEndpoints method to list the keys a region has.
  • With omitHttps set to true, getContentstackEndpoint removes the leading https:// or http://. Pass the result to setHost, which expects a host without a scheme.

Example

Basic usage: get the delivery URL for a region

import com.contentstack.sdk.Contentstack;

public class GetDeliveryUrl {
    public static void main(String[] args) {
        try {
            String url = Contentstack.getContentstackEndpoint("eu", "contentDelivery");
            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 delivery host

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Stack;

public class SetHostFromRegion {
    public static void main(String[] args) throws IllegalAccessException {
        // omitHttps = true returns the host without the https:// scheme
        String host = Contentstack.getContentstackEndpoint("azure-na", "contentDelivery", true);

        Config config = new Config();
        config.setHost(host);
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        System.out.println("Delivery host: " + config.getHost());
    }
}

getContentstackEndpoints

getContentstackEndpoints returns the endpoint of every Contentstack service in a region, with the service key as the map key.

NameTypeDescription
region (required)String

Region ID or alias, such as "eu".

Default: Not applicable
omitHttps (required)boolean

true returns hosts without https://.

Default: Not applicable

Returns: Map. The endpoint of every service in the region.

Validation

  • getContentstackEndpoints throws IllegalArgumentException if region is empty, holds only spaces, or matches no region ID or alias, because it has no endpoint list to return.
  • getContentstackEndpoints throws NullPointerException if region is null.

Behavior

  • getContentstackEndpoints(region) returns full URLs.
  • Client-side lookup. getContentstackEndpoints calls Endpoint.getAllEndpoints with the same arguments. See Endpoint lookup on the Contentstack class page.
  • getContentstackEndpoints reads the regions.json file that the SDK jar bundles. It downloads the current file once per JVM only when the bundled file has no match for region.
  • The result is a Map<String, String>. Its keys are service keys such as contentDelivery and contentManagement, and its values are URLs. Do not rely on the order of the keys.
  • Each call returns a new map. A change to the map does not affect later lookups.
  • With omitHttps set to true, getContentstackEndpoints removes the leading https:// or http:// from every value.
  • The service list differs between regions. Read the keys from the map instead of assuming one region's list applies to another.

Example

Basic usage: list every service endpoint in a region

import com.contentstack.sdk.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 for a region alias

import com.contentstack.sdk.Contentstack;

import java.util.Map;

public class ListRegionHosts {
    public static void main(String[] args) {
        // "AZURE_NA" matches the azure-na region, because matching ignores case and treats _ as -
        Map<String, String> hosts = Contentstack.getContentstackEndpoints("AZURE_NA", true);
        System.out.println("Delivery host: " + hosts.get("contentDelivery"));
        System.out.println("Management host: " + hosts.get("contentManagement"));
    }
}

stack

stack creates the Stack object that holds your credentials and settings, and that every content request starts from.

NameTypeDescription
stackApiKey (required)String

API key of your stack.

Default: Not applicable
deliveryToken (required)String

Delivery token scoped to the environment.

Default: Not applicable
environment (required)String

Publishing environment to read content from.

Default: Not applicable
config (required)Config

Region, host, branch and other stack settings.

Default: Not applicable

Returns: Stack. A new stack object.

Validation

  • stack throws NullPointerException if stackApiKey, deliveryToken or environment is null, because the SDK sends each one as a request header.
  • stack throws IllegalAccessException if any of the three is an empty string. IllegalAccessException is a checked exception, so catch it or declare it on the calling method.
  • stack accepts a value made only of spaces. The SDK checks for an empty string only.
  • The four-argument overload throws NullPointerException if config is null, because stack reads the branch from it.
  • The four-argument overload throws NullPointerException if config enables live preview without a live preview host while the region is US. Call setLivePreviewHost before stack.
  • stack does not check the credentials against Contentstack. A wrong API key or token surfaces as an Error in the callback of the first request.

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

Behavior

  • stack(stackApiKey, deliveryToken, environment) uses a new Config with its default values.
  • Client-side only. stack sends no request.
  • stack sets three request headers that every request from this stack carries:
    • api_key holds stackApiKey.
    • access_token holds deliveryToken.
    • environment holds environment.
  • When the Config holds a branch from setBranch, stack adds a branch header. When it holds early access values from setEarlyAccess, stack adds an x-header-ea header with the values joined by commas.
  • stack picks the delivery host in this order:
    • The host from setHost, when you set one.
    • Otherwise, the contentDelivery host that Endpoint returns for the region from setRegion. For the default region US, that host is cdn.contentstack.io.
  • stack writes the chosen host back into the Config, so getHost returns it after the call.
  • stack builds one HTTP client for the stack with the proxy, connection pool and retry options from the Config. Every request from the stack uses that client.
  • stack reads these settings once. A change to the Config after the call does not reach the existing Stack.

Example

Basic usage: create a stack and fetch an entry

import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class CreateStack {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");

        entry.fetch(new EntryResultCallBack() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, for example for a wrong token, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(entry.getTitle());
            }
        });
    }
}

All parameters: create a stack with a region and a branch

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Stack;

public class CreateStackWithConfig {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config();
        config.setRegion(Config.ContentstackRegion.EU);
        config.setBranch("<BRANCH>");

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);

        // stack wrote the Europe delivery host into the config
        System.out.println(config.getHost());
        System.out.println(stack.getApplicationKey());
    }
}

Error handling: catch a missing credential

import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Stack;

public class CatchMissingEnvironment {
    public static void main(String[] args) {
        String environment = System.getenv().getOrDefault("CONTENTSTACK_ENVIRONMENT", "");
        try {
            Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", environment);
            System.out.println("Stack ready: " + stack.getApplicationKey());
        } catch (IllegalAccessException e) {
            // Thrown when the API key, delivery token or environment is an empty string
            System.out.println("Missing credential: " + e.getMessage());
        }
    }
}