ContentType

View as Markdown

ContentType

A content type defines the fields of one kind of content, such as a blog post or a product page. Every entry belongs to one content type. The ContentType class manages the content types of one stack through the Content Management API (CMA). Use this class to

  • list, create and import content types
  • read, update and delete one content type
  • list the content types that reference a content type
  • work with the entries of a content type through entry

Call the contentType method of the Stack class to get an object.

Instance State

  • Call stack.contentType() without a UID to work with the collection, for example create and query.
  • Call stack.contentType('<CONTENT_TYPE_UID>') to work with one content type, for example fetch and entry.
  • Each form has only its own methods. fetch and entry are undefined on stack.contentType(), and create is undefined on stack.contentType('<CONTENT_TYPE_UID>'), so calling the wrong one throws TypeError.
  • The objects that fetch, create, update, import and query().find() return are the single-item form.

Warning stack.contentType('') returns the collection form, because the SDK treats an empty string as no UID. Check the UID before you build the object.

Class-Level Notes

Branch scoping.

  • When you create the stack with branch_uid, every request from this class sends the branch header, and the API works with the content types of that branch.

Headers.

  • Every request sends the headers of this object, which start as the stack headers. Change them for this object only with addHeader, addHeaderDict and removeHeader.
  • entry and query pass the headers of this object on to the objects they return.

Rate limiting and retry.

  • This SDK automatically retries on 429 with configurable delay and attempt limits.

Additional Resource For more information on the retry options and their defaults, refer to the Contentstack documentation.

Capability Matrix

CapabilitySupportedNotes / Alternative
Export a content typeNoRead it with fetch, which returns the same schema
Pass include_global_fields to referencesNoreferences sends no query parameters
Import from a file in a browserNoimport reads a file path with Node.js fs. Use create with the schema object instead

Method Index

Work with the collection. Available on stack.contentType().

Method NameReturnsDescription
queryA query for content types, sent when you call find(), findOne() or count().Builds a content type query.
createThe new content type.Creates a content type.
importThe imported content type.Imports a content type from a JSON file.
generateUidThe generated UID.Builds a UID from a name.

Work with one content type. Available on stack.contentType('<CONTENT_TYPE_UID>').

Method NameReturnsDescription
fetchThe requested content type.Retrieves one content type.
updateThe updated content type.Saves the fields of this object.
updateCTThe API response with a notice and the updated content type.Saves a content type body that you pass.
deleteThe API response with a notice.Deletes the content type and its entries.
referencesThe API response with the content types that reference this one.Lists the referencing content types.
entryA new entry object.Opens the entries of the content type.

Set request headers. Available on both forms.

Method NameReturnsDescription
addHeaderThe same content type, for chaining.Adds one request header.
addHeaderDictThe same content type, for chaining.Adds several request headers.
removeHeaderThe same content type, for chaining.Removes one request header.

Class-Level Snippet

The snippet below reads one content type, prints its field UIDs, and lists the first ten of its entries.

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const contentType = await stack.contentType('<CONTENT_TYPE_UID>').fetch()
  console.log(contentType.title, contentType.schema.map((field) => field.uid))

  const result = await contentType.entry().query({ limit: 10 }).find()
  for (const entry of result.items) {
    console.log(entry.uid, entry.title)
  }
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

Methods

Each method of the ContentType class has its own section below, with its parameters, validation rules, behavior, and examples.

addHeader

addHeader adds one header to every request that this content type object sends.

NameTypeDescription
key (required)string

Header name, for example x-request-id.

Default: Not applicable
value (required)string

Header value to send.

Default: Not applicable

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

Validation

  • There is no client-side validation. A null or undefined key leaves the headers unchanged, and addHeader returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. addHeader sends no request.
  • The first header change on this object copies the headers that it inherited from the stack. The change then applies to this object only, not to the stack or to other objects that the same stack creates.
  • Every request method of this object sends its headers. A key that the object already holds gets the new value.
  • entry and query pass the headers of this object on to the objects they return. Change the headers first, then call them.

Example

Basic usage: tag the requests of one content type object

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const contentType = stack.contentType('<CONTENT_TYPE_UID>').addHeader('x-request-id', 'docs-123')
// Every request this object sends from now on carries the header
console.log(contentType.stackHeaders['x-request-id'])

addHeaderDict

addHeaderDict adds several headers to every request that this content type object sends.

NameTypeDescription
headerDict (required)object

Header names and values to add.

Default: Not applicable

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

Validation

  • There is no client-side validation. A null value, or a value that is not an object, leaves the headers unchanged, and addHeaderDict returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. addHeaderDict sends no request.
  • Copies every key of headerDict into the headers of this object. A key that the object already holds gets the new value.
  • The first header change on this object copies the headers that it inherited from the stack. The change then applies to this object only.

Example

Basic usage: send two extra headers from one content type object

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const contentType = stack.contentType()
  .addHeaderDict({ 'x-request-id': 'docs-123', 'x-team': 'docs' })
// query() on this object copies both headers
console.log(contentType.stackHeaders)

create

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

NameTypeDescription
data (required)object

Request body with the content type under content_type.

Default: Not applicable
data.content_type.title (required)string

Display name of the content type.

Default: Not applicable
data.content_type.uid (required)string

Unique ID of the content type in the stack.

Default: Not applicable
data.content_type.schema (required)object[]

Field definitions of the content type.

Default: Not applicable
data.content_type.optionsContentTypeOptions

Page settings such as is_page and singleton.

Default: API default
paramobject

Query parameters, sent as given.

Default: undefined (sends no query parameters)
param.include_branchboolean

Adds the _branch key to the response.

Default: API default

Returns: Promise<ContentType>. The new content type.

Validation

  • There is no client-side validation. create sends data as the JSON body as it is.
  • create exists only on stack.contentType(). On stack.contentType('<CONTENT_TYPE_UID>') it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends POST /v3/content_types with data as the body, as Create a content type describes.
  • Resolves to a new ContentType object that holds the fields of the created content type, with fetch, update, delete and entry.
  • To build a UID from the title, call generateUid first.

Example

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

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const content_type = {
  title: 'docs-test-blog-post',
  uid: 'docs_test_blog_post',
  schema: [
    { display_name: 'Title', uid: 'title', data_type: 'text', mandatory: true, unique: true, field_metadata: { _default: true } },
    { display_name: 'URL', uid: 'url', data_type: 'text', field_metadata: { _default: true } }
  ],
  options: { title: 'title', is_page: true, singleton: false, sub_title: [], url_pattern: '/:title' }
}

try {
  const contentType = await stack.contentType().create({ content_type })
  console.log(contentType.uid)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: create a content type on a branch and read the branch key

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>', branch_uid: '<BRANCH>' })

const content_type = {
  title: 'docs-test-author',
  uid: 'docs_test_author',
  schema: [
    { display_name: 'Title', uid: 'title', data_type: 'text', mandatory: true, unique: true, field_metadata: { _default: true } }
  ],
  options: { title: 'title', is_page: false, singleton: false, sub_title: [] }
}

try {
  const contentType = await stack.contentType().create({ content_type }, { include_branch: true })
  console.log(contentType.uid, contentType._branch)
} catch (error) {
  console.error(error.errorMessage)
}

delete

delete removes the content type whose UID you passed to stack.contentType('<CONTENT_TYPE_UID>'), with all of its entries.

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}
param.forceboolean

Forces the deletion of the content type.

Default: API default

Returns: Promise<Response>. The API response with a notice.

Warning A successful delete removes the content type and every entry in it, and you cannot undo it. Read the entries first with entry().query().find() if you need them.

Validation

  • There is no client-side validation.
  • delete exists only on stack.contentType('<CONTENT_TYPE_UID>') and on the objects that fetch, create and query().find() return. On stack.contentType() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends DELETE /v3/content_types/{content_type_uid} with every key of param as a query parameter, as Delete Content Type describes.
  • Resolves to the response body, which carries notice. When the API answers with an empty body, it resolves to { status, statusText } instead.

Example

Basic usage: delete a content type

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const response = await stack.contentType('<CONTENT_TYPE_UID>').delete()
  console.log(response.notice)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: force the deletion

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const response = await stack.contentType('<CONTENT_TYPE_UID>').delete({ force: true })
  console.log(response.notice)
} catch (error) {
  console.error(error.errorMessage)
}

entry

entry returns an object for the entries of this content type, or for one entry when you pass its UID. It sends no request.

NameTypeDescription
uidstring

UID of one entry.

Default: null (returns the collection form)
optionsobject

Options for the entry object.

Default: {}
options.api_versionstring | number

Value of the api_version header. Used only with uid.

Default: undefined (sends no api_version header)

Returns: Entry. A new entry object.

Known issue entry('<ENTRY_UID>', { api_version: '3.2' }) adds api_version to the headers that the whole stack object shares, so other objects from the same stack, such as assets, send it too until a create, fetch or update from that stack resolves. To send the header from one entry only, call entry('<ENTRY_UID>').addHeader('api_version', '3.2') instead.

Validation

  • There is no client-side validation.
  • entry exists only on stack.contentType('<CONTENT_TYPE_UID>') and on the objects that fetch, create and query().find() return. On stack.contentType() it is undefined, and calling it throws TypeError.
  • An invalid value surfaces as a rejected promise from the request method you call next.

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

Behavior

  • Client-side only. entry builds an Entry object with the content type UID and the headers of this object.
  • With a uid, the object works with one entry, for example fetch and publish.
  • Without a uid, or with an empty string, the object works with the entries of the content type, for example create and query.
  • options.api_version has no effect without a uid.

Example

Basic usage: read one entry

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const entry = await stack.contentType('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>').fetch()
  console.log(entry.uid, entry.title)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: publish an entry with the api_version header

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const entry = stack.contentType('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>', { api_version: '3.2' })
  const response = await entry.publish({
    publishDetails: { environments: ['<ENVIRONMENT>'], locales: ['<LOCALE>'] }
  })
  console.log(response.notice)
} catch (error) {
  console.error(error.errorMessage)
}

fetch

fetch retrieves the content type whose UID you passed to stack.contentType('<CONTENT_TYPE_UID>').

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}
param.versionnumber

Version of the content type to read.

Default: API default (latest version)
param.include_global_field_schemaboolean

Adds the schema of each Global field.

Default: API default
param.include_branchboolean

Adds the _branch key to the response.

Default: API default

Returns: Promise<ContentType>. The requested content type.

Validation

  • There is no client-side validation.
  • fetch exists only on stack.contentType('<CONTENT_TYPE_UID>'). On stack.contentType() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends GET /v3/content_types/{content_type_uid} with every key of param as a query parameter, as Get a single content type describes.
  • Without version, the API returns the latest version. The schema in the response matches the version you read.
  • Resolves to a new ContentType object that holds the content type fields, with update, delete, references and entry. The object you called fetch on does not change.

Example

Basic usage: read one content type

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const contentType = await stack.contentType('<CONTENT_TYPE_UID>').fetch()
  console.log(contentType.title, contentType.schema.length)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: read version 2 with Global field schemas on a branch

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>', branch_uid: '<BRANCH>' })

try {
  const contentType = await stack.contentType('<CONTENT_TYPE_UID>')
    .fetch({ version: 2, include_global_field_schema: true, include_branch: true })
  console.log(contentType._version, contentType._branch)
} catch (error) {
  console.error(error.errorMessage)
}

generateUid

generateUid builds a content type UID from a name, in lowercase with underscores. The following table lists its parameters.

NameTypeDescription
name (required)string

Name to build the UID from.

Default: Not applicable

Returns: string. The generated UID.

Validation

  • Throws TypeError if name is empty, null or undefined, because there is no text to build a UID from.
  • Throws TypeError if name is not a string, because the SDK calls name.replace.
  • generateUid exists only on stack.contentType(). On stack.contentType('<CONTENT_TYPE_UID>') it is undefined, and calling it throws TypeError.

Behavior

  • Client-side only. generateUid sends no request and does not check whether the UID is free in the stack.
  • Replaces every run of characters other than A to Z, a to z and 0 to 9 with one _, then lowercases the result. For example, My Blog Post 2 becomes my_blog_post_2.
  • Keeps an _ at the start or the end when the name starts or ends with such characters. Blog! becomes blog_.

Example

Basic usage: build the UID for a new content type

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const uid = stack.contentType().generateUid('docs-test Blog Post')
console.log(uid) // docs_test_blog_post

Error handling: catch an empty name

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  stack.contentType().generateUid('')
} catch (error) {
  // Thrown when the name is empty, null or undefined
  console.error(error instanceof TypeError, error.message)
}

import

import creates a content type, or replaces one, from a JSON file of its schema.

NameTypeDescription
data (required)object

Holds the path of the file to upload.

Default: Not applicable
data.content_type (required)string

Path of the content type JSON file.

Default: Not applicable
paramsobject

Query parameters, sent as given.

Default: {}
params.overwriteboolean

Replaces an existing content type with the same UID.

Default: API default
params.include_branchboolean

Adds the _branch key to the response.

Default: API default

Returns: Promise<ContentType>. The imported content type.

Validation

  • There is no client-side validation. The SDK does not check that the file exists before it sends the request.
  • import exists only on stack.contentType(). On stack.contentType('<CONTENT_TYPE_UID>') it is undefined, and calling it throws TypeError.
  • Without data, the returned promise rejects with a TypeError, because the SDK reads data.content_type to build the upload.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends POST /v3/content_types/import as multipart/form-data, with the file in a field named content_type, as Import a content type describes.
  • Reads the file with the Node.js fs module, so import runs only in Node.js.
  • Resolves to a new ContentType object that holds the fields of the imported content type.

Example

Basic usage: import a content type from a file

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const contentType = await stack.contentType().import({ content_type: '<FILE_PATH>' })
  console.log(contentType.uid, contentType.title)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: replace an existing content type on a branch

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>', branch_uid: '<BRANCH>' })

try {
  const contentType = await stack.contentType()
    .import({ content_type: '<FILE_PATH>' }, { overwrite: true, include_branch: true })
  console.log(contentType.uid, contentType._branch)
} catch (error) {
  console.error(error.errorMessage)
}

query

query builds a request for the content types of the stack. It sends nothing until you call a method of the returned query.

NameTypeDescription
paramsobject

Query parameters for the request.

Default: {}
params.queryobject

Condition on content type fields, sent as JSON.

Default: API default
params.include_countboolean

Adds the total number of content types.

Default: API default
params.include_global_field_schemaboolean

Adds the schema of each Global field.

Default: API default
params.include_branchboolean

Adds the _branch key to each content type.

Default: API default

Returns: Query. A query for content types, sent when you call find(), findOne() or count().

Validation

  • There is no client-side validation.
  • query exists only on stack.contentType(). On stack.contentType('<CONTENT_TYPE_UID>') it is undefined, and calling it throws TypeError.
  • An invalid value surfaces as a rejected promise from the request method you call next.

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

Behavior

  • Client-side only. query copies the headers of this object and params, and returns a Query object.
  • find and findOne send GET /v3/content_types and resolve to ContentType objects, as Get all content types describes. count resolves to the response body.
  • The SDK sends params.query as query=<JSON>, and every other key of params as a query parameter.

Example

Basic usage: list the content types of a stack

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const result = await stack.contentType().query().find()
  for (const contentType of result.items) {
    console.log(contentType.uid, contentType.title)
  }
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: find page content types with a count and Global field schemas

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>', branch_uid: '<BRANCH>' })

try {
  const result = await stack.contentType()
    .query({
      query: { 'options.is_page': true },
      include_count: true,
      include_global_field_schema: true,
      include_branch: true
    })
    .find()
  console.log(result.count)
  for (const contentType of result.items) {
    console.log(contentType.uid, contentType._branch)
  }
} catch (error) {
  console.error(error.errorMessage)
}

references

references lists the content types that reference this content type, directly or through other content types.

This method takes no parameters.

Returns: Promise<Response>. The API response with the content types that reference this one.

Validation

  • There is no client-side validation.
  • references exists only on stack.contentType('<CONTENT_TYPE_UID>') and on the objects that fetch, create and query().find() return. On stack.contentType() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends GET /v3/content_types/{content_type_uid}/references, as Get all references of content type describes.
  • The API includes both direct and nested references.
  • Resolves to the response body as the API returns it.
  • Does not send query parameters, so you cannot pass include_global_fields or include_branch.

Example

Basic usage: list the content types that reference a content type

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const response = await stack.contentType('<CONTENT_TYPE_UID>').references()
  console.log(JSON.stringify(response, null, 2))
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

removeHeader

removeHeader removes one header from the requests that this content type object sends.

NameTypeDescription
key (required)string

Name of the header to remove.

Default: Not applicable

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

Validation

  • There is no client-side validation. A null or undefined key, or a key that the object does not hold, leaves the headers unchanged.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. removeHeader sends no request.
  • Removing a header that the object inherited from the stack first copies the inherited headers, so the stack and other objects keep the header.
  • The SDK adds some headers at request time, for example the authorization header of the client. removeHeader cannot remove those.

Example

Basic usage: send requests from one content type object without the branch header

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>', branch_uid: '<BRANCH>' })

const contentType = stack.contentType('<CONTENT_TYPE_UID>').removeHeader('branch')
// This object now works with the default branch
console.log(contentType.stackHeaders.branch)

update

update saves the fields that this content type object holds, such as title and schema, to the stack.

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}
param.include_branchboolean

Adds the _branch key to the response.

Default: API default

Returns: Promise<ContentType>. The updated content type.

Validation

  • There is no client-side validation.
  • update exists only on stack.contentType('<CONTENT_TYPE_UID>') and on the objects that fetch, create and query().find() return. On stack.contentType() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends PUT /v3/content_types/{content_type_uid} with the body { content_type: <fields of this object> }, as Update Content Type describes. The SDK leaves out uid, created_at, created_by, updated_at, updated_by and its own keys.
  • The body holds only the fields this object has. Call fetch first, change the fields of the object it returns, and then call update, so that the body holds the full schema.
  • The API raises the content type version by one on every update.
  • Resolves to a new ContentType object with the saved fields. To send a body that you build yourself, use updateCT.

Example

Basic usage: rename a content type

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const contentType = await stack.contentType('<CONTENT_TYPE_UID>').fetch()
  contentType.title = 'Blog Post'
  contentType.description = 'Posts for the company blog'
  const updated = await contentType.update()
  console.log(updated.title, updated._version)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: add a field and read the branch key

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>', branch_uid: '<BRANCH>' })

try {
  const contentType = await stack.contentType('<CONTENT_TYPE_UID>').fetch()
  contentType.schema.push({ display_name: 'Author', uid: 'author', data_type: 'text' })
  const updated = await contentType.update({ include_branch: true })
  console.log(updated.schema.length, updated._branch)
} catch (error) {
  console.error(error.errorMessage)
}

updateCT

updateCT replaces the content type with the request body that you pass. The following table lists its parameters.

NameTypeDescription
config (required)object

Request body with the content type under content_type.

Default: Not applicable
config.content_type.title (required)string

Display name of the content type.

Default: Not applicable
config.content_type.schema (required)object[]

Full list of field definitions.

Default: Not applicable
config.content_type.optionsContentTypeOptions

Page settings such as is_page and singleton.

Default: API default

Returns: Promise<Response>. The API response with a notice and the updated content type.

Validation

  • There is no client-side validation. updateCT sends config as the JSON body as it is.
  • updateCT exists only on stack.contentType('<CONTENT_TYPE_UID>') and on the objects that fetch, create and query().find() return. On stack.contentType() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends PUT /v3/content_types/{content_type_uid} with config as the body, as Update Content Type describes. It sends no query parameters.
  • Resolves to the response body as the API returns it, not to a ContentType object. The updated content type is under content_type.
  • Use updateCT when you build the body yourself, for example from a stored schema. To save changes to a fetched object, use update.

Example

Basic usage: replace the schema of a content type

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const config = {
  content_type: {
    title: 'Blog Post',
    schema: [
      { display_name: 'Title', uid: 'title', data_type: 'text', mandatory: true, unique: true, field_metadata: { _default: true } },
      { display_name: 'URL', uid: 'url', data_type: 'text', field_metadata: { _default: true } },
      { display_name: 'Author', uid: 'author', data_type: 'text' }
    ],
    options: { title: 'title', is_page: true, singleton: false, sub_title: [], url_pattern: '/:title' }
  }
}

try {
  const response = await stack.contentType('<CONTENT_TYPE_UID>').updateCT(config)
  console.log(response.notice, response.content_type.schema.length)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}