ContentType

View as Markdown

ContentType

A content type defines the structure, or schema, of the entries of one kind of page or section. Use the ContentType class to

  • read one content type and its schema by UID
  • add the schema of the Global fields it contains to the response
  • start an Entry to read or query the entries of the content type
  • start a ContentTypeQuery that lists or filters content types

fetch(_:) decodes the content type into a ContentTypeModel. The ContentTypeModel and ContentTypeDecodable sections below describe the model and the protocol.

Instance State

The contentType(uid:) method of Stack is the only way to get a ContentType. Which methods work depends on the uid argument:

  • Call stack.contentType(uid: "CONTENT_TYPE_UID") to read the content type with fetch(_:), or to reach its entries with entry(uid:).
  • Call stack.contentType() without a UID to list content types. Chain query() to get a ContentTypeQuery, then call find on it.

The SDK stops the app with a fatal error if you call fetch(_:) or entry(uid:) on a content type without a UID. Both need the UID to build the request path, and the compiler does not catch the mistake.

Warning The UID check tests only for nil. stack.contentType(uid: "") passes it, and the request path then has an empty content type UID. Nothing fails at the point of the mistake. Check that the UID variable is non-empty before you call contentType(uid:).

Class-Level Notes

Settings stay on the object.

  • includeGlobalFields() stores one query parameter, and addValue(_:forHTTPHeaderField:) stores one header, on the content type.
  • fetch(_:) sends them with the environment of the stack, on every call.
  • No method removes a stored value. Call stack.contentType(uid:) again to send a request without it.

What entry(uid:) and query() copy.

  • entry(uid:) and query() copy only the content type UID. The Entry and the ContentTypeQuery they return start with no parameters and no headers of their own.
  • An Entry starts with cachePolicy set to .networkOnly. A ContentTypeQuery takes its cachePolicy from the Stack.

Caching.

  • cachePolicy is .networkOnly on every new content type, whatever the Stack uses. Set it on the content type before you call fetch(_:).

Capability Matrix

CapabilitySupportedNotes / Alternative
List or filter content typesNot on ContentTypeCall query() and then find on the ContentTypeQuery
Add the _branch key to the responseNoUse a ContentTypeQuery and send include_branch through the addURIParam(with:value:) method
Decode the schema into typed Swift fieldsNoschema is an array of dictionaries. Read the keys you need from it

Class-Level Properties

PropertyTypeAccessDefaultDescription
cachePolicyCachePolicyRead-write.networkOnlyWhere fetch(_:) reads the content type from. The Stack page lists the values.

ContentTypeModel

ContentTypeModel is the SDK's model for one content type. Annotate the result of fetch(_:) as ContentTypeModel, or the result of find as ContentstackResponse<ContentTypeModel>. It is a final class that adopts SystemFields, Decodable and EndpointAccessible.

The table below lists its properties. Every property is public var.

PropertyTypeAccessDefaultDescription
uidStringRead-writeNot applicableUID of the content type, from uid. Decoding fails without it.
titleStringRead-writeNot applicableTitle of the content type, from title. Decoding fails without it.
descriptionString?Read-writenilDescription, from description.
createdAtDate?Read-writenilCreation time, from created_at. nil when the key is missing or the date does not parse.
updatedAtDate?Read-writenilLast update time, from updated_at. nil when the key is missing or the date does not parse.
schema[[String: Any]]Read-write[]The fields of the content type, one dictionary per field, from schema.

toJSON(). toJSON() returns a [String: Any] dictionary that JSONSerialization accepts. The dictionary contains uid, title and schema, and contains description, created_at and updated_at only when they have a value. It writes each date as an ISO 8601 string with fractional seconds. Other keys of the response, such as options, are not in it.

FieldKeys. ContentTypeModel.FieldKeys maps each property to its JSON key.

CaseRaw value
titletitle
uiduid
descriptiondescription
createdAtcreated_at
updatedAtupdated_at
schemaschema

QueryableCodingKey. ContentTypeModel.QueryableCodingKey lists the keys you can pass to the where(queryableCodingKey:_:) method of ContentTypeQuery.

CaseRaw value
uiduid
titletitle
descriptiondescription
createdAtcreated_at
updatedAtupdated_at

ContentTypeDecodable

ContentTypeDecodable is a protocol for your own content type model. A conforming type provides the following members:

  • the properties of SystemFields: uid, title, createdAt and updatedAt. The SystemFields page lists their types
  • schema, of type [String: Any]?
  • init(from:), from Decodable

fetch(_:) and find do not compile with a type that has no endpoint, and ContentTypeDecodable supplies none. A conforming type must also adopt EndpointAccessible and return .contenttype from endpoint. ContentTypeModel does not adopt ContentTypeDecodable.

Method Index

Method NameReturnsDescription
fetch(_:)Nothing. The completion handler receives the result.Reads one content type and its schema by UID.
includeGlobalFields()The same content type, for chaining.Adds the schema of the Global fields to the response.
addValue(_:forHTTPHeaderField:)The same content type, for chaining.Adds a header to the fetch request.
entry(uid:)A new entry object for the given UID.Starts an Entry to read or query entries of this content type.
query()A new content type query, limited to this content type when it has a UID.Starts a ContentTypeQuery to list or filter content types.

Class-Level Snippet

The snippet below reads one content type with the schema of its Global fields, then prints the UID and data type of each field.

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID")
    .includeGlobalFields()
    .fetch { (result: Result<ContentTypeModel, Error>, response: ResponseType) in
        switch result {
        case .success(let contentType):
            print(contentType.title)
            for field in contentType.schema {
                print(field["uid"] ?? "", field["data_type"] ?? "")
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Methods

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

addValue(_:forHTTPHeaderField:)

addValue(_:forHTTPHeaderField:) adds one HTTP header that fetch(_:) sends with the request for the content type.

NameTypeDescription
value (required)String

Header value. Sent as it is.

Default: Not applicable
field (required)String

Header name, such as branch. Names the header to send.

Default: Not applicable

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

Validation

  • There is no client-side validation. Empty strings reach the request as they are.
  • Errors that do occur come from the fetch(_:) call that follows, not from addValue(_:forHTTPHeaderField:).

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

Behavior

  • Client-side only. addValue(_:forHTTPHeaderField:) stores the header on the content type and makes no request. The fetch(_:) call that follows sends it, on top of the headers of the Stack.
  • A second call with the same field replaces the stored value.
  • A header you add here takes precedence over a header of the same name that the Stack sends, such as branch. The example below reads one content type from another branch this way.
  • An added api_key or access_token value joins the value the SDK already sets on each request instead of replacing it. Do not use addValue(_:forHTTPHeaderField:) for those two headers.
  • Only fetch(_:) on this content type sends the header. entry(uid:) and query() do not carry it over.

Example

Basic usage: read a content type from a specific branch

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID")
    .addValue("BRANCH_UID", forHTTPHeaderField: "branch")
    .fetch { (result: Result<ContentTypeModel, Error>, response: ResponseType) in
        switch result {
        case .success(let contentType):
            print(contentType.title)
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

entry(uid:)

entry(uid:) creates an Entry for this content type, for one entry or for all of its entries.

NameTypeDescription
uidString?

UID of the entry. Omit it to query all entries.

Default: nil

Returns: Entry. A new entry object for the given UID.

Validation

  • The SDK stops the app with a fatal error if the content type has no UID, because every entry request path contains the content type UID. stack.contentType() without a UID creates such a content type.
  • entry(uid:) does not check the entry UID. Errors that do occur come from the fetch(_:) or find(_:) call that follows.

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

Behavior

  • Client-side only. entry(uid:) makes no request.
  • With a UID, the Entry reads that entry. Call the fetch(_:) method of Entry.
  • Without a UID, the Entry works on all entries of the content type. Call its query() method and then find on the query.
  • The Entry carries the content type UID and the entry UID only. It does not carry the headers, the parameters or the cachePolicy of the content type, and starts with cachePolicy set to .networkOnly.

Example

Basic usage: read one entry

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID")
    .entry(uid: "ENTRY_UID")
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        switch result {
        case .success(let entry):
            print(entry.title)
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Without a UID: list the entries of the content type

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID")
    .entry()
    .query()
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        guard case .success(let entries) = result else { return }
        print(entries.items.map { $0.title })
    }

fetch(_:)

fetch(_:) reads one content type and its schema by UID and decodes it into the model type you name.

The async form, fetch() async throws -> ResourceType, does the same and returns the content type directly. It needs iOS 13, macOS 10.15, tvOS 13 or watchOS 6.

NameTypeDescription
completion (required)@escaping (Result<ResourceType, Error>, ResponseType) -> Void

Receives the decoded content type or the error, and the source of the result.

Default: Not applicable

ResourceType is the model you name in the closure annotation, usually ContentTypeModel. It must adopt EndpointAccessible and Decodable.

Returns: Void. Nothing. The completion handler receives the result.

The async form returns the requested content type and throws on failure.

Validation

  • There is no client-side validation.
  • The SDK stops the app with a fatal error if the content type has no UID, because fetch(_:) needs the UID to read one content type. stack.contentType() without a UID creates such a content type.
  • When the API rejects the request, the result is .failure with an APIError (the async form throws it). Read errorCode, errorMessage and statusCode from it.
  • When the response holds no content type, the result is .failure with SDKError.invalidUID(string:), which carries the UID you passed.

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

Behavior

  • fetch(_:) sends one GET request to /v3/content_types/{content_type_uid}, the Get a single content type request.
  • The request carries the environment of the Stack, the include_global_field_schema parameter when you called includeGlobalFields(), and every header that addValue(_:forHTTPHeaderField:) stored.
  • The response holds the schema of the content type, not its entries. Use entry(uid:) to read entries.
  • The cachePolicy of the content type selects whether fetch(_:) reads the network, the cache, or both. The async form serves .cacheThenNetwork as .cacheElseNetwork.

Example

Basic usage: read a content type by UID

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID")
    .fetch { (result: Result<ContentTypeModel, Error>, response: ResponseType) in
        switch result {
        case .success(let contentType):
            print(contentType.title, contentType.schema.count)
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Use async/await

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let contentType: ContentTypeModel = try await stack.contentType(uid: "CONTENT_TYPE_UID").fetch()
    print(contentType.title, contentType.schema.count)
} catch {
    print(error)
}

includeGlobalFields()

includeGlobalFields() asks the API to return the schema of each Global field inside the content type schema.

This method takes no parameters.

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

Validation

  • There is no client-side validation.
  • Errors that do occur come from the fetch(_:) call that follows, not from includeGlobalFields().

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

Behavior

  • Client-side only. includeGlobalFields() stores include_global_field_schema=true on the content type and makes no request. The fetch(_:) call that follows sends it.
  • The API then returns the schema of each Global field along with the content type schema. See the tip on include_global_field_schema in Get all content types.
  • The SDK puts the result in the schema property of ContentTypeModel, as dictionaries.
  • query() does not carry the parameter over. On a ContentTypeQuery, pass .globalFields to its include(params:) method instead.
  • Calling includeGlobalFields() twice changes nothing, because both calls write the same value under the same key.

Example

Basic usage: read a content type with its Global field schemas

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID")
    .includeGlobalFields()
    .fetch { (result: Result<ContentTypeModel, Error>, response: ResponseType) in
        switch result {
        case .success(let contentType):
            let globalFields = contentType.schema.filter { ($0["data_type"] as? String) == "global_field" }
            for field in globalFields {
                print(field["uid"] ?? "", field["schema"] ?? "")
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

query()

query() creates a ContentTypeQuery that lists or filters the content types of the stack.

This method takes no parameters.

Returns: ContentTypeQuery. A new content type query, limited to this content type when it has a UID.

Validation

  • There is no client-side validation. query() works on a content type with or without a UID.
  • Errors that do occur come from the find call on the query, not from query().

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

Behavior

  • Client-side only. query() makes no request. Call the find(_:) method on the query to send Get all content types.
  • When the content type has a UID, query() adds a uid equals condition, so find returns at most that content type.
  • The query does not carry over the parameters, headers or cache policy of the content type. It starts empty and takes its cachePolicy from the Stack.
  • To list entries instead of content types, use entry(uid:).

Example

Basic usage: list content types with a count

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType().query()
    .include(params: .count)
    .find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentTypes):
            print("\(contentTypes.count ?? 0) content types")
            for contentType in contentTypes.items {
                print(contentType.uid, contentType.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }