Taxonomy
Taxonomy
A taxonomy arranges the content of a stack into a hierarchy of terms that entries carry. Use the Taxonomy class to start a Query that returns the entries tagged with a term, from every content type.
The query decodes each entry into a TaxonomyModel. The TaxonomyModel section below describes it. TaxonomyModel describes an entry, not a taxonomy.
Instance State
The taxonomy(uid:) method of Stack is the only way to get a Taxonomy. It does not read its uid argument, so every instance is the same and reaches the same methods.
- Call stack.taxonomy() and then query() to filter entries by taxonomy term.
- stack.taxonomy(uid: "TAXONOMY_UID") behaves the same as stack.taxonomy(). The UID reaches no request.
Class-Level Notes
Filter entries by taxonomy. The Taxonomy class has no filter methods of its own. The filter methods are on the Query that query() returns. Build the request in three steps:
- Call stack.taxonomy().query().
- Add a condition with the where(valueAtKey:_:) method of Query. Pass the path taxonomies.<TAXONOMY_UID> and an operation such as .equals("TERM_UID"), .includes([...]), .exists(true), .eqBelow, .below, .eqAbove or .above. Combine several conditions with the operator(_:) method and .and or .or.
- Call find(_:) and annotate the result as ContentstackResponse<TaxonomyModel>. An EntryModel annotation stops the app, as the Known issue below explains.
find(_:) then sends Get all entries with defined taxonomies (GET /v3/taxonomies/entries). The Taxonomy section of the Queries reference describes each operator. The Query page maps each Query.Operation case to its operator.
IMPORTANT: Annotate the result of a taxonomy query as ContentstackResponse<TaxonomyModel>, never EntryModel.
Known issue find(_:) on a taxonomy query stops the app when you annotate the result as EntryModel, because the query holds no content type UID and EntryModel reads from the entries endpoint of a content type. Use TaxonomyModel.
Hierarchy depth.
- .eqBelow, .below, .eqAbove and .above take only the term UID and send no levels key, so the API applies its default depth of 10 levels.
- To set levels, pass the whole condition to the addQuery(with:value:) method, as the Class-Level Snippet below does.
What query() passes to the query.
- query() passes the cachePolicy of the taxonomy to the query, but not its headers or parameters. Add headers to the query with the addValue(_:forHTTPHeaderField:) method of BaseQuery.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| List the taxonomies of a stack | No | The SDK has no request for Get all taxonomies |
| Read one taxonomy or its terms | No | fetch(_:) does not read a taxonomy. See the Known issue on the fetch(_:) page |
| Filter entries by taxonomy term | Yes | Use query(), as Class-Level Notes describes |
| Set levels on a hierarchy operator | No dedicated option | Pass the condition to addQuery(with:value:) |
Class-Level Properties
| Property | Type | Access | Default | Description |
|---|---|---|---|---|
| stack | Stack | Read-write | The stack that created the taxonomy | Stack that sends the request. |
| cachePolicy | CachePolicy | Read-write | .networkOnly | Where fetch(_:) reads the result from. query() passes it to the new query. The Stack page lists the values. |
| headers | [String: String] | Read-write | [:] | Headers that addValue(_:forHTTPHeaderField:) stores. Only the async form of fetch(_:) sends them. |
| parameters | [String: Any] | Read-write | [:] | Query parameters. Only the async form of fetch(_:) sends them. |
| queryParameter | [String: Any] | Read-write | [:] | No Taxonomy method reads or sends it. |
TaxonomyModel
TaxonomyModel is the SDK's model for one entry returned by a taxonomy query. It is a public class that adopts EntryDecodable and reads from the taxonomies endpoint.
The table below lists its properties. Every property is public var.
| Property | Type | Access | Default | Description |
|---|---|---|---|---|
| uid | String | Read-write | Not applicable | UID of the entry, from uid. Decoding fails without it. |
| title | String | Read-write | Not applicable | Title of the entry, from title. Decoding fails without it. |
| locale | String | Read-write | Not applicable | Locale of the entry, from locale. Decoding fails without it. |
| createdAt | Date? | Read-write | nil | Creation time, from created_at. |
| updatedAt | Date? | Read-write | nil | Last update time, from updated_at. |
| createdBy | String? | Read-write | nil | UID of the user who created the entry, from created_by. |
| updatedBy | String? | Read-write | nil | UID of the user who last updated the entry, from updated_by. |
| fields | [String: Any]? | Read-write | Every key of the entry | Every key and value of the entry, including taxonomies, _content_type_uid and your custom fields. |
| contentType | ContentTypeModel? | Read-write | nil | Always nil. The SDK never sets it. |
FieldKeys. TaxonomyModel.FieldKeys maps each typed property to its JSON key.
| Case | Raw value |
|---|---|
| title | title |
| uid | uid |
| locale | locale |
| createdAt | created_at |
| updatedAt | updated_at |
| createdBy | created_by |
| updatedBy | updated_by |
| fields | fields |
Method Index
| Method Name | Returns | Description |
|---|---|---|
| query() | A new query for entries filtered by taxonomy. | Starts a Query that filters entries by taxonomy term. |
| addValue(_:forHTTPHeaderField:) | The same taxonomy, for chaining. | Stores a header for the async form of fetch(_:). |
| fetch(_:) | Nothing. The completion handler receives the result. | Returns the first entry of the taxonomies entries endpoint. |
Class-Level Snippet
The snippet below reads the entries tagged with the term blue or any term up to two levels below it in the color taxonomy, from every content type.
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.taxonomy().query()
.addQuery(with: "taxonomies.color", value: ["$eq_below": "blue", "levels": 2])
.find { (result: Result<ContentstackResponse<TaxonomyModel>, Error>, response: ResponseType) in
switch result {
case .success(let entries):
for entry in entries.items {
print(entry.uid, entry.title, entry.fields?["_content_type_uid"] ?? "")
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Methods
Each method of the Taxonomy class has its own section below, with its parameters, validation rules, behavior and examples.
addValue(_:forHTTPHeaderField:)
addValue(_:forHTTPHeaderField:) stores one HTTP header on the taxonomy for the async form of fetch(_:).
| Name | Type | Description |
|---|---|---|
| value (required) | String | Header value. Sent as it is. |
| field (required) | String | Header name, such as branch. Names the header to send. |
Returns: Taxonomy. The same taxonomy, 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:) writes the header to the headers property and makes no request. A second call with the same field replaces the value.
- Only the async form of fetch(_:) sends the stored headers. The completion-handler form sends none of them.
- query() does not carry the headers over. To send a header with a taxonomy query, call the addValue(_:forHTTPHeaderField:) method of BaseQuery on the query instead, as the example below does.
Example
Basic usage: send a branch header with a taxonomy query
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.taxonomy().query()
.addValue("BRANCH_UID", forHTTPHeaderField: "branch")
.where(valueAtKey: "taxonomies.color", .equals("red"))
.find { (result: Result<ContentstackResponse<TaxonomyModel>, Error>, response: ResponseType) in
switch result {
case .success(let entries):
print(entries.items.map { $0.title })
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Header on the taxonomy: reaches the async fetch only
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
let entry: TaxonomyModel = try await stack.taxonomy()
.addValue("BRANCH_UID", forHTTPHeaderField: "branch")
.fetch()
print(entry.title)
} catch {
print(error)
}fetch(_:)
fetch(_:) requests the taxonomies entries endpoint without a condition and returns the first entry of the response.
The async form, fetch() async throws -> ResourceType, does the same and returns the entry directly. It needs iOS 13, macOS 10.15, tvOS 13 or watchOS 6.
| Name | Type | Description |
|---|---|---|
| completion (required) | @escaping (Result<ResourceType, Error>, ResponseType) -> Void | Receives the first entry or the error, and the source of the result. |
ResourceType is the model you name in the closure annotation, usually TaxonomyModel. It must adopt EndpointAccessible and Decodable.
Returns: Void. Nothing. The completion handler receives the result.
The async form returns the first entry and throws on failure.
Known issue fetch(_:) does not read a taxonomy, even when you passed a UID to stack.taxonomy(uid:). It sends Get all entries with defined taxonomies with no query and returns only the first entry. To read entries by taxonomy term, use query() and find(_:).
Validation
- There is no client-side validation.
- 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 entry, the result is .failure with SDKError.invalidURL(string:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- fetch(_:) sends one GET request to /v3/taxonomies/entries, the Get all entries with defined taxonomies request, with the environment of the Stack.
- The completion-handler form sends no other parameter and no header that you stored on the taxonomy.
- The async form also sends the parameters and the headers properties of the taxonomy.
- Neither form sends a taxonomy UID or the queryParameter property.
- The cachePolicy of the taxonomy selects whether fetch(_:) reads the network, the cache, or both.
Example
Basic usage: read the first entry that carries a taxonomy
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.taxonomy()
.fetch { (result: Result<TaxonomyModel, Error>, response: ResponseType) in
switch result {
case .success(let entry):
print(entry.uid, entry.title, entry.locale)
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: TaxonomyModel = try await stack.taxonomy().fetch()
print(entry.uid, entry.title)
} catch {
print(error)
}query()
query() creates a Query that returns the entries of every content type that carry a given taxonomy term.
This method takes no parameters.
Returns: Query. A new query for entries filtered by taxonomy.
Validation
- There is no client-side validation.
- Errors that do occur come from the find(_:) call on the query, not from query().
- IMPORTANT: Annotate the result of find(_:) as ContentstackResponse<TaxonomyModel>. The query holds no content type UID, so the SDK stops the app if you annotate it as EntryModel.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. query() makes no request.
- The new query holds no content type, no conditions and no headers. It takes the cachePolicy of the taxonomy.
- Add a condition on taxonomies.<TAXONOMY_UID> with the where(valueAtKey:_:) method, or combine several with the operator(_:) method.
- find(_:) with TaxonomyModel sends Get all entries with defined taxonomies (GET /v3/taxonomies/entries) with the conditions as the JSON query parameter.
- Each call returns a new query.
Example
Basic usage: read the entries tagged with one term
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.taxonomy().query()
.where(valueAtKey: "taxonomies.color", .equals("red"))
.find { (result: Result<ContentstackResponse<TaxonomyModel>, 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)
}
}
}Combine conditions: entries tagged red in color or small in size
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let taxonomy = stack.taxonomy()
let red = taxonomy.query().where(valueAtKey: "taxonomies.color", .equals("red"))
let small = taxonomy.query().where(valueAtKey: "taxonomies.size", .equals("small"))
taxonomy.query()
.operator(.or([red, small]))
.find { (result: Result<ContentstackResponse<TaxonomyModel>, Error>, response: ResponseType) in
guard case .success(let entries) = result else { return }
print(entries.items.map { $0.title })
}Use async/await: entries tagged with any of several terms
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
let entries: ContentstackResponse<TaxonomyModel> = try await stack.taxonomy().query()
.where(valueAtKey: "taxonomies.color", .includes(["red", "yellow"]))
.find()
print(entries.items.map { $0.title })
} catch {
print(error)
}