Entry

View as Markdown

Entry

An entry is one piece of content that you create from a content type. Use this class to

  • fetch one published entry by its UID, in a locale, a branch or a variant
  • shape the response with field lists, references and include flags
  • start a query on the entries of a content type
  • decode an entry into EntryModel, or into a model of your own that adopts EntryDecodable

Entry sends one request, through fetch(_:). Every other method records a setting for that request or creates a query.

Instance State

You never create an Entry with an initializer, because its initializer is internal. Call entry(uid:) on a content type instead, in one of these two ways:

  • Call stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID") to work with one entry. Set any request options, then call fetch(_:).
  • Call stack.contentType(uid: "CONTENT_TYPE_UID").entry() to work with the entries of the content type. Call query() or query(_:), then find(_:) on the query.

The three calls below stop the app or narrow the result when you make them on the wrong kind of object:

  • fetch(_:) on an entry without a UID stops the app with a fatal error, because fetch(_:) puts the UID in the request path.
  • query() on an entry with a UID returns a query that matches only that entry.
  • entry(uid:) on a content type created without a UID stops the app with a fatal error. See ContentType.

Warning The SDK treats an empty string as a UID. entry(uid: "") creates an entry that passes the UID check, and fetch(_:) sends a request with an empty UID in the path.

Class-Level Notes

Settings stay on the entry.

  • The methods that Entry inherits from EntryQueryable, and addValue(_:forHTTPHeaderField:), write to the parameters and headers dictionaries of the entry.
  • Every later fetch(_:) on the same entry sends them again.
  • No method removes a setting. Remove the key from the public parameters or headers dictionary, or create a new entry.

An entry and its query do not share settings.

  • query() and query(_:) start a new query from the content type. The locale, field lists, includes, headers and variants of the entry do not carry over.
  • The query takes its cache policy from the content type, not from the entry.

Each entry has its own cache policy.

  • cachePolicy on an entry starts as .networkOnly. The entry does not read Stack.cachePolicy or the cache policy of its content type.
  • Set cachePolicy on each entry that needs another policy. The values are .networkOnly, .cacheOnly, .cacheElseNetwork, .networkElseCache and .cacheThenNetwork. The Stack class page describes each one.

You choose the model type.

  • fetch(_:) is generic. Specify the model in the completion handler or in the variable annotation, as Result<EntryModel, Error> or let entry: EntryModel. Without the annotation the code does not compile.
  • Use the SDK's EntryModel class, or a class of your own that adopts EntryDecodable. The EntryModel and EntryDecodable sections below cover both.

Capability Matrix

CapabilitySupportedNotes / Alternative
Fetch an earlier version of an entryNoThe Delivery API serves only the latest published version. See Get a single entry
Resolve every reference without naming the fieldsNo dedicated methodSet entry.parameters["include_all"] = "true" before fetch(_:). See Include All References
Copy the settings of an entry to its queryNoCall the same methods on the query
Take the cache policy from the stackNoSet cachePolicy on each entry

Class-Level Properties

PropertyTypeAccessDefaultDescription
headers[String: String]Read-write[:]Headers that fetch(_:) sends. addValue(_:forHTTPHeaderField:) and the variants methods write here.
cachePolicyCachePolicyRead-write.networkOnlyCaching strategy for fetch(_:). See the Stack class page for the values.
stackStackRead-writeThe stack of the content typeStack that sends the request.
parameters[String: Any]Read-writeThe content_type and uid of the entryRequest parameters. The EntryQueryable methods write here. The SDK moves content_type and uid into the request path and sends the other keys as query parameters.
queryParameter[String: Any]Read-write[:]Query conditions. fetch(_:) does not send it.

EntryModel

EntryModel is the model class the SDK provides for an entry. Specify it in fetch(_:) or find(_:) when you do not need a model of your own. It adopts EntryDecodable and ContentTypeIncludable. The table below lists its properties.

PropertyTypeAccessDefaultDescription
titleStringRead-writeNot applicabletitle of the entry. Decoding fails without it.
uidStringRead-writeNot applicableuid of the entry. Decoding fails without it.
localeStringRead-writeNot applicableLocale of the returned entry. Decoding fails without it.
createdAtDate?Read-writenilcreated_at of the entry. nil when missing or unreadable.
updatedAtDate?Read-writenilupdated_at of the entry. nil when missing or unreadable.
createdByString?Read-writenilUID of the user who created the entry.
updatedByString?Read-writenilUID of the user who last updated the entry.
fields[String: Any]?Read-writeEvery key of the entryAll keys of the entry, including custom fields.
contentTypeContentTypeModel?Read-writenilContent type of the entry, after fetch(_:) with include(params: .contentType).

How fields stores values.

  • fields contains every key of the entry JSON, including title, uid and the system keys.
  • A plain value becomes a Bool, String, Int or Double. A JSON object becomes a dictionary, and a JSON array becomes an array.
  • The SDK tries three model types on each nested object, in the order below, and keeps the first that decodes:
    • AssetModel, when the object has the keys of an asset. A file field becomes an AssetModel.
    • EntryModel, when the object has uid, title and locale. A resolved reference becomes an EntryModel.
    • ContentTypeModel, when the object has uid and title.
  • A date in fields stays the string from the response. Use createdAt and updatedAt for Date values.

FieldKeys. EntryModel.FieldKeys lists the keys that the query methods where(queryableCodingKey:_:), orderByAscending(propertyName:) and orderByDecending(propertyName:) accept.

CaseRaw valueMeaning
titletitleTitle of the entry
uiduidUID of the entry
localelocaleLocale of the entry
createdAtcreated_atCreation date
updatedAtupdated_atLast update date
createdBycreated_byUID of the creator
updatedByupdated_byUID of the last updater

toJSON(). toJSON() -> [String: Any] returns fields as a dictionary that JSONSerialization accepts.

  • toJSON() converts each nested EntryModel, AssetModel and ContentTypeModel in fields back to a dictionary, at every depth.
  • It returns an empty dictionary when fields is nil.
  • It does not add the contentType property.

The example below converts an entry with a resolved reference to JSON text.

import ContentstackSwift
import Foundation

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
    .includeReference(with: ["author"])
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        guard case .success(let entry) = result else { return }
        // JSONSerialization rejects the nested EntryModel objects in fields, so convert first.
        let json = entry.toJSON()
        if let data = try? JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted]),
           let text = String(data: data, encoding: .utf8) {
            print(text)
        }
    }

EntryDecodable

EntryDecodable is the protocol for an entry model of your own. Adopt it to decode entries into typed properties instead of the fields dictionary. An EntryDecodable model also enables typed field keys through query(_:).

The protocol combines four others. Your model must be a class, because SystemFields is class-bound, and must provide the members below:

  • uid: String, title: String, createdAt: Date? and updatedAt: Date? from SystemFields.
  • locale: String, createdBy: String? and updatedBy: String? from EntryFields. See SystemFields.
  • A FieldKeys type that adopts CodingKey, from FieldKeysQueryable. See BaseQuery.
  • init(from:), from Decodable. Write it yourself when FieldKeys maps names such as created_at, because Swift synthesizes Decodable only from a type named CodingKeys.

The SDK supplies the endpoint requirement of EndpointAccessible for every EntryDecodable type, so fetch(_:) and find(_:) request entries.

ContentTypeIncludable. Adopt ContentTypeIncludable as well, with var contentType: ContentTypeModel?, to receive the content type after fetch(_:) with include(params: .contentType). EntryModel adopts it.

The model below maps a Product content type with a price field:

import ContentstackSwift
import Foundation

class Product: EntryDecodable, ContentTypeIncludable {
    enum FieldKeys: String, CodingKey {
        case title, uid, locale, price
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case createdBy = "created_by"
        case updatedBy = "updated_by"
    }

    var title: String
    var uid: String
    var locale: String
    var createdAt: Date?
    var updatedAt: Date?
    var createdBy: String?
    var updatedBy: String?
    var price: Double?
    var contentType: ContentTypeModel?

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: FieldKeys.self)
        title = try container.decode(String.self, forKey: .title)
        uid = try container.decode(String.self, forKey: .uid)
        locale = try container.decode(String.self, forKey: .locale)
        createdAt = try? container.decode(Date.self, forKey: .createdAt)
        updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
        createdBy = try? container.decode(String.self, forKey: .createdBy)
        updatedBy = try? container.decode(String.self, forKey: .updatedBy)
        price = try? container.decode(Double.self, forKey: .price)
    }
}

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<Product, Error>, response: ResponseType) in
        guard case .success(let product) = result else { return }
        print(product.title, product.price ?? 0)
    }

Method Index

Fetch the entry. Available on an entry from entry(uid:) with a UID.

Method NameReturnsDescription
fetch(_:)Nothing. The completion handler receives the result.Retrieves one published entry by its UID.

Set request headers. Available on any entry. Call it before fetch(_:).

Method NameReturnsDescription
addValue(_:forHTTPHeaderField:)The same entry, for chaining.Adds one header to the fetch request.

Start a query. Available on any entry. An entry with a UID gives a query that matches only that entry.

Method NameReturnsDescription
query()A new query for the entries of this content type.Creates a query that decodes into any model.
query(_:)A new typed query for the entries of this content type.Creates a query with the field keys of your model.

Shape the response. Available on any entry, from the EntryQueryable protocol, and documented there: locale(_:), only(fields:), except(fields:), include(params:), includeReference(with:), includeReferenceField(with:only:), includeReferenceField(with:except:), variants(uid:), variants(uids:), variants(uid:branch:) and variants(uids:branch:).

Class-Level Snippet

The snippet below fetches a French entry with an English fallback and its resolved author, then reads a custom field and the author.

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
    .locale("fr-fr")
    .include(params: .fallback)
    .includeReference(with: ["author"])
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        switch result {
        case .success(let entry):
            print("\(entry.title) (\(entry.locale))")
            print("Summary: \(entry.fields?["summary"] ?? "")")
            let authors = (entry.fields?["author"] as? [Any])?.compactMap { $0 as? EntryModel } ?? []
            for author in authors {
                print("Author: \(author.title)")
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Methods

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

addValue(_:forHTTPHeaderField:)

addValue(_:forHTTPHeaderField:) adds one header to the fetch request of this entry.

NameTypeDescription
value (required)String

Value of the header.

Default: Not applicable
forHTTPHeaderField (required)String

Name of the header.

Default: Not applicable

Returns: Entry. The same entry, for chaining.

Validation

  • There is no client-side validation. addValue(_:forHTTPHeaderField:) accepts any name and value, including empty strings.
  • A second api_key or access_token header breaks authentication. The SDK sets both on every request, and URLRequest appends your value to theirs with a comma, so the header no longer contains a valid credential. Do not pass either name.
  • 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:) writes the value to headers under the name and makes no request.
  • A second call with the same name replaces the value. The variants methods write to the same dictionary, under x-cs-variant-uid and branch.
  • fetch(_:) sends every header in headers. A header here takes precedence over a header of the same name that the stack sets for all requests, such as branch.
  • The header stays on this entry only. The query from query() does not receive it. A query has its own addValue(_:forHTTPHeaderField:). The BaseQuery class page describes it.
  • To remove a header, call headers.removeValue(forKey:) on the entry.

Example

Fetch an entry from another branch

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
    // Overrides any branch set on the stack, for this entry only.
    .addValue("BRANCH_UID", forHTTPHeaderField: "branch")
    .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)
            }
        }
    }

fetch(_:)

fetch(_:) retrieves one published entry by its UID and decodes it into the model type you name.

The async form is fetch() async throws -> ResourceType and takes no parameters. The completion-handler form takes the parameter below.

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

Receives the decoded entry or the error, and the source.

Default: Not applicable

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

The async form returns the requested entry and throws on failure.

Validation

  • The SDK stops the app with a fatal error if the entry has no UID, because fetch(_:) reads one entry and puts its UID in the request path. Create the entry with entry(uid:).
  • There is no other client-side validation. An empty string counts as a UID.
  • 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. See APIError.
  • When a successful response holds no entry, the result is .failure with SDKError.invalidUID(string:).
  • When the entry does not decode into the model type, the result is .failure with the DecodingError from JSONDecoder. EntryModel fails only when title, uid or locale is missing.

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

Behavior

  • One call sends one Get a single entry request, GET /v3/content_types/{content_type_uid}/entries/{entry_uid}.
  • fetch(_:) adds the stack's environment as the environment query parameter, every key of parameters as a query parameter, and every key of headers as a header.
  • With an x-cs-variant-uid header from a variants method, the request becomes Get single entry variant.
  • fetch(_:) decodes the entry object of the response into ResourceType. Name EntryModel or a class of your own that adopts EntryDecodable. See Entry.
  • When the request includes the content type, fetch(_:) sets the contentType property of a model that adopts ContentTypeIncludable, such as EntryModel.
  • fetch(_:) does not send queryParameter.
  • The cachePolicy of the entry decides whether fetch(_:) reads the cache, the network or both. The default, .networkOnly, always sends a request.
    • The second argument of the completion handler, ResponseType, is .cache or .network and tells you where the result came from.
    • With .cacheThenNetwork, the completion handler runs twice, first with the cached entry and then with the network entry.
    • The async form serves .cacheThenNetwork as .cacheElseNetwork, because one await returns one value. The SDK logs the substitution.
  • The async form needs iOS 13, macOS 10.15, tvOS 13 or watchOS 6.

Example

Fetch an 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)
            }
        }
    }

Use async/await

import ContentstackSwift

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

Show cached content first, then fresh content

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let entry = stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
entry.cachePolicy = .cacheThenNetwork
entry.fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
    // Runs once for the cache and once for the network.
    guard case .success(let model) = result else { return }
    print(response == .cache ? "Cached:" : "Network:", model.title)
}

Decode into a model of your own

import ContentstackSwift
import Foundation

class Product: EntryDecodable {
    enum FieldKeys: String, CodingKey {
        case title, uid, locale, price
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case createdBy = "created_by"
        case updatedBy = "updated_by"
    }

    var title: String
    var uid: String
    var locale: String
    var createdAt: Date?
    var updatedAt: Date?
    var createdBy: String?
    var updatedBy: String?
    var price: Double?

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: FieldKeys.self)
        title = try container.decode(String.self, forKey: .title)
        uid = try container.decode(String.self, forKey: .uid)
        locale = try container.decode(String.self, forKey: .locale)
        createdAt = try? container.decode(Date.self, forKey: .createdAt)
        updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
        createdBy = try? container.decode(String.self, forKey: .createdBy)
        updatedBy = try? container.decode(String.self, forKey: .updatedBy)
        price = try? container.decode(Double.self, forKey: .price)
    }
}

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<Product, Error>, response: ResponseType) in
        guard case .success(let product) = result else { return }
        print(product.title, product.price ?? 0)
    }

query()

query() creates a query on the entries of the entry's content type.

This method takes no parameters.

Returns: Query. A new query for the entries of this content type.

Validation

  • There is no client-side validation that a valid entry can fail. query() stops the app with a fatal error if the content type has no UID, but entry(uid:) already stops the app in that case, before an entry exists.
  • Errors that do occur come from the find(_:) call that follows, 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 find(_:) on the query to send a Get all entries request.
  • On an entry with a UID, query() adds the condition uid equals that UID, so find(_:) returns only that entry.
  • The query starts empty. The locale, field lists, includes, headers and variants of the entry do not carry over. Call those methods on the query.
  • The query takes its cachePolicy from the content type, which starts as .networkOnly, not from the entry.
  • The Query class page lists the filter, sort and paging methods of the query. It also has the methods of EntryQueryable.
  • Name the model in the find(_:) completion handler, such as Result<ContentstackResponse<EntryModel>, Error>. For typed field keys, use the query(_:) method instead.

Example

Find the entries of a content type

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .where(queryableCodingKey: .title, .equals("Spring sale"))
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let entries):
            for entry in entries.items {
                print(entry.uid, entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Query one entry by its UID

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
// The query matches only ENTRY_UID. Set the locale on the query, not on the entry.
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID").query()
    .locale("fr-fr")
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        guard case .success(let entries) = result else { return }
        print(entries.items.first?.title ?? "No entry in this locale")
    }

query(_:)

query(_:) creates a typed query on the entries of the entry's content type, with filter and sort keys from your model.

NameTypeDescription
entry (required)EntryType.Type

Your model type, such as Product.self.

Default: Not applicable

Returns: QueryOn<EntryType>. A new typed query for the entries of this content type.

Validation

  • EntryType must adopt EntryDecodable. Any other type does not compile.
  • There is no client-side validation that a valid entry can fail. query(_:) stops the app with a fatal error if the content type has no UID, but entry(uid:) already stops the app in that case, before an entry exists.
  • Errors that do occur come from the find(_:) call that follows, 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 find(_:) on the query to send a Get all entries request.
  • The returned QueryOn accepts the cases of EntryType.FieldKeys in its where and sort methods, so the compiler catches a misspelled field key.
  • query(_:) does not set the model type of find(_:). Name the model in the completion handler, such as Result<ContentstackResponse<Product>, Error>.
  • On an entry with a UID, query(_:) adds the condition uid equals that UID, so find(_:) returns only that entry.
  • The query starts empty, as with the query() method. The settings of the entry do not carry over, and the query takes its cachePolicy from the content type.

Example

Find products above a price

import ContentstackSwift
import Foundation

class Product: EntryDecodable {
    enum FieldKeys: String, CodingKey {
        case title, uid, locale, price
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case createdBy = "created_by"
        case updatedBy = "updated_by"
    }

    var title: String
    var uid: String
    var locale: String
    var createdAt: Date?
    var updatedAt: Date?
    var createdBy: String?
    var updatedBy: String?
    var price: Double?

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: FieldKeys.self)
        title = try container.decode(String.self, forKey: .title)
        uid = try container.decode(String.self, forKey: .uid)
        locale = try container.decode(String.self, forKey: .locale)
        createdAt = try? container.decode(Date.self, forKey: .createdAt)
        updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
        createdBy = try? container.decode(String.self, forKey: .createdBy)
        updatedBy = try? container.decode(String.self, forKey: .updatedBy)
        price = try? container.decode(Double.self, forKey: .price)
    }
}

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query(Product.self)
    .where(queryableCodingKey: .price, .isGreaterThan(100))
    .orderByAscending(propertyName: .price)
    .find { (result: Result<ContentstackResponse<Product>, Error>, response: ResponseType) in
        switch result {
        case .success(let products):
            for product in products.items {
                print(product.title, product.price ?? 0)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }