AssetQuery
AssetQuery
AssetQuery lists the published assets of a stack. Use it to
- list every asset, one page at a time
- filter assets by UID, title, file name or date
- add the total count, image dimensions, metadata or fallback-locale content to the response
AssetQuery adopts BaseQuery, so it also has the paging, sorting and raw-query methods that the BaseQuery page documents. The Method Index below links them.
Instance State
The SDK creates an AssetQuery only through the query() method of Asset. Every instance reaches the same methods.
- Call stack.asset().query() to work across all assets.
- Call stack.asset(uid: "ASSET_UID").query() to start with a uid equals condition, so find returns at most that asset.
A new query starts with no parameters and no headers. It takes its cachePolicy from the Stack, not from the Asset you called query() on.
Class-Level Notes
Conditions and parameters stay on the query.
- where(queryableCodingKey:_:) and the BaseQuery filters store conditions in queryParameter. find sends them as one JSON query parameter.
- locale(_:), include(params:) and the BaseQuery paging methods store values in parameters. find sends them as separate query parameters, plus the environment of the stack.
- A second condition on the same key replaces the first. No method removes a stored value. Call query() again for a clean query.
Pagination.
- The SDK sets no limit, so the API applies its own page size. find returns one page and does not fetch the next one.
- Combine skip(theFirst:) and limit(to:) to read the list one page at a time. Add .count through include(params:) to learn the total.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Filter on a key outside QueryableCodingKey | Yes | Use the where(valueAtKeyPath:_:) method with the field path |
| Read every page in one call | No | Page through the list with skip(theFirst:) and limit(to:) |
| Add the _branch key to the response | No dedicated option | Send include_branch through the addURIParam(with:value:) method |
Class-Level Properties
The table below lists the properties of AssetQuery. They come from BaseQuery, and the methods of the class read and write them, so you rarely set them directly.
| Property | Type | Access | Default | Description |
|---|---|---|---|---|
| stack | Stack | Read-write | The stack of the Asset | Stack that sends the request. |
| parameters | [String: Any] | Read-write | [:] | Query parameters that find sends, such as locale and include_count. |
| queryParameter | [String: Any] | Read-write | [:] | Conditions that find sends as the JSON query parameter. |
| headers | [String: String] | Read-write | [:] | Extra headers that find sends. |
| cachePolicy | CachePolicy | Read-write | The cachePolicy of the Stack | Where find reads the result from. |
AssetQuery.ResourceType is AssetModel.
AssetQuery.Include
AssetQuery.Include is an OptionSet that you pass to include(params:). Combine values in an array literal, such as [.count, .dimension]. The table below lists its values.
| Value | Raw value | Query parameter find sends | Effect on the response |
|---|---|---|---|
| .count | 1 | include_count=true | Adds count, the total number of matching assets. |
| .relativeURL | 2 | relative_urls=true | Asks for the relative URL of each asset. |
| .dimension | 4 | include_dimension=true | Adds the height and width of each image. |
| .fallback | 8 | include_fallback=true | Returns the fallback-locale asset when the locale has none published. |
| .metadata | 16 | include_metadata=true | Adds the _metadata key to each asset. |
| .all | 31 | All five parameters above | Combines every value. |
Method Index
Methods of AssetQuery. Available on every AssetQuery.
| Method Name | Returns | Description |
|---|---|---|
| locale(_:) | The same asset query, for chaining. | Sets the locale of the assets to list. |
| where(queryableCodingKey:_:) | The same asset query, for chaining. | Adds a condition on a typed asset key. |
| include(params:) | The same asset query, for chaining. | Adds count, dimensions, metadata or fallback content to the response. |
Methods from BaseQuery. Available on every AssetQuery. The BaseQuery page documents each one.
| Method Name | Returns | Description |
|---|---|---|
| find(_:) | Nothing. The completion handler receives the result. | Sends the query and returns one page of assets. |
| where(valueAtKeyPath:_:) | The same query, for chaining. | Adds a condition on any field path. |
| skip(theFirst:) | The same query, for chaining. | Skips a number of assets for pagination. |
| limit(to:) | The same query, for chaining. | Caps the number of assets returned. |
| orderByAscending(keyPath:) | The same query, for chaining. | Sorts the assets in ascending order of a field. |
| orderByDecending(keyPath:) | The same query, for chaining. | Sorts the assets in descending order of a field. |
| addURIParam(with:value:) | The same query, for chaining. | Adds one query parameter to the request. |
| addURIParam(dictionary:) | The same query, for chaining. | Adds several query parameters to the request. |
| addQuery(with:value:) | The same query, for chaining. | Adds one raw condition to the JSON query. |
| addQuery(dictionary:) | The same query, for chaining. | Adds several raw conditions to the JSON query. |
| addValue(_:forHTTPHeaderField:) | The same query, for chaining. | Adds a header to the request. |
Class-Level Snippet
The snippet below lists the first 20 image assets in French, newest first, with their dimensions and the total count.
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
.locale("fr-fr")
.where(valueAtKeyPath: "content_type", .matches("^image/"))
.include(params: [.count, .dimension])
.orderByDecending(keyPath: "updated_at")
.limit(to: 20)
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
switch result {
case .success(let assets):
print("Showing \(assets.items.count) of \(assets.count ?? 0)")
for asset in assets.items {
print(asset.fileName, asset.dimension?.width ?? 0, asset.dimension?.height ?? 0)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Methods
Each method of the AssetQuery class has its own section below, with its parameters, validation rules, behavior and examples.
include(params:)
include(params:) asks the API to add the total count, image dimensions, metadata, relative URLs or fallback-locale assets to the response.
| Name | Type | Description |
|---|---|---|
| params (required) | AssetQuery.Include | Options to add, such as [.count, .dimension]. Each option sends one parameter. |
Returns: AssetQuery. The same asset query, for chaining.
Validation
- There is no client-side validation. An empty set, [], stores nothing.
- Errors that do occur come from the find(_:) call that follows, not from include(params:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. include(params:) stores one parameter with the value true in parameters for each option in the set and makes no request.
- The table below maps each option to the parameter that find(_:) sends with Get all assets:
| Option | Parameter |
|---|---|
| .count | include_count |
| .relativeURL | relative_urls |
| .dimension | include_dimension |
| .fallback | include_fallback |
| .metadata | include_metadata |
| .all | All five |
- A later call adds options. It never removes an option that an earlier call stored.
- With .count, read the total from the count property of the ContentstackResponse. With .dimension, read the dimension property of each AssetModel. With .metadata, read fields["_metadata"].
Example
Basic usage: list assets with a count and their dimensions
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
.include(params: [.count, .dimension])
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
switch result {
case .success(let assets):
print("Total: \(assets.count ?? 0)")
for asset in assets.items {
print(asset.fileName, asset.dimension?.width ?? 0, asset.dimension?.height ?? 0)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}All options: add every include value
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
.locale("fr-fr")
.include(params: .all)
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
guard case .success(let assets) = result else { return }
for asset in assets.items {
print(asset.url, asset.fields?["_metadata"] ?? "No metadata")
}
}locale(_:)
locale(_:) sets the locale code that find sends with the request for the asset list.
| Name | Type | Description |
|---|---|---|
| locale (required) | String | Locale code, such as "fr-fr". Selects the localized assets. |
Returns: AssetQuery. The same asset query, for chaining.
Validation
- There is no client-side validation. locale(_:) does not check the code, so an empty or unknown code reaches the API as it is.
- Errors that do occur come from the find(_:) call that follows, not from locale(_:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. locale(_:) stores the code under locale in parameters and makes no request.
- The find(_:) call that follows sends it as the locale query parameter of Get all assets.
- A second call replaces the code from the first call.
- To get assets that have no published version in that locale from the fallback locale, add .fallback through include(params:), as the example below does.
Example
Basic usage: list assets in one locale, with fallback
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
.locale("fr-fr")
.include(params: .fallback)
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
switch result {
case .success(let assets):
for asset in assets.items {
print(asset.title, asset.url)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}where(queryableCodingKey:_:)
where(queryableCodingKey:_:) adds a condition on one typed asset key, so find returns only the assets that match it.
| Name | Type | Description |
|---|---|---|
| queryableCodingKey (required) | AssetModel.QueryableCodingKey | Asset key to test, such as .title. Names the JSON key. |
| operation (required) | Query.Operation | Comparison and value, such as .equals("Banner"). Sets the match rule. |
Returns: AssetQuery. The same asset query, for chaining.
Validation
- There is no client-side validation. The type system limits the key to the five cases of AssetModel.QueryableCodingKey.
- Errors that do occur come from the find(_:) call that follows, not from where(queryableCodingKey:_:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. where(queryableCodingKey:_:) passes the raw value of the key to the where(valueAtKeyPath:_:) method of BaseQuery, which stores the condition in queryParameter.
- The keys are .uid, .title, .fileName (filename), .createdAt (created_at) and .updatedAt (updated_at). The Asset page lists them.
- The Query page lists the cases of Query.Operation, such as .equals, .notEquals, .includes, .matches and .isGreaterThan.
- A second condition on the same key replaces the first. Conditions on different keys combine, and the API returns the assets that match all of them.
- find(_:) sends every condition as the JSON query parameter of Get all assets.
- To test a key outside the five cases, such as content_type, call where(valueAtKeyPath:_:) with the key name.
Example
Basic usage: find assets by title
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
.where(queryableCodingKey: .title, .equals("Banner"))
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
switch result {
case .success(let assets):
print(assets.items.map { $0.url })
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Combine two conditions: assets updated after a date with a name pattern
import ContentstackSwift
import Foundation
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let since = Date(timeIntervalSinceNow: -7 * 24 * 60 * 60)
stack.asset().query()
.where(queryableCodingKey: .updatedAt, .isGreaterThan(since))
.where(queryableCodingKey: .fileName, .matches("^banner"))
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
guard case .success(let assets) = result else { return }
print(assets.items.map { $0.fileName })
}