AssetQuery
AssetQuery
Assets are the media files uploaded to a stack, such as images, videos, PDFs, and audio files. Use this class to
- list the assets published in an environment
- filter that list by asset field values
- add dimensions, metadata, relative URLs, and extra field groups to each asset in the response
stack.asset_query() takes no arguments and returns an AssetQuery. To read one asset by its UID, call stack.asset('<ASSET_UID>'), which returns an Asset.
AssetQuery inherits from BaseQuery, the class that Query also inherits from. Only some of the inherited methods change the asset request, as the Class-Level Notes below describe.
Class-Level Notes
What find sends.
- find sends the query parameters that the methods in the first three groups of the Method Index set.
- When the where or query method has added a condition, find also sends every condition as one JSON object in the query parameter.
- find never sends the values that the eight inherited methods in the last group of the Method Index store.
Known issue include_count, limit, skip, order_by_ascending, order_by_descending, param, add_params, and remove_param return the query and raise nothing, but find does not send what they store. A chain that uses them returns unsorted, unpaged results with no count. Narrow the list with the where method, and sort or count the returned list in your own code.
Pagination.
- One find call sends one request and returns one page. The SDK does not request further pages.
- The Delivery API returns the first 100 assets when the request sets no limit. See Pagination.
- Because limit and skip have no effect on this class, find returns at most that first page. To read every published asset, use the sync_init method of Stack with publish_type='asset_published'.
Environment.
- The constructor copies the environment from the Stack headers into the request URL once. Every find on that query sends that environment.
- The environment method writes to the Stack headers dictionary, which every object you create from that Stack reads. Its page includes a Known issue line with the consequence.
- The Delivery API expects a delivery token that belongs to the environment you read from. See the access_token header in Get all assets. To list assets from a second environment, create a second Stack with that environment and its delivery token.
Flags are one-way.
- The include_ methods and the relative_url method each write the string 'true' under a fixed query parameter key.
- No working method removes a query parameter. Create a new stack.asset_query() to send a request without one.
Rate limiting and retry.
- The SDK retries a request that returns 408 or 429, sending the initial request plus up to five retries, with no delay between them.
- Each request times out after 30 seconds unless you pass a different timeout to Stack.
Additional Resource Refer to the Stack class page for the retry_strategy and timeout options.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Page through assets with limit and skip | No | Narrow the list with where, or read every asset through Stack.sync_init |
| Return a total count with include_count | No | Count the assets list that find returns |
| Sort with order_by_ascending or order_by_descending | No | Sort the returned list in your own code |
| Read one asset by UID | No | Use the fetch method of Asset |
| Scope an environment change to one query | No | Create a separate Stack for each environment |
Method Index
Every method below is available on stack.asset_query(). The groups follow what each method does to the request.
List assets. Available on stack.asset_query() as the terminal call of a chain.
| Method Name | Returns | Description |
|---|---|---|
| find | The matching assets. | Lists the published assets that match the query. |
Filter the list. Available on stack.asset_query(). AssetQuery inherits both methods from BaseQuery.
| Method Name | Returns | Description |
|---|---|---|
| where | The same query, for chaining. | Adds a field condition with a comparison operator. |
| query | The same query, for chaining. | Adds a field condition that matches a string value. |
Shape the response. Available on stack.asset_query().
| Method Name | Returns | Description |
|---|---|---|
| include_dimension | The same query, for chaining. | Adds the height and width of each image. |
| include_metadata | The same query, for chaining. | Adds the metadata of each asset. |
| include_branch | The same query, for chaining. | Adds the branch of each asset. |
| include_fallback | The same query, for chaining. | Returns fallback-locale assets when a localization is missing. |
| relative_url | The same query, for chaining. | Requests the relative URL of each asset. |
| asset_fields | The same query, for chaining. | Requests extra asset field groups. |
| locale | The same query, for chaining. | Sets the locale to read. |
| version | The same query, for chaining. | Sets the version query parameter. |
| environment | The same query, for chaining. | Sets the environment header on the Stack. |
Inherited methods with no effect. Available on stack.asset_query() through BaseQuery, but find does not send what they store.
| Method Name | Returns | Description |
|---|---|---|
| include_count | The same query, for chaining. | Stores a count flag that find does not send. |
| limit | The same query, for chaining. | Stores a page size that find does not send. |
| skip | The same query, for chaining. | Stores an offset that find does not send. |
| order_by_ascending | The same query, for chaining. | Stores an ascending sort key that find does not send. |
| order_by_descending | The same query, for chaining. | Stores a descending sort key that find does not send. |
| param | The same query, for chaining. | Stores a parameter that find does not send. |
| add_params | The same query, for chaining. | Stores several parameters that find does not send. |
| remove_param | The same query, for chaining. | Deletes a parameter from the unsent store. |
Class-Level Snippet
This snippet lists the PNG images in an environment, with their dimensions, and prints each title and URL.
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query() \
.where('content_type', QueryOperation.EQUALS, fields='image/png') \
.include_dimension() \
.relative_url() \
.find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'], asset['url'])Methods
Each method of the AssetQuery class has its own section below, with its parameters, validation rules, behavior, and examples.
add_params
add_params stores several query parameters on the query at once, but find does not send them on an asset query.
| Name | Type | Description |
|---|---|---|
| param (required) | dict | Query parameter names mapped to their values. |
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation of the names or values. add_params merges the dictionary as given.
- None, or a value that is not a mapping or a list of key and value pairs, raises TypeError, because add_params merges it with dict.update.
- Omitting the argument raises TypeError, because param is a positional parameter with no default.
- add_params cannot cause an API error on an asset query, because find does not send the parameters.
Behavior
- Has no effect on AssetQuery. find does not send the values this method stores. See the Known issue on the AssetQuery class page.
- A key that the store already holds takes the new value.
- On a Query, the add_params method sends the parameters.
Limitations
- Does not add query parameters to the asset request. Chain the dedicated methods instead, such as locale and include_fallback.
Example
Basic usage: chain the dedicated methods instead
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# find does not send add_params, so the dedicated methods set the same values
result = stack.asset_query() \
.add_params({'locale': 'fr-fr', 'include_fallback': 'true'}) \
.locale('fr-fr') \
.include_fallback() \
.find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'])asset_fields
asset_fields requests extra asset field groups, such as visual_markups, for each asset in the response.
| Name | Type | Description |
|---|---|---|
| field_names (required) | str | Field group names, passed as separate arguments. |
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. asset_fields converts each name with str() and stores it, so an unknown group name reaches the API unchanged.
- Calling asset_fields() with no arguments is valid and changes nothing.
- Errors that do occur come from the find() call that follows, not from asset_fields().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. asset_fields appends the names to a list under the asset_fields[] query parameter and makes no request. The find() call that follows sends one asset_fields[] value per name.
- The SDK names four groups: user_defined_fields, embedded_metadata, ai_generated_metadata, and visual_markups.
- The Delivery API defines the groups it accepts. See asset_fields[] in Get all assets for the current list.
- With visual_markups, the API returns the hotspot and bounding-box annotations of each asset under the visual_markups key, or an empty array when the asset has none. See asset_fields[] in Get all assets.
- A list or a tuple counts as several names. asset_fields(['user_defined_fields', 'visual_markups']) stores the same two names as two separate arguments.
- A second call adds to the list instead of replacing it.
Example
Basic usage: list assets with their visual markups
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().asset_fields('visual_markups').find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'], asset.get('visual_markups'))All parameters: request every field group the SDK names
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query() \
.asset_fields('user_defined_fields', 'embedded_metadata') \
.asset_fields(['ai_generated_metadata', 'visual_markups']) \
.find()
print(len(result.get('assets', [])), 'assets')
except Exception as error:
print('Request failed:', error)environment
environment writes an environment name into the environment header that the Stack sends with every request.
| Name | Type | Description |
|---|---|---|
| environment (required) | str | Environment name to send in the request header. |
Returns: AssetQuery. The same query, for chaining.
Known issue environment does not change the environment that this query's find sends in the URL, and it changes the header for every later request from the same Stack. To list assets from another environment, create a separate Stack with that environment and its delivery token.
Validation
- There is no client-side validation of the name. environment stores an empty string as given.
- A value that is not a str, including None, changes nothing, and environment returns the query.
- Omitting the argument raises TypeError, because environment is a positional parameter with no default.
- Errors that do occur come from the find() call that follows, not from environment().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. environment writes the name into the Stack headers dictionary and makes no request.
- The query keeps the environment that its constructor copied into the URL. The find() call that follows therefore sends the new name in the header and the original name in the URL.
- Every request the same Stack sends afterwards carries the new header. Every Asset or AssetQuery you create from that Stack afterwards also copies the new name into its URL.
- Get all assets lists environment as a query parameter and takes an environment-specific delivery token in the access_token header.
- Calling environment twice replaces the first value, because both calls write the same header key.
Example
Basic usage: set the environment header
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().environment('<ENVIRONMENT>').find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
print(len(result['assets']), 'assets')Workaround: list a second environment through its own stack
import contentstack
production = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', 'production')
staging = contentstack.Stack('<API_KEY>', '<STAGING_DELIVERY_TOKEN>', 'staging')
try:
live = production.asset_query().find()
draft = staging.asset_query().find()
print(len(live.get('assets', [])), len(draft.get('assets', [])))
except Exception as error:
print('Request failed:', error)find
find sends the asset query and returns the published assets that match it.
This method takes no parameters. It reads the conditions and query parameters the chain set from the instance.
Returns: dict. The matching assets.
Validation
- There is no client-side validation. find sends whatever conditions and query parameters the query holds.
- find raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- One call sends one Get all assets request, GET /v3/assets.
- The request carries the environment the constructor copied into the URL, and every query parameter that the response-shaping methods set, such as include_dimension or locale.
- When the where or query method has added a condition, find sends all conditions as one JSON object in the query parameter.
- find does not send the values that include_count, limit, skip, order_by_ascending, order_by_descending, param, add_params, and remove_param store. See the Known issue on the AssetQuery class page.
- find returns the parsed JSON body unchanged. Read the list of assets from result['assets'].
- find returns one page. The Delivery API returns the first 100 assets when the request sets no limit. See Pagination.
- Calling find twice on one query sends the same request twice. The SDK caches nothing.
Limitations
- Does not return more than the first page of assets. Narrow the list with the where method, or read every published asset through the sync_init method of Stack.
Example
Basic usage: list the assets in an environment
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['uid'], asset['title'])Filtered list: find the assets whose title starts with a word
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query() \
.where('title', QueryOperation.MATCHES, fields='^Hero') \
.include_dimension() \
.find()
print(len(result.get('assets', [])), 'matching assets')
except Exception as error:
print('Request failed:', error)include_branch
include_branch asks the API to add the _branch key, the UID of the branch each asset belongs to, to the response.
This method takes no parameters.
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. include_branch takes no input and cannot fail.
- Errors that do occur come from the find() call that follows, not from include_branch().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. include_branch sets the include_branch query parameter to 'true' and makes no request. The find() call that follows sends it.
- The API adds the _branch top-level key, which holds the unique ID of the branch. See include_branch in Get all assets.
- include_branch does not choose the branch. The branch argument of Stack sets the branch header that selects it.
- Calling include_branch twice changes nothing, because both calls write the same value under the same key.
Example
Basic usage: list the assets of a branch with the branch key
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>', branch='development')
try:
result = stack.asset_query().include_branch().find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
print(result)include_count
include_count stores a flag that asks for the total asset count, but find does not send it on an asset query.
This method takes no parameters.
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. include_count takes no input and cannot fail.
- include_count cannot cause an API error on an asset query, because find does not send the flag.
Behavior
- Has no effect on AssetQuery. find does not send the value this method stores. See the Known issue on the AssetQuery class page.
- The response from find therefore carries no count key.
- On a Query, the include_count method sends the flag.
Limitations
- Does not return the total number of assets. The length of the assets list counts only the page that find returns. Read every published asset through the sync_init method of Stack to count them all.
Example
Basic usage: count the assets on the returned page
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# find does not send include_count, so the response has no count key
result = stack.asset_query().include_count().find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
print(len(result['assets']), 'assets on this page')include_dimension
include_dimension asks the API to add the height and width of each image asset to the response.
This method takes no parameters.
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. include_dimension takes no input and cannot fail.
- Errors that do occur come from the find() call that follows, not from include_dimension().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. include_dimension sets the include_dimension query parameter to 'true' and makes no request. The find() call that follows sends it.
- The API returns dimensions for JPG, GIF, PNG, WebP, BMP, TIFF, SVG, and PSD images. See include_dimension in Get all assets.
- Calling include_dimension twice changes nothing, because both calls write the same value under the same key.
Example
Basic usage: list images with their height and width
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().include_dimension().find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'], asset['url'])include_fallback
include_fallback asks the API to return assets from the fallback locale when the requested locale has no published version.
This method takes no parameters.
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. include_fallback takes no input and cannot fail.
- Errors that do occur come from the find() call that follows, not from include_fallback().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. include_fallback sets the include_fallback query parameter to 'true' and makes no request. The find() call that follows sends it.
- The API then includes the published asset details from the fallback locale when the requested locale holds no published content. See include_fallback in Get all assets.
- Pair it with the locale method, which sets the requested locale.
- Calling include_fallback twice changes nothing, because both calls write the same value under the same key.
Example
Basic usage: list French assets with fallback
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().locale('fr-fr').include_fallback().find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'])include_metadata
include_metadata asks the API to add the metadata of each asset to the response.
This method takes no parameters.
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. include_metadata takes no input and cannot fail.
- Errors that do occur come from the find() call that follows, not from include_metadata().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. include_metadata sets the include_metadata query parameter to 'true' and makes no request. The find() call that follows sends it.
- The API returns the metadata of each asset under the _metadata key, with one entry per extension UID. See Get all assets.
- Calling include_metadata twice changes nothing, because both calls write the same value under the same key.
- Asset has no include_metadata method. To add metadata to one asset, call params('include_metadata', 'true') through the params method of Asset.
Example
Basic usage: list assets with their metadata
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().include_metadata().find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'], asset.get('_metadata'))limit
limit stores a page size on the query, but find does not send it on an asset query.
| Name | Type | Description |
|---|---|---|
| limit_count (required) | int | Maximum number of assets to return. |
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. limit converts the value with str() and stores it.
- Omitting the argument raises TypeError, because limit_count is a positional parameter with no default.
- limit cannot cause an API error on an asset query, because find does not send the value.
Behavior
- Has no effect on AssetQuery. find does not send the value this method stores. See the Known issue on the AssetQuery class page.
- The API applies its own page size and returns the first 100 assets. See Pagination.
- On a Query, the limit method sends the value.
Limitations
- Does not cap the asset list. Slice the returned list in your own code, or narrow it with the where method.
Example
Basic usage: keep the first ten assets of the returned page
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# find does not send limit, so the API applies its own page size
result = stack.asset_query().limit(10).find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets'][:10]:
print(asset['title'])locale
locale sets the locale of the assets to list.
| Name | Type | Description |
|---|---|---|
| locale (required) | str | Locale code to read, such as fr-fr. |
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. locale stores the value as given, so an empty string sends an empty locale parameter and None sends the text None.
- Omitting the argument raises TypeError, because locale is a positional parameter with no default.
- Errors that do occur come from the find() call that follows, not from locale().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. locale sets the locale query parameter and makes no request. The find() call that follows sends it.
- Calling locale twice replaces the first value, because both calls write the same key.
- Pair it with the include_fallback method to receive fallback-locale assets when the requested locale has no published version.
Example
Basic usage: list the assets of one locale
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().locale('fr-fr').find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'])order_by_ascending
order_by_ascending stores a sort key for ascending order, but find does not send it on an asset query.
| Name | Type | Description |
|---|---|---|
| key (required) | str | Asset field to sort by, such as title. |
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. order_by_ascending converts the key with str() and stores it.
- Omitting the argument raises TypeError, because key is a positional parameter with no default.
- order_by_ascending cannot cause an API error on an asset query, because find does not send the key.
Behavior
- Has no effect on AssetQuery. find does not send the value this method stores. See the Known issue on the AssetQuery class page.
- The assets arrive in the order the API applies by default.
- On a Query, the order_by_ascending method sends the key as the asc parameter.
Limitations
- Does not sort the asset list. Sort the returned list in your own code.
Example
Basic usage: sort the returned assets in your own code
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# find does not send the sort key, so sort the list after the call
result = stack.asset_query().order_by_ascending('title').find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in sorted(result['assets'], key=lambda item: item.get('title', '')):
print(asset['title'])order_by_descending
order_by_descending stores a sort key for descending order, but find does not send it on an asset query.
| Name | Type | Description |
|---|---|---|
| key (required) | str | Asset field to sort by, such as title. |
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. order_by_descending converts the key with str() and stores it.
- Omitting the argument raises TypeError, because key is a positional parameter with no default.
- order_by_descending cannot cause an API error on an asset query, because find does not send the key.
Behavior
- Has no effect on AssetQuery. find does not send the value this method stores. See the Known issue on the AssetQuery class page.
- The assets arrive in the order the API applies by default.
- On a Query, the order_by_descending method sends the key as the desc parameter.
Limitations
- Does not sort the asset list. Sort the returned list in your own code.
Example
Basic usage: sort the returned assets in your own code
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# find does not send the sort key, so sort the list after the call
result = stack.asset_query().order_by_descending('title').find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in sorted(result['assets'], key=lambda item: item.get('title', ''), reverse=True):
print(asset['title'])param
param stores one query parameter on the query, but find does not send it on an asset query.
| Name | Type | Description |
|---|---|---|
| key (required) | str | Query parameter name. |
| value (required) | Any | Query parameter value to store. |
Returns: AssetQuery. The same query, for chaining.
Validation
- param raises KeyError when key or value is None, because a parameter needs both.
- Omitting either argument raises TypeError, because both are positional parameters with no default.
- param cannot cause an API error on an asset query, because find does not send the pair.
Behavior
- Has no effect on AssetQuery. find does not send the value this method stores. See the Known issue on the AssetQuery class page.
- param converts the value with str() before it stores it.
- On a Query, the param method sends the pair.
Limitations
- Does not add a query parameter to the asset request. Use the dedicated method instead, such as locale, version, or include_dimension.
Example
Basic usage: use the dedicated method instead
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# find does not send param('locale', ...), so locale() sets the locale
result = stack.asset_query().param('locale', 'fr-fr').locale('fr-fr').find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'])Error handling: a null value raises before any request
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
query = stack.asset_query().param('locale', None)
except KeyError as error:
# Raised when the key or the value is None
print('Invalid parameter:', error)query
query adds a condition that matches one asset field against a string value.
| Name | Type | Description |
|---|---|---|
| key (required) | str | Asset field to match, such as title. |
| value (required) | Any | Value to match, sent as a string. |
Returns: AssetQuery. The same query, for chaining.
Validation
- query raises KeyError when key or value is None, because a condition needs both.
- Omitting either argument raises TypeError, because both are positional parameters with no default.
- There is no other client-side validation. query accepts an empty string and stores it.
- Errors that do occur come from the find() call that follows, not from query().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. query adds the condition to the query's conditions and makes no request. The find() call that follows sends every condition as one JSON object in the query parameter, as the Equals Operator describes.
- query converts the value with str(). The number 1000 arrives as the string "1000", and a dictionary arrives as its Python representation, not as an operator. Use the where method for numbers, lists, and operators.
- query writes to the same conditions as the where method, so a second condition on the same field replaces the first.
Example
Basic usage: list the assets with a given file name
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().query('filename', 'hero-banner.png').find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['uid'], asset['url'])Error handling: a null value raises before any request
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
selected_title = None
try:
query = stack.asset_query().query('title', selected_title)
except KeyError as error:
# Raised when the key or the value is None
print('Invalid condition:', error)relative_url
relative_url asks the API to include the relative URL of each asset in the response.
This method takes no parameters.
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. relative_url takes no input and cannot fail.
- Errors that do occur come from the find() call that follows, not from relative_url().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. relative_url sets the relative_urls query parameter to 'true' and makes no request. The find() call that follows sends it.
- The method name is singular on AssetQuery, and the parameter it sends is plural. The equivalent method on Asset is the relative_urls method.
- Calling relative_url twice changes nothing, because both calls write the same value under the same key.
Example
Basic usage: list assets with their relative URLs
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().relative_url().find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['url'])remove_param
remove_param deletes one key from the store of the inherited methods, which find does not send on an asset query.
| Name | Type | Description |
|---|---|---|
| key (required) | str | Name of the stored parameter to delete. |
Returns: AssetQuery. The same query, for chaining.
Validation
- remove_param raises ValueError when key is None, because it needs a key to look up.
- Omitting the argument raises TypeError, because key is a positional parameter with no default.
- A key that the store does not hold changes nothing and raises nothing.
- remove_param cannot cause an API error on an asset query, because it changes nothing that find sends.
Behavior
- Has no effect on AssetQuery. find does not read the store this method changes. See the Known issue on the AssetQuery class page.
- remove_param cannot delete a parameter that a response-shaping method set, such as locale or include_dimension, and cannot delete a where condition.
- On a Query, the remove_param method changes what find sends.
Limitations
- Does not remove a parameter from the asset request. Create a new stack.asset_query() without the method that set it.
Example
Basic usage: build a new query instead of removing a parameter
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# remove_param does not delete the locale that locale() set
stack.asset_query().locale('fr-fr').remove_param('locale')
# Build a new query without locale() instead
result = stack.asset_query().find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
print(len(result['assets']), 'assets')Error handling: a null key raises ValueError
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
query = stack.asset_query().remove_param(None)
except ValueError as error:
# Raised when the key is None
print('Invalid key:', error)skip
skip stores an offset on the query, but find does not send it on an asset query.
| Name | Type | Description |
|---|---|---|
| skip_count (required) | int | Number of assets to skip before returning results. |
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. skip converts the value with str() and stores it.
- Omitting the argument raises TypeError, because skip_count is a positional parameter with no default.
- skip cannot cause an API error on an asset query, because find does not send the value.
Behavior
- Has no effect on AssetQuery. find does not send the value this method stores. See the Known issue on the AssetQuery class page.
- Every find call returns the same first page of assets. See Pagination.
- On a Query, the skip method sends the value.
Limitations
- Does not reach assets beyond the first page. Narrow the list with the where method, or read every published asset through the sync_init method of Stack.
Example
Basic usage: skip assets in your own code
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# find does not send skip, so the response starts at the first asset
result = stack.asset_query().skip(2).find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets'][2:]:
print(asset['title'])version
version sets the version query parameter on the asset listing request.
| Name | Type | Description |
|---|---|---|
| version (required) | int | Asset version number to request. |
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation. version stores the value as given, so a string, a negative number, or None reaches the request as its text form.
- Omitting the argument raises TypeError, because version is a positional parameter with no default.
- Errors that do occur come from the find() call that follows, not from version().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. version sets the version query parameter and makes no request. The find() call that follows sends it.
- The API reference documents version on Get a single asset, not on Get all assets, the request that find sends.
- Get a single asset says to leave the environment parameter blank to retrieve a specific version. AssetQuery always sends the environment that the Stack held when you created the query.
- To read one version of one asset, call params('version', '2') through the params method of Asset instead.
- Calling version twice replaces the first value, because both calls write the same key.
Example
Basic usage: send a version number with the listing
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().version(3).find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'])where
where adds a condition on one asset field, using a comparison operator from QueryOperation.
| Name | Type | Description |
|---|---|---|
| field_uid (required) | str | Asset field to compare, such as title. |
| query_operation (required) | QueryOperation | Comparison operator to apply. |
| fields | Any | Value or list of values to compare against. |
Returns: AssetQuery. The same query, for chaining.
Validation
- There is no client-side validation of the field or the value. where stores both as given.
- When field_uid or query_operation is None, where adds nothing and returns the query.
- A query_operation that is not a QueryOperation member, such as the string '$lt', raises AttributeError, because where reads the member's name and value.
- Omitting field_uid or query_operation raises TypeError, because both are positional parameters with no default.
- Errors that do occur come from the find() call that follows, not from where().
- find() raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. where adds the condition to the query's conditions and makes no request. The find() call that follows sends every condition as one JSON object in the query parameter.
- Import QueryOperation with from contentstack.basequery import QueryOperation. The members map to the Queries operators, which work for assets as well as entries:
| Member | Operator sent |
|---|---|
| EQUALS | The value itself, with no operator |
| NOT_EQUALS | $ne |
| INCLUDES | $in |
| EXCLUDES | $nin |
| IS_LESS_THAN | $lt |
| IS_LESS_THAN_OR_EQUAL | $lte |
| IS_GREATER_THAN | $gt |
| IS_GREATER_THAN_OR_EQUAL | $gte |
| EXISTS | $exists |
| MATCHES | $regex |
- With EQUALS, a one-item list sends the item itself, so fields=['Hero'] and fields='Hero' send the same condition.
- When you omit fields, the condition compares against null.
- Two conditions on the same field do not combine. The second call replaces the first. The query method writes to the same conditions, so it replaces a where condition on the same field too.
- where keeps the value's JSON type, so a number stays a number and a list stays a list.
Example
Basic usage: list the assets with a given title
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query().where('title', QueryOperation.EQUALS, fields='Hero banner').find()
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)
else:
if 'error_code' in result:
# The Delivery API rejected the request and returned the error body
print('Delivery API error:', result['error_code'], result['error_message'])
else:
for asset in result['assets']:
print(asset['title'], asset['url'])All parameters: combine an array operator and a comparison
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset_query() \
.where('content_type', QueryOperation.INCLUDES, fields=['image/png', 'image/jpeg']) \
.where('created_at', QueryOperation.IS_GREATER_THAN, fields='2026-01-01') \
.find()
print(len(result.get('assets', [])), 'matching assets')
except Exception as error:
print('Request failed:', error)Error handling: pass a QueryOperation member, not a string
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
query = stack.asset_query().where('title', '$regex', fields='^Hero')
except AttributeError as error:
# Raised because the operator is a string instead of a QueryOperation member
print('Use a QueryOperation member:', error)