ContentType

View as Markdown

ContentType

Warning Contentstack has deprecated the Dart Delivery SDK for new projects. Existing apps can keep using it. For new Dart or Flutter projects, call the Content Delivery API directly with an HTTP client.

A content type defines the fields of the entries you create from it. Use this class to

  • fetch the schema of one content type
  • open one entry, or all the entries, of a content type
  • start a query across every content type of the stack

stack.contentType() returns the object for each of these tasks and takes one optional argument:

NameTypeDescription
contentTypeIdString?UID of the content type. Omit it to query the content types of the stack.

Instance State

Which methods work depends on the UID you pass to stack.contentType().

  • Call stack.contentType('<CONTENT_TYPE_UID>') to work with one content type, for example to fetch its schema or open an entry.
  • Call stack.contentType() without a UID to list content types through query.

The Method Index below lists all three methods. query works on both, and does not read the UID.

On an instance without a UID, fetch throws Exception. The entry method still returns an Entry, but that entry has no content type in its path.

  • Its fetch requests a URL without the content type, which fails.
  • Its query throws TypeError on stack.contentType(). On stack.contentType(''), its query requests the path /content_types//entries.

Warning stack.contentType('') creates an instance without a UID. The SDK tests the UID for an empty string, so a UID variable that is unexpectedly empty takes the no-UID branch, and the error appears only on the request. Check the variable before you pass it.

Class-Level Notes

Environment and API version.

  • The content type reads the environment from the stack headers and the API version from the stack when you create it. A later setHeader call that changes the environment header does not change the environment query parameter of an existing content type.

Response shape.

  • The SDK has no model class for content types. Call fetch without type arguments. The result is the decoded JSON body as a Map, with the schema under content_type.

Method Index

Method NameReturnsDescription
fetchThe requested content type.Fetches the schema of one content type.
entryA new entry for the content type.Opens one entry, or all entries, of the content type.
queryA new query for the stack's content types.Starts a query across every content type of the stack.

Class-Level Snippet

This snippet fetches the schema of one content type, then reads the title of one of its entries.

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final contentType = stack.contentType('<CONTENT_TYPE_UID>');

  try {
    final schema = await contentType.fetch();
    if (schema is Map && schema.containsKey('error_code')) {
      // The API rejected the request
      print('Request failed: ${schema['error_code']} ${schema['error_message']}');
      return;
    }
    print('fields: ${schema['content_type']['schema'].length}');

    final response = await contentType.entry(entryUid: '<ENTRY_UID>').fetch();
    print(response['entry']['title']);
  } catch (e) {
    // Thrown for a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

Methods

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

entry

entry opens one entry of the content type by its UID, or all its entries when you omit the UID.

NameTypeDescription
entryUidString? (named)

UID of the entry. null opens all entries of the content type.

Default: null

Returns: Entry. A new entry for the content type.

Validation

  • There is no client-side validation. entry accepts any string and makes no request.
  • Without entryUid, the fetch method of the entry throws Exception, because it reads one entry. Call query on the entry to list entries instead.
  • On a content type created without a UID, the entry has no content type in its path, so the request that its fetch sends fails. See Instance State on the ContentType class page.

Behavior

  • Client-side only. entry builds an Entry object and makes no request.
  • entryUid is a named parameter. Write entry(entryUid: '<ENTRY_UID>').
  • The entry reads the environment from the stack when you create it.
  • See the Entry class page for the settings and the request.

Example

Basic usage: fetch one entry

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final entry = stack.contentType('<CONTENT_TYPE_UID>').entry(entryUid: '<ENTRY_UID>');

  try {
    final response = await entry.fetch();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request, for example because the UID does not exist
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print(response['entry']['title']);
    }
  } catch (e) {
    // Thrown for a missing UID, a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

No UID: list the first five entries

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()..limit(5);

  final response = await query.find();
  for (final entry in response['entries']) {
    print(entry['title']);
  }
}

fetch

fetch returns the schema of the content type, without its entries.

NameTypeDescription
queryParamsMap<String, dynamic>?

Extra query parameters. Every value must be a String.

Default: null

Returns: Future<T>. The requested content type.

Validation

  • Throws Exception if the content type has no UID, because fetch reads one content type. This happens on stack.contentType() and stack.contentType('').
  • Throws TypeError if queryParams is not a map of strings at run time, because fetch casts it to Map<String, String?>. See the Known issue under Behavior.
  • Errors from the request:
    • fetch throws only when the request does not complete: a network failure, a 30-second timeout or a response that is not JSON.
    • An API rejection, for example an unknown UID, comes back as the result with an error_code key. It does not throw.
    • Check the result for an error_code key even inside a try block.

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

Behavior

  • Known issue: A map literal written inside the call, such as fetch({'include_branch': 'true'}), throws TypeError, because Dart types it as Map<String, dynamic>. A non-string value such as true throws the same error. Write the map as <String, String>{...}.
  • One call sends one Get a single content type request, GET /<apiVersion>/content_types/{content_type_uid}, with the environment query parameter and each entry of queryParams.
  • fetch adds queryParams to the parameters of the content type object. A later fetch on the same object sends them again.
  • With include_branch set to 'true', the API adds the _branch key, which names the branch of the content type.
  • The result is the decoded JSON body as a Map, with the schema under content_type. The SDK has no model class for content types, so call fetch without type arguments.

Example

Basic usage: list the fields of a content type

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final contentType = stack.contentType('<CONTENT_TYPE_UID>');

  try {
    final response = await contentType.fetch();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request, for example because the UID does not exist
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      for (final field in response['content_type']['schema']) {
        print('${field['uid']}: ${field['data_type']}');
      }
    }
  } catch (e) {
    // Thrown for a missing UID, a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

All parameters: include the branch of the content type

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    branch: '<BRANCH>',
  );
  final contentType = stack.contentType('<CONTENT_TYPE_UID>');

  // Type the map as <String, String>, or fetch throws TypeError
  final response = await contentType.fetch(<String, String>{'include_branch': 'true'});
  print(response['content_type']['_branch']);
}

query

query starts a query across every content type of the stack.

This method takes no parameters.

Returns: ContentTypeQuery. A new query for the stack's content types.

Validation

  • There is no client-side validation. query cannot fail and makes no request.
  • Errors come from the find call that follows. An API rejection comes back as the result with an error_code key, not as an exception.

Behavior

  • Client-side only. query builds a ContentTypeQuery object and makes no request.
  • The query covers every content type of the stack. It does not read the UID of the content type you call it on, so stack.contentType() and stack.contentType('<CONTENT_TYPE_UID>') return the same query.
  • The query reads the environment from the stack when you create it.
  • See the ContentTypeQuery class page for the settings and the request.

Example

Basic usage: list the content types with a count

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final query = stack.contentType().query()..includeCount();

  try {
    final response = await query.find();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print('content types: ${response['count']}');
    }
  } catch (e) {
    // Thrown for a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}