ContentType

View as Markdown

ContentType

ContentType creates, fetches, lists, updates, and deletes the content types of a stack, and opens the entries of one content type. A content type defines the schema that every entry of that type follows.

When to Use This Class: Use this class when your code builds or changes a content model. For example, a stack setup script creates a Blog Post content type, or an import job reads a schema before it writes entries.

Conceptual Role: Acts as the Content Management API (CMA) client for the /content_types endpoint. Call stack.ContentType() to get an instance, and describe the schema with a ContentModelling object.

Returns: ContentType. A handle for content type operations.

Instance State

The UID you pass to stack.ContentType() decides which methods you can call on the instance:

  • Call stack.ContentType() without a UID to work with the content type collection, for example Query or Create.
  • Call stack.ContentType("<CONTENT_TYPE_UID>") to work with one content type, for example Fetch or Delete, or to open its entries with Entry.

If you call a method from the other group, it throws before any request leaves the SDK. A collection method on an instance that has a UID throws InvalidOperationException, and a single-item method on an instance with no UID throws ArgumentException.

The Method Index below lists every method in each group.

Warning The SDK checks for an empty string as if it were no UID, so stack.ContentType("") allows Query and Create, and the SDK then sends the request to /content_types/ with a trailing slash. Pass null, or call stack.ContentType() with no argument, when you mean the collection.

Class-Level Notes

Authentication.

  • stack.ContentType() throws InvalidOperationException when the client has no authtoken and the Stack has no management token, and when the Stack has no API key.
  • The CMA accepts an authtoken, a management token, or an Open Authorization (OAuth) token for every content type request. When the Stack has a management token, the SDK sends it instead of the client's authtoken.

Request body.

  • Create and Update serialize the ContentModelling object under the content_type key. The SDK leaves out every property that is null.
  • Update replaces the schema. Send the complete Schema list, including the fields you do not change.

Branch scoping.

  • Content type requests accept a branch header. Create the Stack with client.Stack("<API_KEY>", "<MANAGEMENT_TOKEN>", "<BRANCH_UID>") to send every request of this class to that branch.

Errors.

  • The SDK throws ContentstackErrorException when the API returns an error status. Read StatusCode, ErrorCode, ErrorMessage, and Errors on the exception to see what the API rejected.

Rate Limiting & Retry.

  • This SDK automatically retries a request that returns 429, 500, 502, 503, or 504, with configurable delay and attempt limits.

Additional Resources For more information on retry settings, refer to the ContentstackClientOptions documentation. For the request shapes, refer to the Content Types section of the Content Management API reference.

Capability Matrix

CapabilitySupportedNotes / Alternative
Fetch an earlier version of a content typeYesPass version in the collection of Fetch.
Return the schema of global fields inside a content typeYesPass include_global_field_schema set to true in the collection of Fetch or of the query's Find.
Export or import a content type as a JSON fileNoThe CMA has export and import requests, and this SDK has no method for them. Fetch the content type and create it in the other stack instead.
List the content types that reference this oneNoThe CMA has a references request, and this SDK has no method for it.

Method Index

Work with the content type collection. Available on stack.ContentType() when you pass no UID.

Method NameReturnsDescription
QueryA new query for content types.Builds a query that lists content types.
CreateThe API response with the created content type.Creates a content type from a schema.
CreateAsyncThe API response with the created content type.Creates a content type from a schema asynchronously.

Work with one content type. Available on stack.ContentType("<CONTENT_TYPE_UID>").

Method NameReturnsDescription
FetchThe API response with the requested content type.Retrieves one content type.
FetchAsyncThe API response with the requested content type.Retrieves one content type asynchronously.
UpdateThe API response with the updated content type.Replaces the schema of a content type.
UpdateAsyncThe API response with the updated content type.Replaces the schema of a content type asynchronously.
DeleteThe API response with the deletion notice.Deletes a content type and its entries.
DeleteAsyncThe API response with the deletion notice.Deletes a content type and its entries asynchronously.
EntryA new entry object.Opens the entries of this content type.

Class-Level Snippet

The snippet below creates a Blog Post content type with two fields, fetches it, and lists every content type in the stack.

using System;
using System.Collections.Generic;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
Stack stack = client.Stack("<API_KEY>");

ContentModelling model = new ContentModelling
{
    Title = "Blog Post",
    Uid = "blog_post",
    Schema = new List<Field>
    {
        new TextboxField { DisplayName = "Title", Uid = "title", DataType = "text", Mandatory = true, Unique = true },
        new TextboxField { DisplayName = "URL", Uid = "url", DataType = "text" }
    },
    Options = new Option { Title = "title", IsPage = true, UrlPrefix = "/blog/" }
};

try
{
    await stack.ContentType().CreateAsync(model);

    ContentstackResponse fetched = await stack.ContentType("blog_post").FetchAsync();
    Console.WriteLine(fetched.OpenJsonObjectResponse()["content_type"]?["title"]);

    ContentstackResponse list = await stack.ContentType().Query().IncludeCount().FindAsync();
    Console.WriteLine($"Content types in the stack: {list.OpenJsonObjectResponse()["count"]}");
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Methods

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

Create

Create creates a content type in the stack from the schema in a ContentModelling object.

NameTypeDescription
model (required)ContentModelling

Title, UID, schema, and options of the new content type.

Default: Not applicable
collectionParameterCollection?

Adds query parameters, for example include_branch.

Default: null

Returns: ContentstackResponse. The API response with the created content type.

Validation

  • Throws InvalidOperationException if the instance has a UID, because Create adds a new content type to the collection. Call stack.ContentType() with no UID, and set the UID of the new content type in model.Uid.
  • Throws ArgumentNullException (parameter dataModel) if model is null, before any request.
  • The SDK does not check model. A missing title, a duplicate UID, or an invalid field reaches the API, and the SDK throws the API rejection as ContentstackErrorException. Read e.Errors for the field that the API rejected.
  • collection set to null sends no query parameters.

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

Behavior

  • Sends one POST request to /content_types with the body {"content_type": <model>}. The SDK leaves out every ContentModelling property that is null.
  • The Create a content type request of the Content Management API reference describes the schema. The API creates the content type with the UID in model.Uid.
  • Each entry in model.Schema is a Field subclass. The SDK serializes the properties of the subclass, so a TextboxField sends format and a ReferenceField sends reference_to.
  • Returns the raw API response. The new content type sits under the content_type key.

Example

Basic usage: create a content type with a title field

using System;
using System.Collections.Generic;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

ContentModelling model = new ContentModelling
{
    Title = "Blog Post",
    Uid = "blog_post",
    Schema = new List<Field>
    {
        new TextboxField { DisplayName = "Title", Uid = "title", DataType = "text", Mandatory = true, Unique = true }
    }
};

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType().Create(model);
    Console.WriteLine(response.OpenJsonObjectResponse()["content_type"]?["uid"]);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: create a page content type with a reference field, using a management token

using System;
using System.Collections.Generic;
using System.Text.Json;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();

ContentModelling model = new ContentModelling
{
    Title = "Blog Post",
    Uid = "blog_post",
    Description = "Articles for the company blog",
    Schema = new List<Field>
    {
        new TextboxField { DisplayName = "Title", Uid = "title", DataType = "text", Mandatory = true, Unique = true },
        new TextboxField { DisplayName = "URL", Uid = "url", DataType = "text" },
        new ReferenceField
        {
            DisplayName = "Author",
            Uid = "author",
            DataType = "reference",
            ReferenceTo = JsonSerializer.SerializeToElement(new[] { "author" }),
            FieldMetadata = new FieldMetadata { RefMultiple = false }
        }
    },
    Options = new Option { Title = "title", IsPage = true, UrlPattern = "/:title", UrlPrefix = "/blog/" }
};

ParameterCollection collection = new ParameterCollection();
collection.Add("include_branch", true);

try
{
    ContentstackResponse response = client.Stack("<API_KEY>", "<MANAGEMENT_TOKEN>").ContentType().Create(model, collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["content_type"]?["_branch"]);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

Edge case: calling Create on an instance that has a UID

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

ContentModelling model = new ContentModelling { Title = "Blog Post", Uid = "blog_post" };

try
{
    // The UID belongs in the model, not in stack.ContentType().
    client.Stack("<API_KEY>").ContentType("blog_post").Create(model);
}
catch (InvalidOperationException e)
{
    // Fires before any request, because the instance has a UID
    Console.WriteLine(e.Message);
}

CreateAsync

CreateAsync creates a content type in the stack from the schema in a ContentModelling object, without blocking the calling thread.

NameTypeDescription
model (required)ContentModelling

Title, UID, schema, and options of the new content type.

Default: Not applicable
collectionParameterCollection?

Adds query parameters, for example include_branch.

Default: null

Returns: Task<ContentstackResponse>. The API response with the created content type.

Validation

  • Throws InvalidOperationException if the instance has a UID, because CreateAsync adds a new content type to the collection. Call stack.ContentType() with no UID.
  • Throws ArgumentNullException (parameter dataModel) if model is null.
  • The SDK throws the exceptions above when you call CreateAsync, before it returns a task. An API rejection surfaces when you await the task, as ContentstackErrorException.

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

Behavior

  • Sends the same POST request as Create, on a task that you await.
  • Otherwise behaves like Create.

Example

Basic usage: create a content type with a title field

using System;
using System.Collections.Generic;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

ContentModelling model = new ContentModelling
{
    Title = "Blog Post",
    Uid = "blog_post",
    Schema = new List<Field>
    {
        new TextboxField { DisplayName = "Title", Uid = "title", DataType = "text", Mandatory = true, Unique = true }
    }
};

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").ContentType().CreateAsync(model);
    Console.WriteLine(response.OpenJsonObjectResponse()["content_type"]?["uid"]);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: create a single-page content type with a management token

using System;
using System.Collections.Generic;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();

ContentModelling model = new ContentModelling
{
    Title = "Home Page",
    Uid = "home_page",
    Schema = new List<Field>
    {
        new TextboxField { DisplayName = "Title", Uid = "title", DataType = "text", Mandatory = true, Unique = true }
    },
    Options = new Option { Title = "title", Singleton = true, IsPage = true }
};

ParameterCollection collection = new ParameterCollection();
collection.Add("include_branch", true);

try
{
    ContentstackResponse response = await client
        .Stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .ContentType()
        .CreateAsync(model, collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

Delete

Delete deletes the content type whose UID you passed to stack.ContentType(), together with all its entries.

NameTypeDescription
collectionParameterCollection?

Adds query parameters, for example force.

Default: null

Returns: ContentstackResponse. The API response with the deletion notice.

Validation

  • Throws ArgumentException (parameter uid) if the instance has no UID or an empty string, because Delete removes one content type. Call stack.ContentType("<CONTENT_TYPE_UID>").
  • The SDK does not check the UID format. A UID that names no content type reaches the API, and the SDK throws the API rejection as ContentstackErrorException.
  • collection set to null sends no query parameters, so the request carries no force flag.

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

Behavior

  • Sends one DELETE request to /content_types/<CONTENT_TYPE_UID>, with the entries of collection as query parameters.
  • The Delete Content Type request of the Content Management API reference deletes the content type and all the entries in it. Pass force set to true in collection to force the deletion.
  • Returns the raw API response with a notice key.

Warning Deleting a content type also deletes every entry of that content type. The SDK and the API offer no way to restore them.

Example

Basic usage: delete a content type

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType("<CONTENT_TYPE_UID>").Delete();
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: force the deletion with a management token

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();

ParameterCollection collection = new ParameterCollection();
collection.Add("force", true);

try
{
    ContentstackResponse response = client
        .Stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .ContentType("<CONTENT_TYPE_UID>")
        .Delete(collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

DeleteAsync

DeleteAsync deletes the content type whose UID you passed to stack.ContentType(), together with all its entries, without blocking the calling thread.

NameTypeDescription
collectionParameterCollection?

Adds query parameters, for example force.

Default: null

Returns: Task<ContentstackResponse>. The API response with the deletion notice.

Validation

  • Throws ArgumentException (parameter uid) if the instance has no UID or an empty string, because DeleteAsync removes one content type. Call stack.ContentType("<CONTENT_TYPE_UID>").
  • The SDK throws the exception above when you call DeleteAsync, before it returns a task.
  • An API rejection surfaces when you await the task, as ContentstackErrorException.

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

Behavior

  • Sends the same DELETE request as Delete, on a task that you await.
  • Otherwise behaves like Delete.

Warning Deleting a content type also deletes every entry of that content type. The SDK and the API offer no way to restore them.

Example

Basic usage: delete a content type

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").ContentType("<CONTENT_TYPE_UID>").DeleteAsync();
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: force the deletion with a management token

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();

ParameterCollection collection = new ParameterCollection();
collection.Add("force", true);

try
{
    ContentstackResponse response = await client
        .Stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .ContentType("<CONTENT_TYPE_UID>")
        .DeleteAsync(collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

Entry

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

NameTypeDescription
uidstring?

UID of one entry. Omit it to work with all entries.

Default: null

Returns: Entry. A new entry object.

Validation

  • Throws ArgumentException (parameter uid) if the content type instance has no UID or an empty string, because entries belong to one content type. Call stack.ContentType("<CONTENT_TYPE_UID>") first.
  • uid set to null returns an object for the entry collection, for example to call Query or Create on it.
  • Entry sends no request. Errors from the API come from the method you call on the returned object.

Behavior

  • Builds the request path /content_types/<CONTENT_TYPE_UID>/entries, or /content_types/<CONTENT_TYPE_UID>/entries/<ENTRY_UID> when you pass uid.
  • The returned object sends its requests with the same Stack, so it uses the same API key, token, and branch.
  • See the Entry class for the methods you can call on the returned object.

Example

Basic usage: fetch one entry of a content type

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client
        .Stack("<API_KEY>")
        .ContentType("<CONTENT_TYPE_UID>")
        .Entry("<ENTRY_UID>")
        .Fetch();
    Console.WriteLine(response.OpenJsonObjectResponse()["entry"]?["title"]);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Collection: list the entries of a content type with a management token

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient();

try
{
    ContentstackResponse response = client
        .Stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .ContentType("<CONTENT_TYPE_UID>")
        .Entry()
        .Query()
        .Find();
    Console.WriteLine(response.OpenJsonObjectResponse()["entries"]?.AsArray().Count);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

Edge case: calling Entry on a content type instance with no UID

using System;
using Contentstack.Management.Core;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    client.Stack("<API_KEY>").ContentType().Entry("<ENTRY_UID>");
}
catch (ArgumentException e)
{
    // Fires before any request, because the content type instance has no UID
    Console.WriteLine(e.Message);
}

Fetch

Fetch retrieves the content type whose UID you passed to stack.ContentType(), including its schema.

NameTypeDescription
collectionParameterCollection?

Adds query parameters, for example version.

Default: null

Returns: ContentstackResponse. The API response with the requested content type.

Validation

  • Throws ArgumentException (parameter uid) if the instance has no UID or an empty string, because Fetch reads one content type. Call stack.ContentType("<CONTENT_TYPE_UID>").
  • The SDK does not check the UID format. A UID that names no content type reaches the API, and the SDK throws the API rejection as ContentstackErrorException.
  • collection set to null sends no query parameters.

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

Behavior

  • Sends one GET request to /content_types/<CONTENT_TYPE_UID>, with the entries of collection as query parameters. The Get a single content type request of the Content Management API reference describes the parameters the API accepts:
    • version returns the schema of that content type version. Without it, the API returns the latest version.
    • include_global_field_schema set to true adds the schema of each global field that the content type uses.
    • include_branch set to true adds the _branch key to the response.
  • Returns the raw API response. The content type sits under the content_type key. Read it as JSON with OpenJsonObjectResponse(), or deserialize the content_type node into a ContentModelling object.

Example

Basic usage: fetch a content type by UID

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType("<CONTENT_TYPE_UID>").Fetch();
    Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: fetch an earlier version with global field schemas, using a management token

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();

ParameterCollection collection = new ParameterCollection();
collection.Add("version", 2);
collection.Add("include_global_field_schema", true);

try
{
    ContentstackResponse response = client
        .Stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .ContentType("<CONTENT_TYPE_UID>")
        .Fetch(collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["content_type"]?["_version"]);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

Typed result: read the schema into ContentModelling

using System;
using System.Text.Json;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType("<CONTENT_TYPE_UID>").Fetch();

    // The content type sits under the "content_type" key, so deserialize that node.
    // client.SerializerOptions picks the Field subclass for each schema entry.
    ContentModelling? model = response.OpenJsonObjectResponse()["content_type"]?.Deserialize<ContentModelling>(client.SerializerOptions);

    foreach (Field field in model?.Schema ?? new())
    {
        Console.WriteLine($"{field.Uid}: {field.GetType().Name}");
    }
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

FetchAsync

FetchAsync retrieves the content type whose UID you passed to stack.ContentType(), including its schema, without blocking the calling thread.

NameTypeDescription
collectionParameterCollection?

Adds query parameters, for example version.

Default: null

Returns: Task<ContentstackResponse>. The API response with the requested content type.

Validation

  • Throws ArgumentException (parameter uid) if the instance has no UID or an empty string, because FetchAsync reads one content type. Call stack.ContentType("<CONTENT_TYPE_UID>").
  • The SDK throws the exception above when you call FetchAsync, before it returns a task.
  • An API rejection surfaces when you await the task, as ContentstackErrorException.

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

Behavior

  • Sends the same GET request as Fetch, on a task that you await.
  • Otherwise behaves like Fetch.

Example

Basic usage: fetch a content type by UID

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").ContentType("<CONTENT_TYPE_UID>").FetchAsync();
    Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: fetch an earlier version with global field schemas, using a management token

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();

ParameterCollection collection = new ParameterCollection();
collection.Add("version", 2);
collection.Add("include_global_field_schema", true);

try
{
    ContentstackResponse response = await client
        .Stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .ContentType("<CONTENT_TYPE_UID>")
        .FetchAsync(collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["content_type"]?["_version"]);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

Query

Query returns a query object that lists the content types in the stack when you call Find or FindAsync on it.

This method takes no parameters.

Returns: Query. A new query for content types.

Validation

  • Throws InvalidOperationException if the instance has a UID, because Query lists the content type collection. Call stack.ContentType() with no UID.
  • Query sends no request. Errors that do occur come from the Find or FindAsync call that follows, not from Query. The SDK throws an API rejection as ContentstackErrorException.

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

Behavior

  • Find and FindAsync send one GET request to /content_types. The request carries the parameters from Limit, Skip, IncludeCount, and the collection argument of Find. See the Query class for those methods.
  • The Get all content types request of the Content Management API reference accepts include_count, include_global_field_schema, include_branch, and a query filter in JSON. Pass a filter with ParameterCollection.AddQuery.
  • Returns the raw API response. The content types sit under the content_types key, and count holds the total when you call IncludeCount.
  • Does not page through the results for you. Without Limit and Skip, the API applies its own page size.

Example

Basic usage: list the content types in a stack

using System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType().Query().Find();
    JsonArray? contentTypes = response.OpenJsonObjectResponse()["content_types"]?.AsArray();

    foreach (JsonNode? contentType in contentTypes ?? new JsonArray())
    {
        Console.WriteLine($"{contentType?["uid"]}: {contentType?["title"]}");
    }
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Paging: read one page of content types with a count and global field schemas

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();

ParameterCollection collection = new ParameterCollection();
collection.Add("include_global_field_schema", true);

try
{
    ContentstackResponse response = await client
        .Stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
        .ContentType()
        .Query()
        .Limit(10)
        .Skip(0)
        .IncludeCount()
        .FindAsync(collection);
    Console.WriteLine($"Total content types: {response.OpenJsonObjectResponse()["count"]}");
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

Filter: find content types by title

using System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

ParameterCollection collection = new ParameterCollection();
collection.AddQuery(new JsonObject { ["title"] = "Blog Post" });

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType().Query().Find(collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["content_types"]?.AsArray().Count);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

Update

Update replaces the schema and settings of the content type whose UID you passed to stack.ContentType().

NameTypeDescription
model (required)ContentModelling

The complete new schema and settings.

Default: Not applicable
collectionParameterCollection?

Adds query parameters, for example include_branch.

Default: null

Returns: ContentstackResponse. The API response with the updated content type.

Validation

  • Throws ArgumentException (parameter uid) if the instance has no UID or an empty string, because Update changes one content type. Call stack.ContentType("<CONTENT_TYPE_UID>").
  • Throws ArgumentNullException (parameter dataModel) if model is null, before any request.
  • The SDK does not check model. An invalid schema reaches the API, and the SDK throws the API rejection as ContentstackErrorException.

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

Behavior

  • Sends one PUT request to /content_types/<CONTENT_TYPE_UID> with the body {"content_type": <model>}. The SDK leaves out every ContentModelling property that is null.
  • The Update Content Type request of the Content Management API reference replaces the schema with the one you send and increments the content type version. Send every field you want to keep, not only the changed ones.
  • Set model.FieldRules to add field visibility rules, as the Set Field Visibility Rule for Content Type request describes. See FieldRules.
  • Returns the raw API response. The updated content type sits under the content_type key.

Warning The API replaces the schema with the one you send, so the content type loses every field that you leave out of model.Schema. Fetch the content type first and change the fetched schema.

Example

Basic usage: rename a content type and keep its fields

using System;
using System.Collections.Generic;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

ContentModelling model = new ContentModelling
{
    Title = "Article",
    Uid = "blog_post",
    Schema = new List<Field>
    {
        new TextboxField { DisplayName = "Title", Uid = "title", DataType = "text", Mandatory = true, Unique = true },
        new TextboxField { DisplayName = "URL", Uid = "url", DataType = "text" }
    }
};

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType("blog_post").Update(model);
    Console.WriteLine(response.OpenJsonObjectResponse()["content_type"]?["title"]);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: add a field to the fetched schema, using a management token

using System;
using System.Text.Json;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();
Stack stack = client.Stack("<API_KEY>", "<MANAGEMENT_TOKEN>");

ParameterCollection collection = new ParameterCollection();
collection.Add("include_branch", true);

try
{
    ContentstackResponse fetched = stack.ContentType("<CONTENT_TYPE_UID>").Fetch();
    ContentModelling model = fetched.OpenJsonObjectResponse()["content_type"]!.Deserialize<ContentModelling>(client.SerializerOptions)!;

    model.Schema!.Add(new NumberField { DisplayName = "Reading Time", Uid = "reading_time", DataType = "number", Min = 1 });

    ContentstackResponse response = stack.ContentType("<CONTENT_TYPE_UID>").Update(model, collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

UpdateAsync

UpdateAsync replaces the schema and settings of the content type whose UID you passed to stack.ContentType(), without blocking the calling thread.

NameTypeDescription
model (required)ContentModelling

The complete new schema and settings.

Default: Not applicable
collectionParameterCollection?

Adds query parameters, for example include_branch.

Default: null

Returns: Task<ContentstackResponse>. The API response with the updated content type.

Validation

  • Throws ArgumentException (parameter uid) if the instance has no UID or an empty string, because UpdateAsync changes one content type. Call stack.ContentType("<CONTENT_TYPE_UID>").
  • Throws ArgumentNullException (parameter dataModel) if model is null.
  • The SDK throws the exceptions above when you call UpdateAsync, before it returns a task. An API rejection surfaces when you await the task, as ContentstackErrorException.

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

Behavior

  • Sends the same PUT request as Update, on a task that you await.
  • Otherwise behaves like Update.

Example

Basic usage: rename a content type and keep its fields

using System;
using System.Collections.Generic;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

ContentModelling model = new ContentModelling
{
    Title = "Article",
    Uid = "blog_post",
    Schema = new List<Field>
    {
        new TextboxField { DisplayName = "Title", Uid = "title", DataType = "text", Mandatory = true, Unique = true },
        new TextboxField { DisplayName = "URL", Uid = "url", DataType = "text" }
    }
};

try
{
    ContentstackResponse response = await client.Stack("<API_KEY>").ContentType("blog_post").UpdateAsync(model);
    Console.WriteLine(response.OpenJsonObjectResponse()["content_type"]?["title"]);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

All parameters: add a field to the fetched schema, using a management token

using System;
using System.Text.Json;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;
using Contentstack.Management.Core.Queryable;

ContentstackClient client = new ContentstackClient();
Stack stack = client.Stack("<API_KEY>", "<MANAGEMENT_TOKEN>");

ParameterCollection collection = new ParameterCollection();
collection.Add("include_branch", true);

try
{
    ContentstackResponse fetched = await stack.ContentType("<CONTENT_TYPE_UID>").FetchAsync();
    ContentModelling model = fetched.OpenJsonObjectResponse()["content_type"]!.Deserialize<ContentModelling>(client.SerializerOptions)!;

    model.Schema!.Add(new NumberField { DisplayName = "Reading Time", Uid = "reading_time", DataType = "number", Min = 1 });

    ContentstackResponse response = await stack.ContentType("<CONTENT_TYPE_UID>").UpdateAsync(model, collection);
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}