ContentType

View as Markdown

ContentType

A content type defines the structure of a page or a section of your site, and every entry follows its schema. Use this class to

  • list the content types of a stack and read one of them
  • create, update, and delete a content type, including its field visibility rules
  • find the content types and global fields that reference a content type
  • export and import a content type
  • open the entries of a content type

stack.contentType("<CONTENT_TYPE_UID>") returns a ContentType for one content type. The call takes one argument:

NameTypeDescription
contentTypeUidStringUID of the content type. Leave it out to work with all content types of the stack.

Create the object through stack.contentType(). The class also has a public constructor, but it needs the client's internal Retrofit instance.

addHeader

addHeader adds one header to every later request from this content type object.

NameTypeDescription
key (required)String

Name of the header, such as branch.

Default: Not applicable
value (required)String

Value of the header.

Default: Not applicable

Returns: ContentType. The same content type, for chaining.

Validation

  • There is no client-side validation.
  • A null key or value makes execute() throw IllegalArgumentException on every later request from this object, because Retrofit rejects a header map that holds null.
  • 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

  • Puts the header into the header map of this object. The new value replaces a header with the same name, including the api_key, authorization, and branch headers that the object copied from the stack.
  • Every request method of this object sends the header map. The stack and other content type objects do not see the header.
  • An entry that you create afterward with entry copies the header.

Example

Basic usage: read a content type on a branch

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

import java.io.IOException;

public class FetchContentTypeOnBranch {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        ContentType contentType = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType("<CONTENT_TYPE_UID>")
                .addHeader("branch", "<BRANCH>");

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

addHeaders

addHeaders adds several headers to every later request from this content type object.

NameTypeDescription
headers (required)HashMap<String, String>

Header names mapped to their values.

Default: Not applicable

Returns: ContentType. The same content type, for chaining.

Validation

  • Throws NullPointerException if headers is null, because the SDK copies every pair from the map.
  • A null key or value in the map makes execute() throw IllegalArgumentException on later requests, because Retrofit rejects a header map that holds null.
  • 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

  • Copies every pair into the header map of this object. Each new value replaces a header with the same name.
  • Every request method of this object sends the header map, and entry copies it into new entries.
  • The SDK copies the pairs, so later changes to your map do not reach the object.

Example

Basic usage: add a branch header

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

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

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

        HashMap<String, String> headers = new HashMap<>();
        headers.put("branch", "<BRANCH>");

        ContentType contentType = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType()
                .addHeaders(headers);

        Response<ResponseBody> response = contentType.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 the later requests from this content type object, such as include_count or version.

NameTypeDescription
key (required)String

Name of the query parameter, such as include_count.

Default: Not applicable
value (required)Object

Value of the parameter. The SDK sends its toString() form.

Default: Not applicable

Returns: ContentType. The same content type, for chaining.

Validation

  • There is no client-side validation.
  • A null key or value makes execute() throw IllegalArgumentException on later requests that send the parameter map, because Retrofit rejects a query map that holds null.
  • 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

Example

Basic usage: list content types with a count and global field schemas

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

import java.io.IOException;

public class FindContentTypesWithCount {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        ContentType contentType = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType()
                .addParam("include_count", true)
                .addParam("include_global_field_schema", true);

        Response<ResponseBody> response = contentType.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 several query parameters to the later requests from this content type object.

NameTypeDescription
params (required)HashMap<String, Object>

Parameter names mapped to their values.

Default: Not applicable

Returns: ContentType. The same content type, for chaining.

Validation

  • Throws NullPointerException if params is null, because the SDK copies every pair from the map.
  • A null key or value in the map makes execute() throw IllegalArgumentException on later requests that send the map. Retrofit rejects a query map that holds null.
  • 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

  • Copies every pair into the query parameter map of this object. Each new value replaces a parameter with the same name.
  • The requests that send the map are the same as for addParam.

Example

Basic usage: read an earlier version of a content type with its global field schemas

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

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

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

        HashMap<String, Object> params = new HashMap<>();
        params.put("version", 2);
        params.put("include_global_field_schema", true);

        ContentType contentType = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType("<CONTENT_TYPE_UID>")
                .addParams(params);

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

create

create creates a content type in the stack from the schema you send.

NameTypeDescription
requestBody (required)JSONObject

Request body with the content type under a content_type key.

Default: Not applicable
requestBody.content_type.title (required)String

Name of the content type.

Default: Not applicable
requestBody.content_type.uid (required)String

UID of the content type, unique in the stack.

Default: Not applicable
requestBody.content_type.schema (required)JSONArray

Field definitions of the content type.

Default: Not applicable

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

Validation

  • There is no client-side validation of the body.
  • A null body makes execute() throw IllegalArgumentException, 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().

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

Behavior

  • One call builds one Create a content type request (POST /content_types) with requestBody as the JSON body.
  • The request sends the query parameters of this object. The API accepts include_branch.
  • The body holds the complete schema. To remove the unique constraint of a field, such as the default title field, set its unique key to false.
  • create ignores the content type UID, so call it on stack.contentType().

Example

Basic usage: create a content type with a title and a URL field

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

import java.io.IOException;

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

        JSONObject titleMetadata = new JSONObject();
        titleMetadata.put("_default", true);
        JSONObject title = new JSONObject();
        title.put("display_name", "Title");
        title.put("uid", "title");
        title.put("data_type", "text");
        title.put("field_metadata", titleMetadata);
        title.put("mandatory", true);
        title.put("unique", false);

        JSONObject urlMetadata = new JSONObject();
        urlMetadata.put("_default", true);
        JSONObject url = new JSONObject();
        url.put("display_name", "URL");
        url.put("uid", "url");
        url.put("data_type", "text");
        url.put("field_metadata", urlMetadata);

        JSONArray schema = new JSONArray();
        schema.add(title);
        schema.add(url);

        JSONObject details = new JSONObject();
        details.put("title", "docs-test-blog-post");
        details.put("uid", "docs_test_blog_post");
        details.put("schema", schema);
        JSONObject body = new JSONObject();
        body.put("content_type", details);

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

delete

delete deletes a content type and all the entries in it.

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

Validation

  • Throws NullPointerException if the content type has no UID, as after stack.contentType(), because the request path needs 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 call builds one Delete Content Type request (DELETE /content_types/{content_type_uid}).
  • The request sends the query parameters of this object. The API accepts force set to true to force the deletion.

Example

Basic usage: delete a content type

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

import java.io.IOException;

public class DeleteContentType {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        ContentType contentType = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType("<CONTENT_TYPE_UID>")
                .addParam("force", true);

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

entry

entry creates an Entry object for this content type, either for all of its entries or for one entry.

NameTypeDescription
entryUid (required)String

UID of the entry. Leave it out with entry() to work with all entries.

Default: Not applicable

Returns: Entry. A new entry object.

Validation

  • Throws NullPointerException if the content type has no UID, as after stack.contentType(), because every entry request needs the content type UID.
  • entry does not check entryUid. entry(null) returns an entry whose single-entry methods throw NullPointerException.
  • An invalid UID surfaces as an API error in the response when you call execute() on a request from the entry.

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

Behavior

  • Sends no request.
  • Which entry methods work depends on the overload:
    • entry() stores an empty entry UID. Use it for the content-type-wide methods, such as find and create.
    • entry(entryUid) stores the UID. Use it for the single-entry methods, such as fetch and publish.
  • The new entry copies the current headers of this content type, including headers from addHeader. It does not copy the query parameters.
  • Each call creates a new object. Headers and parameters you add to one entry do not reach other entries.

Example

Basic usage: list the entries, then read one entry

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

import java.io.IOException;

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

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

        Response<ResponseBody> one = contentType.entry("<ENTRY_UID>").fetch().execute();
        if (!one.isSuccessful()) { System.out.println(one.errorBody().string()); return; }
        System.out.println(one.body().string());
    }
}

export

export exports a content type and its schema as JSON. It does not export the entries of the content type.

NameTypeDescription
version (required)int

Version of the content type to export. export() exports the latest version.

Default: Not applicable

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

Validation

  • Throws NullPointerException if the content type has no UID, as after stack.contentType(), because the request path needs 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 call builds one Export a content type request (GET /content_types/{content_type_uid}/export).
  • export(version) adds the version query parameter. export() sends none, and the API exports the latest version.
  • export sends no other query parameter. Values from addParam do not reach this request.
  • The SDK does not save the response to a file. Write response.body().string() to a file yourself.

Example

Basic usage: export the latest version to a file

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

import java.io.FileWriter;
import java.io.IOException;

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

        Response<ResponseBody> response = contentType.export().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;
        }
        try (FileWriter writer = new FileWriter("<FILE_PATH>")) {
            writer.write(response.body().string());
        }
    }
}

Version: export version 2

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

import java.io.IOException;

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

        Response<ResponseBody> response = contentType.export(2).execute();
        if (!response.isSuccessful()) { System.out.println(response.errorBody().string()); return; }
        System.out.println(response.body().string());
    }
}

fetch

fetch reads one content type with its schema.

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

Validation

  • Throws NullPointerException if the content type has no UID, as after stack.contentType(), because the request path needs 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 call builds one Get a single content type request (GET /content_types/{content_type_uid}).
  • The request sends the query parameters of this object. The API accepts the following three:
    • version reads an earlier version of the content type. Without it, the API returns the latest version.
    • include_global_field_schema adds the schema of each global field.
    • include_branch adds the _branch key.
  • To read the content type as a Java object, use fetchAsPojo.

Example

Basic usage: read a content type

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

import java.io.IOException;

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

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

Query parameters: read version 2 with global field schemas

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

import java.io.IOException;

public class FetchContentTypeWithSchema {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        ContentType contentType = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType("<CONTENT_TYPE_UID>")
                .addParam("version", 2)
                .addParam("include_global_field_schema", true);

        Response<ResponseBody> response = contentType.fetch().execute();
        if (!response.isSuccessful()) { System.out.println(response.errorBody().string()); return; }
        System.out.println(response.body().string());
    }
}

fetchAsPojo

fetchAsPojo reads one content type and maps the response to a ContentTypeResponse.

Returns: Call<ContentTypeResponse>. The request for the content type as a typed object, sent when you call execute().

Validation

  • Throws NullPointerException if the content type has no UID, as after stack.contentType(), because the request path needs the UID.
  • An API rejection does not throw. response.isSuccessful() is false, response.body() is null, and the error details are in response.errorBody().

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

Behavior

  • Sends the same Get a single content type request as fetch, with the query parameters of this object.
  • The SDK maps the content_type object of the response. ContentTypeResponse has two getters:
    • getRawJson() returns the content type as a Map<String, Object>.
    • getContentPojo() returns a ContentTypePojo.
  • ContentTypePojo has no public getters or fields, so code outside the SDK cannot read its values. Read the content type through getRawJson().

Example

Basic usage: print the title and schema of a content type

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.ContentType;
import com.contentstack.cms.stack.ContentTypeResponse;
import retrofit2.Response;

import java.io.IOException;
import java.util.Map;

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

        Response<ContentTypeResponse> response = contentType.fetchAsPojo().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;
        }
        Map<String, Object> raw = response.body().getRawJson();
        System.out.println(raw.get("title"));
        System.out.println(raw.get("schema"));
    }
}

fieldVisibilityRule

fieldVisibilityRule sets field visibility rules on an existing content type, so that fields show or hide based on the values of other fields.

NameTypeDescription
requestBody (required)JSONObject

Request body with the rules under content_type.field_rules.

Default: Not applicable
requestBody.content_type.field_rules (required)JSONArray

Rules, each with conditions, match_type, and actions.

Default: Not applicable

Returns: Call<ResponseBody>. The request for the content type with its field visibility rules, sent when you call execute().

Validation

  • Throws NullPointerException if the content type has no UID, as after stack.contentType(), because the request path needs the UID.
  • A null body makes execute() throw IllegalArgumentException, 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().

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

Behavior

  • One call builds one Set Field Visibility Rule for Content Type request (PUT /content_types/{content_type_uid}) with requestBody as the JSON body. This is the same request as update.
  • The request sends the query parameters of this object. The API accepts include_branch.

Example

Basic usage: show a field when another field equals a value

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

import java.io.IOException;

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

        JSONObject condition = new JSONObject();
        condition.put("operand_field", "post_type");
        condition.put("operator", "equals");
        condition.put("value", "video");
        JSONArray conditions = new JSONArray();
        conditions.add(condition);

        JSONObject action = new JSONObject();
        action.put("action", "show");
        action.put("target_field", "video_url");
        JSONArray actions = new JSONArray();
        actions.add(action);

        JSONObject rule = new JSONObject();
        rule.put("conditions", conditions);
        rule.put("match_type", "all");
        rule.put("actions", actions);
        JSONArray rules = new JSONArray();
        rules.add(rule);

        JSONObject details = new JSONObject();
        details.put("field_rules", rules);
        JSONObject body = new JSONObject();
        body.put("content_type", details);

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

find

find lists the content types of the stack.

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

Validation

  • There is no client-side validation.
  • 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 call builds one Get all content types request (GET /content_types).
  • The request sends the query parameters of this object. The API accepts the following three:
    • include_count adds the total number of content types.
    • include_global_field_schema adds the schema of each global field inside the content types.
    • include_branch adds the _branch key.
  • find ignores the content type UID, so it works the same on stack.contentType() and on stack.contentType("<CONTENT_TYPE_UID>").
  • To read the content types as Java objects, use findAsPojo.

Example

Basic usage: list the content types

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

import java.io.IOException;

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

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

Error handling: read the error code

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.Error;
import com.contentstack.cms.stack.ContentType;
import com.google.gson.Gson;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

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

        try {
            Response<ResponseBody> response = contentType.find().execute();
            if (!response.isSuccessful()) {
                // Read the error body once and map it to the SDK's Error model
                Error error = new Gson().fromJson(response.errorBody().string(), Error.class);
                System.out.println("API error " + error.getErrorCode() + ": " + error.getErrorMessage());
                return;
            }
            System.out.println(response.body().string());
        } catch (IOException e) {
            // Thrown only when the request does not complete, such as a timeout
            System.out.println("Request did not complete: " + e.getMessage());
        }
    }
}

findAsPojo

findAsPojo lists the content types of the stack and maps the response to a ContentTypesResponse.

Returns: Call<ContentTypesResponse>. The request for all content types in the stack as typed objects, sent when you call execute().

Validation

  • There is no client-side validation.
  • An API rejection does not throw. response.isSuccessful() is false, response.body() is null, and the error details are in response.errorBody().

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

Behavior

  • Sends the same Get all content types request as find, with the query parameters of this object.
  • The SDK maps the content_types array of the response. Other top-level keys, such as count, do not reach your code. Use find to read them.
  • ContentTypesResponse has two getters:
    • getRawJson() returns each content type as a Map<String, Object>.
    • getContentTypes() returns a List<ContentTypePojo>.
  • ContentTypePojo has no public getters or fields, so code outside the SDK cannot read its values. Read the content types through getRawJson().

Example

Basic usage: print the UID and title of each content type

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.ContentType;
import com.contentstack.cms.stack.ContentTypesResponse;
import retrofit2.Response;

import java.io.IOException;
import java.util.Map;

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

        Response<ContentTypesResponse> response = contentType.findAsPojo().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;
        }
        for (Map<String, Object> item : response.body().getRawJson()) {
            System.out.println(item.get("uid") + ": " + item.get("title"));
        }
    }
}

importOverwrite

importOverwrite builds an Import a content type request that replaces an existing content type.

Returns: Call<ResponseBody>. The request for the content type import that replaces an existing one, sent when you call execute().

Validation

  • There is no client-side validation.
  • 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 call builds one POST /content_types/import?overwrite=true request with an empty body.
  • importOverwrite sends no other query parameter. Values from addParam do not reach this request.
  • importOverwrite adds the header Content-Type: multipart/form-data to this content type object. The header stays, so every later request from the object, and every entry you create from it afterward, sends that content type. Call importOverwrite on a separate content type object.

Example

Basic usage: build the overwrite import on a separate object

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

import java.io.IOException;

public class ImportContentTypeOverwrite {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        // This object serves the import only, so the multipart header reaches no other request
        ContentType importer = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").contentType();

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

imports

imports builds an Import a content type request for the stack.

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

Validation

  • There is no client-side validation.
  • 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 call builds one POST /content_types/import request with an empty body.
  • The request sends the query parameters of this object. The API accepts overwrite set to true to replace an existing content type, and include_branch.
  • importOverwrite sends the same path with overwrite=true fixed.

Example

Basic usage: build the import request

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

import java.io.IOException;

public class ImportContentType {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        ContentType contentType = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType()
                .addParam("overwrite", false);

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

reference

reference lists the content types that reference a content type, directly or through nested references, and optionally the global fields too.

NameTypeDescription
isIncludeGlobalField (required)Boolean

true also lists the global fields that reference the content type.

Default: Not applicable

Returns: Call<ResponseBody>. The request for the content types that reference this content type, sent when you call execute().

Validation

  • Throws NullPointerException if the content type has no UID, as after stack.contentType(), because the request path needs the UID.
  • A null value does not throw. The SDK then sends no include_global_fields parameter.
  • 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 call builds one Get all references of content type request (GET /content_types/{content_type_uid}/references?include_global_fields={value}).
  • The API returns direct and nested references. When B references content type A, and C references B, the request for C returns A and B.
  • reference sends only the include_global_fields parameter. Values from addParam do not reach this request.
  • referenceIncludeGlobalField sends the same request with the parameter fixed to true.

Example

Basic usage: list the content types and global fields that reference a content type

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

import java.io.IOException;

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

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

referenceIncludeGlobalField

referenceIncludeGlobalField lists the content types and the global fields that reference a content type.

Returns: Call<ResponseBody>. The request for the content types and global fields that reference this content type, sent when you call execute().

Validation

  • Throws NullPointerException if the content type has no UID, as after stack.contentType(), because the request path needs 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 call builds one Get all references of content type request (GET /content_types/{content_type_uid}/references?include_global_fields=true).
  • The result matches reference(true). See the reference method.
  • referenceIncludeGlobalField sends no other query parameter. Values from addParam do not reach this request.

Example

Basic usage: list references, including global fields

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

import java.io.IOException;

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

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

removeParam

removeParam removes one query parameter from this content type object, so that later requests no longer send it.

NameTypeDescription
key (required)String

Name of the query parameter to remove.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation. A key that the object does not hold changes nothing and does not throw.
  • 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

  • Removes the key from the map that addParam and addParams fill.
  • removeParam returns nothing, so you cannot chain another call after it. Call it as a separate statement.

Example

Basic usage: read the latest version after reading an earlier one

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

import java.io.IOException;

public class RemoveContentTypeParam {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        ContentType contentType = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType("<CONTENT_TYPE_UID>")
                .addParam("version", 1);

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

        contentType.removeParam("version");
        Response<ResponseBody> latest = contentType.fetch().execute();
        if (!latest.isSuccessful()) { System.out.println(latest.errorBody().string()); return; }
        System.out.println(latest.body().string());
    }
}

update

update replaces the schema of an existing content type.

NameTypeDescription
requestBody (required)JSONObject

Request body with the content type under a content_type key.

Default: Not applicable
requestBody.content_type.title (required)String

Name of the content type.

Default: Not applicable
requestBody.content_type.schema (required)JSONArray

The complete, updated field definitions.

Default: Not applicable

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

Validation

  • Throws NullPointerException if the content type has no UID, as after stack.contentType(), because the request path needs the UID.
  • A null body makes execute() throw IllegalArgumentException, 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().

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

Behavior

  • One call builds one Update Content Type request (PUT /content_types/{content_type_uid}) with requestBody as the JSON body.
  • The request sends the query parameters of this object. The API accepts include_branch.
  • Each update increments the version of the content type, as Update Content Type states.
  • fieldVisibilityRule sends the same request with field rules in the body.

Example

Basic usage: add a summary field to a content type

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

import java.io.IOException;

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

        JSONObject titleMetadata = new JSONObject();
        titleMetadata.put("_default", true);
        JSONObject title = new JSONObject();
        title.put("display_name", "Title");
        title.put("uid", "title");
        title.put("data_type", "text");
        title.put("field_metadata", titleMetadata);
        title.put("mandatory", true);

        JSONObject summary = new JSONObject();
        summary.put("display_name", "Summary");
        summary.put("uid", "summary");
        summary.put("data_type", "text");

        // Send every field. A field you leave out is not part of the new schema.
        JSONArray schema = new JSONArray();
        schema.add(title);
        schema.add(summary);

        JSONObject details = new JSONObject();
        details.put("title", "docs-test-blog-post");
        details.put("schema", schema);
        JSONObject body = new JSONObject();
        body.put("content_type", details);

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