Extensions

View as Markdown

Extensions

An extension adds custom behavior to the Contentstack interface. A custom field extension adds a field type that you can use in content types. Use this class to

  • list the extensions in a stack, or only the custom fields
  • upload a custom field from an HTML file, or create one from a source URL or source code
  • fetch, update, or delete one custom field

The extensions method on Stack returns a new Extensions. It has two forms:

NameTypeDescription
customFieldUidStringUID of the custom field. Omit it to list or create extensions.

Additional Resource The Extensions section of the Content Management API (CMA) reference describes every extension request and its response.

addHeader

addHeader adds one request header to the requests that this extensions object sends.

NameTypeDescription
key (required)String

Name of the request header.

Default: Not applicable
value (required)String

Value of the request header.

Default: Not applicable

Returns: Extensions. The same extensions, for chaining.

Validation

  • There is no client-side validation. addHeader stores any key and value.
  • An invalid value surfaces as an API error in the response when you call execute() on the request this method feeds.
  • A null key or value passes here. execute() then throws IllegalArgumentException on the next request.

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

Behavior

  • Client-side only. addHeader stores the header on this extensions object and makes no request.
  • Every request method on this extensions object sends every stored header.
  • stack.extensions() copies the stack's headers into the new object. addHeader changes only this object, not the stack or other objects.
  • A second call with the same key replaces the first value, including a header the stack set, such as authorization or branch.
  • fetch and uploadCustomField set Content-Type to multipart/form-data on this object, and uploadCustomFieldUsingJSONObject sets application/json. A Content-Type from addHeader lasts until one of those methods replaces it.

Example

Basic usage: fetch an extension from another branch

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

import java.io.IOException;

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

        Response<ResponseBody> response = extensions.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 request headers at once to the requests that this extensions object sends.

NameTypeDescription
headers (required)HashMap<String, String>

Header names and values to add.

Default: Not applicable

Returns: Extensions. The same extensions, for chaining.

Validation

  • Throws NullPointerException when the map is null, because addHeaders copies its entries.
  • 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

  • Client-side only. addHeaders copies every pair into the headers of this extensions object and makes no request.
  • Every request method on this extensions object sends every stored header.
  • A key that already exists takes the new value, including a header the stack set, such as authorization or branch.

Example

Basic usage: add headers from a map

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

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

public class ListExtensionsWithHeaders {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        HashMap<String, String> headers = new HashMap<>();
        headers.put("branch", "<BRANCH>");
        Extensions extensions = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").extensions().addHeaders(headers);

        Response<ResponseBody> response = extensions.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 requests that this extensions object sends.

NameTypeDescription
key (required)String

Name of the query parameter.

Default: Not applicable
value (required)Object

Value of the query parameter.

Default: Not applicable

Returns: Extensions. The same extensions, for chaining.

Validation

  • There is no client-side validation. addParam stores any key and value.
  • An invalid value surfaces as an API error in the response when you call execute() on the request this method feeds.
  • A null key or value passes here. execute() then throws IllegalArgumentException on a request that sends query parameters.

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

Behavior

  • Client-side only. addParam stores the pair on this extensions object and makes no request.
  • find, fetch, uploadCustomField, uploadCustomFieldUsingJSONObject, and update send every stored parameter. delete does not send them.
  • The SDK writes the value with its toString() method. Pass a JSONObject for a JSON value such as query, because its toString() returns JSON.
  • A second call with the same key replaces the first value. The parameter stays on the object for every later request until removeParam removes it.

Example

Basic usage: list only custom fields

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

import java.io.IOException;

public class ListCustomFields {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        JSONObject query = new JSONObject();
        query.put("type", "field");
        Extensions extensions = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").extensions()
                .addParam("query", query);

        Response<ResponseBody> response = extensions.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 at once to the requests that this extensions object sends.

NameTypeDescription
params (required)HashMap<String, Object>

Query parameter names and values to add.

Default: Not applicable

Returns: Extensions. A null reference, not the same extensions object.

Validation

  • Throws NullPointerException when the map is null, because addParams copies its entries.
  • 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

  • Known issue: In 1.16.0, addParams stores the parameters and then returns null, so a method chained after it throws NullPointerException. Call addParams as its own statement and call the next method on your Extensions variable, as the example below shows.
  • Client-side only. addParams copies every pair into the query parameters of this extensions object and makes no request.
  • find, fetch, uploadCustomField, uploadCustomFieldUsingJSONObject, and update send every stored parameter. delete does not send them.
  • A key that already exists takes the new value. Keys that are not in the map keep their values.

Example

Basic usage: add parameters without chaining after addParams

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

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

public class ListExtensionsWithParams {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        HashMap<String, Object> params = new HashMap<>();
        params.put("include_branch", true);
        Extensions extensions = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").extensions();
        // addParams returns null in 1.16.0, so call it as its own statement
        extensions.addParams(params);

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

delete

delete builds the request that deletes one custom field from the stack.

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

Validation

  • Throws IllegalAccessError when the object has no UID or an empty UID, because the request path needs one. Create the object with stack.extensions("<EXTENSION_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

Warning delete removes the custom field from the stack. The Extensions API has no request that restores a deleted custom field, so upload it again if you need it back.

  • One execute() sends one Delete custom field request (DELETE /v3/extensions/{custom_field_uid}) with the headers on this object.
  • delete does not send the query parameters from addParam.
  • The response body is the raw JSON from the API, with a notice message.

Example

Basic usage: delete a custom field

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

import java.io.IOException;

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

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

fetch

fetch builds the request that retrieves one custom field by its UID.

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

Validation

  • Throws IllegalAccessError when the object has no UID or an empty UID, because the request path needs one. Create the object with stack.extensions("<EXTENSION_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 execute() sends one Get a single custom field request (GET /v3/extensions/{custom_field_uid}) with the headers and query parameters on this object.
  • The API reference lists include_branch for this request. Add it with addParam to include the _branch key in the response.
  • fetch sets Content-Type to multipart/form-data on this object, and the value stays for later requests. Call update on a new object, as the Known issue on that page describes.
  • The response body is the raw JSON from the API.

Example

Basic usage: fetch one custom field

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

import java.io.IOException;

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

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

find

find builds the request that lists the extensions in the stack.

Returns: Call<ResponseBody>. The request for the stack's extensions, 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 execute() sends one Get all custom fields request (GET /v3/extensions) with the headers and query parameters on this object.
  • The API reference lists the following two query parameters for this request. Add them with addParam:
    • query: {"type":"field"} limits the list to custom fields.
    • include_branch: true adds the _branch key to the response.
  • The response body is the raw JSON from the API, with the extensions under an extensions array.
  • The SDK sends one request and does not page through results.

Example

Basic usage: list the custom fields in the stack

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

import java.io.IOException;

public class ListCustomFieldExtensions {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        JSONObject query = new JSONObject();
        query.put("type", "field");

        Extensions extensions = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").extensions()
                .addParam("query", query)
                .addParam("include_branch", true);

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

removeParam

removeParam removes one query parameter from this extensions object.

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 removeParam does not throw.

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

Behavior

Example

Basic usage: drop a parameter before the next request

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

import java.io.IOException;

public class RemoveExtensionParam {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        Extensions extensions = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").extensions()
                .addParam("include_branch", true);
        extensions.removeParam("include_branch");

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

update

update builds the request that changes the details of one custom field, such as its title, tags, source, or configuration.

NameTypeDescription
body (required)JSONObject

Request body with the field under an extension key.

Default: Not applicable
body.extension.titleString

Title of the custom field.

Default: API default
body.extension.data_typeString

Data type of the field input.

Default: API default
body.extension.typeString

Extension type, field for a custom field.

Default: API default
body.extension.srcString

URL that hosts the field.

Default: API default
body.extension.srcdocString

Source code of the field.

Default: API default
body.extension.tagsList<String>

Tags for the custom field.

Default: API default
body.extension.multipleBoolean

true to store multiple values.

Default: API default
body.extension.configString

Configuration of the field, as JSON text.

Default: API default

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

Validation

  • Throws NullPointerException when body is null, because update checks the body first.
  • Throws IllegalAccessError when the object has no UID or an empty UID, because the request path needs one. Create the object with stack.extensions("<EXTENSION_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

  • Known issue: In 1.16.0, after fetch or uploadCustomField runs on the same object, update labels its JSON body multipart/form-data. Call update on a new object from stack.extensions("<EXTENSION_UID>"), or call addHeader("Content-Type", "application/json") before update.
  • One execute() sends one Update a custom field request (PUT /v3/extensions/{custom_field_uid}) with body as the JSON body and the query parameters on this object.
  • The response body is the raw JSON from the API, with the updated field under an extension key.

Example

Basic usage: change the title and tags of a custom field

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

import java.io.IOException;

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

        JSONArray tags = new JSONArray();
        tags.add("rating");

        JSONObject extension = new JSONObject();
        extension.put("title", "Star rating");
        extension.put("tags", tags);
        JSONObject body = new JSONObject();
        body.put("extension", extension);

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

All parameters: replace every detail of a hosted custom field

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

import java.io.IOException;

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

        JSONArray tags = new JSONArray();
        tags.add("rating");
        tags.add("review");

        JSONObject extension = new JSONObject();
        extension.put("title", "Star rating");
        extension.put("data_type", "number");
        extension.put("type", "field");
        extension.put("src", "https://example.com/rating-field-v2.html");
        extension.put("tags", tags);
        extension.put("multiple", false);
        extension.put("config", "{\"max\": 5}");
        JSONObject body = new JSONObject();
        body.put("extension", extension);

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

Source code: switch a custom field to source code that Contentstack hosts

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

import java.io.IOException;

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

        JSONObject extension = new JSONObject();
        extension.put("srcdoc", "<html><body><input type=\"number\" max=\"5\"></body></html>");
        JSONObject body = new JSONObject();
        body.put("extension", extension);

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

uploadCustomField

uploadCustomField builds the request that uploads a custom field to the stack as multipart form data, with the HTML file of the field and its settings.

NameTypeDescription
body (required)Map<String, RequestBody>

Form fields to send. Each key is a form field name.

Default: Not applicable
body["extension[upload]"] (required)RequestBody

HTML file of the custom field.

Default: Not applicable
body["extension[title]"] (required)RequestBody

Title of the custom field.

Default: Not applicable
body["extension[data_type]"] (required)RequestBody

Data type of the field input, for example text.

Default: Not applicable
body["extension[type]"] (required)RequestBody

Extension type. Pass field.

Default: Not applicable
body["extension[tags]"]RequestBody

Tags for the custom field.

Default: API default
body["extension[multiple]"]RequestBody

true to store multiple values.

Default: API default

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

Validation

  • There is no client-side validation. uploadCustomField does not check the map keys or values.
  • execute() throws IllegalArgumentException when body is null or holds a null key or value, because Retrofit cannot build the form.
  • 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 execute() sends one Upload a custom field request (POST /v3/extensions) as multipart form data, with the query parameters on this object.
  • The SDK sends one form part per map entry. Each part takes the map key as its name and sends no file name.
  • uploadCustomField sets Content-Type to multipart/form-data on this object, and the value stays for later requests. Call update on a new object, as the Known issue on that page describes.
  • To create a custom field from a source URL or from source code instead of a file, use the uploadCustomFieldUsingJSONObject method.

Example

Basic usage: upload a custom field from an HTML file

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Extensions;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;

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

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

        MediaType text = MediaType.parse("text/plain");
        Map<String, RequestBody> body = new HashMap<>();
        body.put("extension[upload]", RequestBody.create(MediaType.parse("text/html"), new File("<FILE_PATH>")));
        body.put("extension[title]", RequestBody.create(text, "docs-test-rating"));
        body.put("extension[data_type]", RequestBody.create(text, "number"));
        body.put("extension[type]", RequestBody.create(text, "field"));
        body.put("extension[tags]", RequestBody.create(text, "rating,review"));
        body.put("extension[multiple]", RequestBody.create(text, "false"));

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

uploadCustomFieldUsingJSONObject

uploadCustomFieldUsingJSONObject builds the request that creates a custom field from a JSON body, with either a source URL that hosts the field or the field's source code.

NameTypeDescription
body (required)JSONObject

Request body with the field under an extension key.

Default: Not applicable
body.extension.title (required)String

Title of the custom field.

Default: Not applicable
body.extension.data_type (required)String

Data type of the field input, for example text.

Default: Not applicable
body.extension.type (required)String

Extension type. Pass field.

Default: Not applicable
body.extension.srcString

URL that hosts the field. Pass this or srcdoc.

Default: API default
body.extension.srcdocString

Source code of the field. Pass this or src.

Default: API default
body.extension.tagsList<String>

Tags for the custom field.

Default: API default
body.extension.multipleBoolean

true to store multiple values.

Default: API default
body.extension.configString

Configuration of the field, as JSON text.

Default: API default

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

Validation

  • There is no client-side validation. uploadCustomFieldUsingJSONObject does not check body.
  • execute() throws IllegalArgumentException when body is null, because the request needs 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 execute() sends one POST /v3/extensions request with body as the JSON body and the query parameters on this object.
  • The API reference documents two forms of this request:
  • The API reference lists Text, Number, Date, Boolean, JSON, Reference, File, and Asset as the data types of a custom field.
  • uploadCustomFieldUsingJSONObject sets Content-Type to application/json on this object, and the value stays for later requests.
  • The response body is the raw JSON from the API, with the new field under an extension key.

Example

Basic usage: create a custom field from a source URL

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

import java.io.IOException;

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

        JSONObject extension = new JSONObject();
        extension.put("title", "docs-test-rating");
        extension.put("data_type", "number");
        extension.put("src", "https://example.com/rating-field.html");
        extension.put("type", "field");
        JSONObject body = new JSONObject();
        body.put("extension", extension);

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

All parameters: create a custom field from source code with tags and configuration

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

import java.io.IOException;

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

        JSONArray tags = new JSONArray();
        tags.add("rating");
        tags.add("review");

        JSONObject extension = new JSONObject();
        extension.put("title", "docs-test-color-picker");
        extension.put("data_type", "text");
        extension.put("srcdoc", "<html><body><input type=\"color\"></body></html>");
        extension.put("type", "field");
        extension.put("tags", tags);
        extension.put("multiple", false);
        extension.put("config", "{}");
        JSONObject body = new JSONObject();
        body.put("extension", extension);

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