Query
Query
Query builds a request for the published entries of one content type. Use this class to
- match entries by field value, tag, or a combination of conditions
- choose the locale, fields, references, and embedded items the response carries
- sort and paginate the result
- send the request with find or find_one
content_type.query() is the only way to get an instance. query() takes no arguments, and the query reads its content type UID from the stack.content_type() call before it. The following table describes that argument:
| Name | Type | Description |
|---|---|---|
| content_type_uid | str | UID of the content type whose entries the query reads. Pass it to stack.content_type(). |
- content_type.query() raises PermissionError if the content type UID is None, as it is after stack.content_type() with no argument.
- Every method except find and find_one returns the same Query, so calls chain in any order and one of those two sends the request.
Warning stack.content_type('').query() does not raise. The check rejects None only, so an empty string builds the request path /content_types//entries. Check that a UID variable is non-empty before you pass it.
Class-Level Notes
Three stores, merged when the request goes out.
- where and query write the condition object, which find sends as JSON under the query parameter.
- The pagination and sort methods, param, add_params, tags, search, where_in, where_not_in, query_operator, and the include_ methods that Query defines write the URL parameters.
- locale, only, excepts, include_reference, include_content_type, include_reference_content_type_uid, asset_fields, and add_param write the entry option store.
- find copies the entry option store over the URL parameters, so on a shared key the entry option wins. remove_param deletes URL parameters only.
One value survives under the query key.
- find writes a non-empty condition object under query after every other value, so a where or query condition replaces whatever query_operator, param, or add_params put there.
- query_operator empties the condition object first, so a where call before it has no effect.
Known issue where_in and where_not_in build a condition that never reaches the API. Pass the $in_query or $nin_query operator through the where method instead.
Pagination.
- Each find call sends one request and returns one page. The SDK does not request further pages.
- Without limit, the API returns the first 100 entries. Chain include_count and compare the count with the number of entries in the page, then use skip and limit to read later pages.
- find_one writes limit=1 and leaves it on the query.
Live preview.
- When you create the Stack with a live_preview dictionary, find and find_one try to merge a preview entry into the response, and the merge fails.
Known issue With a live_preview dictionary on the Stack, find and find_one raise instead of returning entries. Run queries from a second Stack created without live_preview, and read a preview entry with the fetch method on the Entry class.
Rate limiting and retry.
- This SDK retries 408 and 429 responses automatically. The default retry_strategy sends the initial request plus up to five retries, with no delay between them, because its backoff_factor is 0.
- Pass your own retry_strategy to Stack with a non-zero backoff factor if you expect to hit 429.
Additional Resource Implement Retry Mechanism with Python Delivery SDK covers the retry_strategy parameters and backoff configuration.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Reference queries through where_in and where_not_in | No | Pass {'$in_query': ...} or {'$nin_query': ...} to where with QueryOperation.EQUALS. |
| Return every entry in one call | No | Page through the results with skip and limit. |
| Combine query_operator with a where condition on the same query | No | Pass the extra condition as one more sub-query to query_operator. |
| Remove an entry option such as locale or only | No | Build a new query. remove_param deletes URL parameters only. |
| A merged live preview result | No | Read the preview entry with the fetch method on the Entry class. |
Method Index
Every method below works on any Query instance. The groups follow what you are trying to do.
Filter the entries. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| where | The same query, for chaining. | Matches entries by a field value and an operator. |
| query | The same query, for chaining. | Matches entries whose field equals a string. |
| query_operator | The same query, for chaining. | Joins the conditions of other queries with $and or $or. |
| where_in | The same query, for chaining. | Builds a reference condition with $in_query. |
| where_not_in | The same query, for chaining. | Builds a reference condition with $nin_query. |
| tags | The same query, for chaining. | Sends tags to match entries by. |
| search | The same query, for chaining. | Sends a free-text search value. Deprecated. |
Choose what the request reads. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| locale | The same query, for chaining. | Sets the locale to read. |
| include_fallback | The same query, for chaining. | Returns fallback locale content when a localization is missing. |
Shape the response. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| only | The same query, for chaining. | Keeps one top-level field in each entry. |
| excepts | The same query, for chaining. | Leaves one top-level field out of each entry. |
| include_reference | The same query, for chaining. | Returns referenced entries in full instead of as UIDs. |
| include_reference_content_type_uid | The same query, for chaining. | Asks for the content type UID of each referenced entry. |
| include_content_type | The same query, for chaining. | Asks for the content type with the entries. |
| include_embedded_items | The same query, for chaining. | Returns items embedded in rich text fields. |
| include_metadata | The same query, for chaining. | Adds the metadata of each entry to the response. |
| include_branch | The same query, for chaining. | Adds the _branch key to each entry. |
| asset_fields | The same query, for chaining. | Adds extra field groups to embedded assets. |
Sort and paginate. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| limit | The same query, for chaining. | Sets the maximum number of entries returned. |
| skip | The same query, for chaining. | Skips a number of entries before the page starts. |
| include_count | The same query, for chaining. | Adds the total number of matching entries. |
| order_by_ascending | The same query, for chaining. | Sorts entries by one field in ascending order. |
| order_by_descending | The same query, for chaining. | Sorts entries by one field in descending order. |
Send a parameter the SDK has no method for. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| param | The same query, for chaining. | Adds one URL parameter, converting the value to a string. |
| add_params | The same query, for chaining. | Merges a dictionary of URL parameters. |
| add_param | The same query, for chaining. | Adds one entry option, unconverted. |
| remove_param | The same query, for chaining. | Deletes one URL parameter. |
Send the request. Available on any Query, as the last call in the chain.
| Method Name | Returns | Description |
|---|---|---|
| find | The matching entries. | Sends the query and returns one page of entries. |
| find_one | The first matching entry. | Sends the query with the page size set to one. |
Class-Level Snippet
The following snippet lists the ten cheapest French entries under a price, with the total count and only the title field.
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>') \
.query() \
.where('price_in_usd', QueryOperation.IS_LESS_THAN, fields=600) \
.locale('fr-fr') \
.include_fallback() \
.only('title') \
.order_by_ascending('price_in_usd') \
.limit(10) \
.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('total matches:', result.get('count'))
for entry in result['entries']:
print(entry['uid'], entry.get('title'))Methods
Each method of the Query class has its own section below, with its parameters, validation rules, behavior, and examples.
add_param
add_param adds one query parameter that the SDK has no method for.
| Name | Type | Description |
|---|---|---|
| key (required) | str | Query parameter name. |
| value (required) | str | Value to send for that parameter. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. When key or value is None, add_param records nothing, raises nothing, and returns the query.
- add_param keeps the value as given, without converting it to a string.
- Calling add_param() with fewer than two arguments raises TypeError, because add_param takes key and value as positional parameters with no default.
- Errors that do occur come from the find() call that follows, not from add_param().
- 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. add_param stores the pair and makes no request. The find method sends it.
- A second call with the same key replaces the value.
- A list value sends one pair per item, because the find method encodes repeated keys. The annotation names str, and a list works the same way.
- add_param writes the entry option store. The find method copies that store over the URL parameters. On a shared key, this value wins over the value from the param or add_params method. The remove_param method cannot delete it.
- The param and add_params methods write the URL parameters instead. A key that add_param sets wins over the same key from those methods, and over methods such as limit that write the URL parameters.
Example
Basic usage: resolve taxonomy terms
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().add_param('include_taxonomy_terms', 'true').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 entry in result['entries']:
print(entry['title'])List value: keep two top-level fields
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# A list sends one only[BASE][] pair per item.
result = stack.content_type('<CONTENT_TYPE_UID>').query().add_param('only[BASE][]', ['title', 'url']).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)add_params
add_params merges a dictionary of URL query parameters into the request.
| Name | Type | Description |
|---|---|---|
| param (required) | dict | Query parameter names and values to add. |
Returns: Query. The same query, for chaining.
Validation
- add_params raises TypeError if param is None, because it merges the argument into the URL parameters with dict.update.
- There is no other client-side validation. add_params keeps the values as given, without converting them to strings.
- Calling add_params() without an argument raises TypeError, because param is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from add_params().
- 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. add_params merges the dictionary into the URL parameters and makes no request. The find method sends it.
- A key you pass replaces the same key already stored, including one from limit or skip.
- A list value sends one pair per item, because the find method encodes repeated keys.
- add_params writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: add two parameters in one call
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().add_params({'include_taxonomy_terms': 'true', 'include_publish_details': 'true'}).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 entry in result['entries']:
print(entry['title'])asset_fields
asset_fields asks the API to add extra field groups to each asset embedded in the entries.
| Name | Type | Description |
|---|---|---|
| field_names (required) | str | list[str] | Asset field group names, passed as separate arguments. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation of the names. asset_fields converts each value with str() and keeps it, so a misspelled name reaches the request.
- A list or tuple argument contributes each of its items.
- A call with no arguments changes nothing and raises 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 adds each name to the asset_fields[] query parameter and makes no request. The find method sends one asset_fields[] pair per name.
- Calls add up. A second call appends its names to the ones already stored, and a repeated name goes out twice.
- The SDK documents four field group names: user_defined_fields, embedded_metadata, ai_generated_metadata, and visual_markups.
- visual_markups returns the hotspot and bounding-box annotations of each embedded asset under the visual_markups key. See the asset_fields[] parameter of the Get all entries request.
- asset_fields writes the entry option store. The find method copies that store over the URL parameters. On a shared key, this value wins over the value from the param or add_params method. The remove_param method cannot delete it.
Example
Basic usage: add one field group
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').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 entry in result['entries']:
print(entry['title'])Several field groups: pass names as separate arguments, or a list
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# Calls add up. This request sends three asset_fields[] values.
result = stack.content_type('<CONTENT_TYPE_UID>').query().asset_fields('user_defined_fields', 'visual_markups').asset_fields(['embedded_metadata']).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)excepts
excepts removes one top-level field from each entry in the response.
| Name | Type | Description |
|---|---|---|
| field_uid (required) | str | UID of the top-level field to leave out. |
Returns: Query. The same query, for chaining.
Validation
- excepts accepts one field UID as a string. It raises KeyError if field_uid is any other non-null type, such as a list, because excepts stores a single string under the except[BASE][] key.
- A None value records nothing and raises nothing, so the response carries every field.
- excepts does not check that the field exists. An unknown field UID reaches the request as given.
- Calling excepts() without an argument raises TypeError, because field_uid is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from excepts().
- 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. excepts writes the except[BASE][] query parameter and makes no request. The find method sends it.
- A second call replaces the first field. excepts holds one field UID at a time.
- excepts writes the entry option store. The find method copies that store over the URL parameters. On a shared key, this value wins over the value from the param or add_params method. The remove_param method cannot delete it.
- BASE stands for the top-level fields of the content type schema. See the Exclude operator section of the API reference.
Limitations
- Does not take more than one field. To leave out several fields, pass a list under the same key through the add_param method, for example add_param('except[BASE][]', ['title', 'url']). The find method sends one except[BASE][] pair per list item.
- Does not apply to the fields of a referenced entry. The API takes except[<reference_field_uid>][] for those. Send it through the add_param method together with the include_reference method.
Example
Basic usage: leave the body field out
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().excepts('body').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 entry in result['entries']:
print(entry['title'])Several fields: pass a list through add_param
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().add_param('except[BASE][]', ['title', 'url']).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)find
find sends the query and returns one page of matching entries.
This method takes no parameters. It reads the content type UID and every chained condition and parameter from the instance.
Returns: dict. The matching entries.
Validation
- find does not check the chain. The content_type.query() call rejects a None content type UID with PermissionError, and accepts an empty string, which builds the path /content_types//entries.
- find raises TypeError if a where value has no JSON form, such as a datetime.
- When the Stack carries a live_preview dictionary, find raises. See the Known issue below.
- 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
- Each call sends one GET /content_types/{content_type_uid}/entries request. See the Get all entries request.
- find returns the response body as a dictionary. Read the entries from its entries key, and the total from its count key when you chained include_count.
- find builds the query string in four steps.
- It starts from the URL parameters, such as those from limit and param.
- It copies the entry option store over them, so a value from locale, only, or add_param wins on a shared key.
- It writes the conditions from where and query as JSON under the query key, when there are any.
- It copies the environment request header into the environment parameter, and encodes a list value as one pair per item.
- find returns one page. Without limit, the API returns the first 100 entries. Use skip and limit to read later pages. See the Pagination request.
- The query keeps every chained value, so a second find on the same instance sends the same request again.
Known issue When the Stack carries a live_preview dictionary, find and find_one raise ValueError, TypeError, or IndexError instead of returning entries. Run queries from a second Stack created without live_preview, and read a preview entry with the fetch method on the Entry class.
Example
Basic usage: list the entries of a content type
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').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 entry in result['entries']:
print(entry['title'])Pagination: read every entry, one page at a time
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
page_size = 100
skip = 0
entries = []
try:
while True:
result = stack.content_type('<CONTENT_TYPE_UID>').query().include_count().skip(skip).limit(page_size).find()
entries.extend(result.get('entries', []))
skip += page_size
if skip >= result.get('count', 0):
break
print(len(entries))
except Exception as error:
print('Request failed:', error)find_one
find_one sends the query with the page size set to one and returns the first matching entry.
This method takes no parameters. It reads the content type UID and every chained condition and parameter from the instance.
Returns: dict. The first matching entry.
Validation
- find_one does not check the chain. Like the find method, it raises TypeError if a where value has no JSON form, such as a datetime. It also raises when you create the Stack with a live_preview dictionary.
- find_one 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
- find_one writes 1 to the limit URL parameter, then sends the same request as the find method.
- The response keeps the list shape. Read the entry from result['entries'][0], and check that the list is not empty first.
- The limit value stays on the query. A later find call on the same instance also returns at most one entry, and a limit call before find_one has no effect.
- Combine find_one with order_by_ascending or order_by_descending to choose which entry comes first.
Example
Basic usage: read the most recently updated entry
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().order_by_descending('updated_at').find_one()
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'])
elif result['entries']:
print(result['entries'][0]['title'])
else:
print('No entry matches the query.')include_branch
include_branch asks the API to add the _branch key, which names the branch of each entry, to the response.
This method takes no parameters.
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. include_branch 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 URL parameter to 'true' and makes no request. The find method sends it.
- The API adds the _branch key with the unique ID of the branch. See the include_branch parameter of the Get all entries request. The branch argument of Stack chooses the branch.
- A second call changes nothing. include_branch writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: read the branch of each entry
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').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:
for entry in result['entries']:
print(entry['title'], entry.get('_branch'))include_content_type
include_content_type asks the API to return the content type of the entries along with the response.
This method takes no parameters.
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. include_content_type cannot fail.
- Errors that do occur come from the find() call that follows, not from include_content_type().
- 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_content_type writes two query parameters and makes no request. The find method sends both.
- include_content_type set to 'true'.
- include_global_field_schema set to 'true', so the content type schema carries the schema of each global field it uses. See the include_global_field_schema parameter of the Get a single content type request.
- A second call changes nothing. The SDK writes the same two keys again.
- include_content_type writes the entry option store. The find method copies that store over the URL parameters. On a shared key, this value wins over the value from the param or add_params method. The remove_param method cannot delete it.
Example
Basic usage: read the content type with the entries
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().include_content_type().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 entry in result['entries']:
print(entry['title'])Read the content type from the response
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().include_content_type().find()
print(result.get('content_type'))
except Exception as error:
print('Request failed:', error)include_count
include_count asks the API to add the total number of matching entries to the response.
This method takes no parameters.
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. include_count cannot fail.
- Errors that do occur come from the find() call that follows, not from include_count().
- 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_count sets the include_count URL parameter to 'true' and makes no request. The find method sends it.
- The API returns the entries and their total count. See the Count request.
- Compare the count with the number of entries returned to find out whether more pages remain. See the Pagination request.
- A second call changes nothing. include_count writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: read the total count with the first page
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').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:
for entry in result['entries']:
print(entry['title'])Pagination: compare the count with the page
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().include_count().limit(10).find()
print(result.get('count'), len(result.get('entries', [])))
except Exception as error:
print('Request failed:', error)include_embedded_items
include_embedded_items asks the API to return the entries and assets embedded in the rich text fields of each entry.
This method takes no parameters.
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. include_embedded_items cannot fail.
- Errors that do occur come from the find() call that follows, not from include_embedded_items().
- 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_embedded_items sets the include_embedded_items[] URL parameter to BASE and makes no request. The find method sends it.
- With BASE, the API returns the first level of entries and assets embedded in the Rich Text Editor field, under the _embedded_items key. See the Get information on embedded RTE objects request.
- A second call changes nothing. include_embedded_items writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Limitations
- Does not return items embedded inside embedded items. Send include_embedded_items[] as RECURSIVE through the add_param method instead, and embedded_items_depth to set the number of levels. The API caps the depth at 5. A value set through add_param wins over the BASE value that include_embedded_items writes.
Example
Basic usage: read the embedded items of each entry
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().include_embedded_items().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 entry in result['entries']:
print(entry.get('_embedded_items'))Nested embedded items: send RECURSIVE through add_param
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().add_param('include_embedded_items[]', 'RECURSIVE').add_param('embedded_items_depth', '3').find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)include_fallback
include_fallback asks the API to return the fallback locale content for entries that have no published content in the requested locale.
This method takes no parameters.
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. include_fallback 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 URL parameter to 'true' and makes no request. The find method sends it.
- The API returns the published content of the fallback locale when the locale you named has none. See the include_fallback parameter of the Get all entries request. Chain the locale method to name the locale.
- A second call changes nothing. include_fallback writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: read French content, or the fallback locale
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').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 entry in result['entries']:
print(entry['title'])include_metadata
include_metadata asks the API to add the metadata of each entry to the response.
This method takes no parameters.
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. include_metadata 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 URL parameter to 'true' and makes no request. The find method sends it.
- The API returns the metadata under the _metadata key of each entry, with one key per extension UID. See the Get all entries request.
- A second call changes nothing. include_metadata writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: read the metadata of each entry
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').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 entry in result['entries']:
print(entry['title'], entry.get('_metadata'))include_reference
include_reference asks the API to return the entries in the named reference fields in full, instead of as UIDs.
| Name | Type | Description |
|---|---|---|
| field_uid (required) | str | list[str] | Reference field UID, or a list of them, to resolve. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation of the field UID. include_reference does not check that the field exists or that it is a reference field.
- A value that is not a str or a list, such as None or a tuple, records nothing and raises nothing. The request then goes out without include[], and every reference field holds UIDs only.
- Calling include_reference() without an argument raises TypeError, because field_uid is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from include_reference().
- 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_reference writes the include[] query parameter and makes no request. The find method sends it.
- A list sends one include[] pair per item.
- A second call replaces the first value. It does not add to it, so pass every field in one list.
- include_reference writes the entry option store. The find method copies that store over the URL parameters. On a shared key, this value wins over the value from the param or add_params method. The remove_param method cannot delete it.
- Without include_reference, a reference field holds only the UIDs of the referenced entries. See the Include Reference section of the API reference.
- To keep only some fields of a referenced entry, send only[<reference_field_uid>][] through the add_param method.
Example
Basic usage: resolve one reference field
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().include_reference('author').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 entry in result['entries']:
print(entry['title'])Several fields: pass a list
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().include_reference(['author', 'categories']).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)include_reference_content_type_uid
include_reference_content_type_uid asks the API to add the content type UID to each referenced entry in the response.
This method takes no parameters.
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. include_reference_content_type_uid cannot fail.
- Errors that do occur come from the find() call that follows, not from include_reference_content_type_uid().
- 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_reference_content_type_uid sets the include_reference_content_type_uid query parameter to 'true' and makes no request. The find method sends it.
- A second call changes nothing. The SDK writes the same key again.
- include_reference_content_type_uid writes the entry option store. The find method copies that store over the URL parameters. On a shared key, this value wins over the value from the param or add_params method. The remove_param method cannot delete it.
- Chain the include_reference method as well when you need the referenced entries in full.
Example
Basic usage: resolve a reference and its content type UID
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().include_reference('author').include_reference_content_type_uid().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 entry in result['entries']:
print(entry['title'])limit
limit sets the maximum number of entries the response returns.
| Name | Type | Description |
|---|---|---|
| limit_count (required) | int | Maximum number of entries to return. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. limit converts the value with str(), so zero, a negative number, or None reaches the request as text.
- The API accepts positive integers only. For limit=0, an empty value, or a non-numeric value, it returns the default number of entries rather than every entry. See the Limit request.
- Calling limit() without an argument raises TypeError, because limit_count is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from limit().
- 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. limit writes the limit URL parameter and makes no request. The find method sends it.
- Without limit, the API returns the first 100 entries. See the Pagination request.
- A second call replaces the first value. The find_one method writes 1 over it.
- limit writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: read at most five entries
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().limit(5).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 entry in result['entries']:
print(entry['title'])locale
locale sets the locale the query reads, so the response carries content published in that locale.
| Name | Type | Description |
|---|---|---|
| locale (required) | str | Locale code to read, for example fr-fr. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. locale keeps the value as given, so an empty string or a code the stack does not have reaches the request. A None value reaches the request as the text None.
- Calling locale() without an argument raises TypeError, because locale is a required positional parameter.
- 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 writes the locale query parameter and makes no request. The find method sends it.
- A second call replaces the first value.
- locale writes the entry option store. The find method copies that store over the URL parameters. On a shared key, this value wins over the value from the param or add_params method. The remove_param method cannot delete it.
- The Delivery API returns only content published in the locale you name. See the locale parameter of the Get all entries request.
- When the content has no published version in that locale, chain the include_fallback method to read the fallback locale instead.
Example
Basic usage: read content in French
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').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 entry in result['entries']:
print(entry['title'])Locale with fallback: read the fallback locale when French has no published version
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().locale('fr-fr').include_fallback().find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)only
only limits each entry in the response to one top-level field.
| Name | Type | Description |
|---|---|---|
| field_uid (required) | str | UID of the top-level field to keep. |
Returns: Query. The same query, for chaining.
Validation
- only accepts one field UID as a string. It raises KeyError if field_uid is any other non-null type, such as a list, because only stores a single string under the only[BASE][] key.
- A None value records nothing and raises nothing, so the response carries every field.
- only does not check that the field exists. An unknown field UID reaches the request as given.
- Calling only() without an argument raises TypeError, because field_uid is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from only().
- 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. only writes the only[BASE][] query parameter and makes no request. The find method sends it.
- A second call replaces the first field. only holds one field UID at a time.
- only writes the entry option store. The find method copies that store over the URL parameters. On a shared key, this value wins over the value from the param or add_params method. The remove_param method cannot delete it.
- BASE stands for the top-level fields of the content type schema. See the Only operator section of the API reference.
Limitations
- Does not take more than one field. To keep several fields, pass a list under the same key through the add_param method, for example add_param('only[BASE][]', ['title', 'url']). The find method sends one only[BASE][] pair per list item.
- Does not apply to the fields of a referenced entry. The API takes only[<reference_field_uid>][] for those. Send it through the add_param method together with the include_reference method.
Example
Basic usage: keep only the title field
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().only('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 entry in result['entries']:
print(entry['title'])Several fields: pass a list through add_param
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().add_param('only[BASE][]', ['title', 'url']).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)order_by_ascending
order_by_ascending sorts the entries by one field in ascending order.
| Name | Type | Description |
|---|---|---|
| key (required) | str | UID of the field to sort by. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. order_by_ascending converts the value with str(), so an unknown field UID or None reaches the request as text.
- Calling order_by_ascending() without an argument raises TypeError, because key is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from order_by_ascending().
- 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. order_by_ascending writes the asc URL parameter and makes no request. The find method sends it. See the Order by asc request.
- A second call replaces the first field. The request sorts by one field per direction.
- order_by_ascending and the order_by_descending method write different keys, so a chain that calls both sends both asc and desc.
- order_by_ascending writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: sort entries by title
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').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 entry in result['entries']:
print(entry['title'])order_by_descending
order_by_descending sorts the entries by one field in descending order.
| Name | Type | Description |
|---|---|---|
| key (required) | str | UID of the field to sort by. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. order_by_descending converts the value with str(), so an unknown field UID or None reaches the request as text.
- Calling order_by_descending() without an argument raises TypeError, because key is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from order_by_descending().
- 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. order_by_descending writes the desc URL parameter and makes no request. The find method sends it. See the Order by desc request.
- A second call replaces the first field. The request sorts by one field per direction.
- order_by_descending and the order_by_ascending method write different keys, so a chain that calls both sends both asc and desc.
- order_by_descending writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: sort entries by update time
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().order_by_descending('updated_at').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 entry in result['entries']:
print(entry['title'])param
param adds one URL query parameter to the request, converting the value to a string.
| Name | Type | Description |
|---|---|---|
| key (required) | str | Query parameter name. |
| value (required) | Any | Value to send. param converts it to a string. |
Returns: Query. The same query, for chaining.
Validation
- param raises KeyError if key or value is None, because a query parameter needs both a name and a value.
- param converts every value with str(). A list therefore goes out as its Python text, such as ['title', 'url'], rather than as repeated keys. Use the add_params or add_param method for a list value.
- Calling param() with fewer than two arguments raises TypeError, because param takes key and value as positional parameters with no default.
- Errors that do occur come from the find() call that follows, not from param().
- 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. param writes the pair to the URL parameters and makes no request. The find method sends it.
- A second call with the same key replaces the value.
- param writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
- The find method writes the conditions from where and query under the query key when there are any. A param('query', ...) value survives only on a query with no such condition.
Example
Basic usage: resolve taxonomy terms
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().param('include_taxonomy_terms', 'true').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 entry in result['entries']:
print(entry['title'])Raw condition: send a JSON query string
import json
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
condition = json.dumps({'price_in_usd': {'$lt': 600}})
result = stack.content_type('<CONTENT_TYPE_UID>').query().param('query', condition).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)query
query adds a condition that matches entries whose field equals a string value.
| Name | Type | Description |
|---|---|---|
| key (required) | str | UID of the field to test. |
| value (required) | Any | Value to match. query converts it to a string. |
Returns: Query. The same query, for chaining.
Validation
- query raises KeyError if key or value is None, because a condition needs both a field and a value.
- query converts every value with str(). A number therefore matches as a string, and a dictionary goes out as its Python text rather than as an operator. Use the where method for a number, a list, or an operator.
- Calling query() with fewer than two arguments raises TypeError, because query takes key and value as positional parameters with no default.
- 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 one key to the same condition object that the where method writes, and makes no request. The find method serializes that object to JSON and sends it as the query parameter. See the Equals Operator request.
- A second call on the same key replaces the value. A where call on the same field replaces it too.
- The query_operator method empties the condition object, so a query call before it has no effect.
Example
Basic usage: match entries by title
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().query('title', 'Redmi 3S').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 entry in result['entries']:
print(entry['title'])Combined with where: both conditions share one condition object
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().query('color', 'Gold').where('price_in_usd', QueryOperation.IS_LESS_THAN, fields=600).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)query_operator
query_operator joins the conditions of other queries with $and or $or.
| Name | Type | Description |
|---|---|---|
| query_type (required) | QueryType | Operator that joins the conditions. |
| query_objects (required) | Query | Queries whose conditions to join, passed as separate arguments. |
Returns: Query. The same query, for chaining.
Validation
- query_operator raises AttributeError if query_type is not a QueryType member, such as the string '$and', because it reads the member's value.
- It raises AttributeError if an item in query_objects is not a Query, such as a dictionary, because it reads the parameters attribute of each item.
- A call with no query_objects does not raise. It sends an empty list under the operator.
- Calling query_operator() without an argument raises TypeError, because query_type is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from query_operator().
- 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_operator reads the condition object of each query you pass, empties this query's own condition object, and writes {"$and": [...]} or {"$or": [...]} as JSON under the query URL parameter. It makes no request.
- query_operator reads only the conditions that the where and query methods wrote on each sub-query. Other settings on a sub-query, such as limit or locale, do not carry over. Set those on this query.
- A where or query call on this query after query_operator replaces the whole operator condition, because find writes a non-empty condition object under the same query key. To add a condition to an $and, pass it as one more sub-query instead.
- Import QueryType from contentstack.query. The package root does not export it. The table below lists its members:
| Member | Operator sent | API reference |
|---|---|---|
| QueryType.AND | $and | AND Operator |
| QueryType.OR | $or | OR Operator |
Example
Basic usage: match entries that meet either condition
import contentstack
from contentstack.basequery import QueryOperation
from contentstack.query import QueryType
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
content_type = stack.content_type('<CONTENT_TYPE_UID>')
gold = content_type.query().where('color', QueryOperation.EQUALS, fields='Gold')
black = content_type.query().where('color', QueryOperation.EQUALS, fields='Black')
try:
result = content_type.query().query_operator(QueryType.OR, gold, black).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 entry in result['entries']:
print(entry['title'])AND with paging: set pagination on the outer query
import contentstack
from contentstack.basequery import QueryOperation
from contentstack.query import QueryType
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
content_type = stack.content_type('<CONTENT_TYPE_UID>')
cheap = content_type.query().where('price_in_usd', QueryOperation.IS_LESS_THAN, fields=600)
gold = content_type.query().where('color', QueryOperation.EQUALS, fields='Gold')
try:
result = content_type.query().query_operator(QueryType.AND, cheap, gold).limit(10).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)remove_param
remove_param deletes one URL query parameter from the query.
| Name | Type | Description |
|---|---|---|
| key (required) | str | Name of the query parameter to delete. |
Returns: Query. The same query, for chaining.
Validation
- remove_param raises ValueError if key is None, because it needs a name to delete.
- A key that the query does not hold does not raise. remove_param changes nothing.
- Calling remove_param() without an argument raises TypeError, because key is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from remove_param().
- 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. remove_param deletes the key from the URL parameters and makes no request.
- It deletes values that param, add_params, limit, skip, include_count, and the other URL parameter methods wrote.
- It cannot delete a value from the entry option store, such as one from locale, only, or add_param, or a condition from where or query. Build a new query instead.
Example
Basic usage: drop the count before the next request
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().include_count().remove_param('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:
for entry in result['entries']:
print(entry['title'])search
search sends a free-text value in the typeahead query parameter. Version 1.7.0 of the SDK deprecated it.
| Name | Type | Description |
|---|---|---|
| value (required) | str | Text to search for. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. A None value records nothing and raises nothing.
- Calling search() without an argument raises TypeError, because value is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from search().
- 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
- search issues a UserWarning on every call. The warning names version 1.7.0 as the release that deprecated the method.
- Client-side only. search writes the typeahead URL parameter and makes no request. The find method sends it.
- A second call replaces the first value.
- search writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Limitations
- Does not have a regex replacement on this class, although the deprecation warning names one. Use the where method with QueryOperation.MATCHES instead. See the Search by Regex request.
Example
Basic usage: send a search value
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().search('phone').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 entry in result['entries']:
print(entry['title'])Replacement: match a regular expression with where
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().where('title', QueryOperation.MATCHES, fields='^Blog').find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)skip
skip sets the number of matching entries the API skips before it starts the page.
| Name | Type | Description |
|---|---|---|
| skip_count (required) | int | Number of entries to skip. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. skip converts the value with str(), so a negative number, a string, or None reaches the request as text.
- Calling skip() without an argument raises TypeError, because skip_count is a required positional parameter.
- Errors that do occur come from the find() call that follows, not from skip().
- 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. skip writes the skip URL parameter and makes no request. The find method sends it.
- A second call replaces the first value.
- Combine skip with the limit method to read one page at a time. See the Skip and Pagination requests.
- skip writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: read the second page of 10 entries
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().skip(10).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 entry in result['entries']:
print(entry['title'])tags
tags sends a comma-separated list of tags in the tags query parameter, to match entries that carry those tags.
| Name | Type | Description |
|---|---|---|
| tags (required) | str | Tags to match, passed as separate arguments. |
Returns: Query. The same query, for chaining.
Validation
- tags raises TypeError if any argument is not a string, because it joins the arguments with commas.
- A call with no arguments does not raise. It sends an empty tags parameter.
- tags does not check that a tag exists.
- Errors that do occur come from the find() call that follows, not from tags().
- 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. tags joins the arguments with commas into the tags URL parameter and makes no request. The find method sends it.
- A second call replaces the first list. Pass every tag in one call.
- tags writes the URL parameters. A value for the same key from the add_param method wins over it, and the remove_param method can delete it.
Example
Basic usage: match entries by one tag
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().tags('featured').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 entry in result['entries']:
print(entry['title'])Several tags: pass them as separate arguments
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().tags('featured', 'sale').find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)where
where adds a condition that matches entries by the value of one field.
| Name | Type | Description |
|---|---|---|
| field_uid (required) | str | UID of the field to test. |
| query_operation (required) | QueryOperation | Operator to apply to the field. |
| fields | Any | Value to compare the field with. |
Returns: Query. The same query, for chaining.
Validation
- When field_uid or query_operation is None, where records nothing and raises nothing, so the condition never reaches the request.
- where raises AttributeError if query_operation is not a QueryOperation member, such as the string '$lt', because where reads the member's name and value.
- There is no check on fields. The SDK places the value in the condition as given. A value that JSON cannot encode, such as a datetime, raises TypeError on the find() call.
- Calling where() with fewer than two arguments raises TypeError, because where takes field_uid and query_operation as 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 one key to the condition object of the query and makes no request. The find method serializes that object to JSON and sends it as the query parameter.
- Calls on different fields add keys to the same condition object. A second call on the same field replaces the condition for that field. Use the query_operator method to apply two conditions to one field.
- With EQUALS, the condition is the value itself, and a one-item list becomes that item. Every other operator writes {"<operator>": fields}.
- Import QueryOperation from contentstack.basequery. The package root does not export it. The table below lists its members:
| Member | Operator sent | Pass in fields | API reference |
|---|---|---|---|
| EQUALS | None, the value itself | A value | Equals Operator |
| NOT_EQUALS | $ne | A value | Not-equals Operator |
| INCLUDES | $in | A list of values | Array Equals Operator |
| EXCLUDES | $nin | A list of values | Array Not-equals Operator |
| IS_LESS_THAN | $lt | A value | Less Than |
| IS_LESS_THAN_OR_EQUAL | $lte | A value | Less Than Or Equal To |
| IS_GREATER_THAN | $gt | A value | Greater Than |
| IS_GREATER_THAN_OR_EQUAL | $gte | A value | Greater Than Or Equal To |
| EXISTS | $exists | True or False | Exists |
| MATCHES | $regex | A regular expression string | Search by Regex |
- To test a field of a referenced entry, pass the reference search operator as the value with EQUALS, for example fields={'$in_query': {'title': 'Apple Inc.'}}. See the Reference Search Equals request. This form replaces the where_in method, whose condition never reaches the API.
- The query_operator method empties the condition object. A where call before it has no effect, and a where call after it replaces the whole operator condition.
Example
Basic usage: match entries by title
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().where('title', QueryOperation.EQUALS, fields='Redmi 3S').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 entry in result['entries']:
print(entry['title'])Several conditions: a list operator and a comparison
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().where('color', QueryOperation.INCLUDES, fields=['Gold', 'Black']).where('price_in_usd', QueryOperation.IS_LESS_THAN, fields=600).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)Pattern and presence: match a regular expression on entries that have a field
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().where('title', QueryOperation.MATCHES, fields='^Blog').where('url', QueryOperation.EXISTS, fields=True).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)Reference search: match entries by a field of the referenced entry
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().where('brand', QueryOperation.EQUALS, fields={'$in_query': {'title': 'Apple Inc.'}}).find()
print(result['entries'])
except Exception as error:
print('Request failed:', error)where_in
where_in builds a condition that matches entries whose reference field points to entries that meet another query.
| Name | Type | Description |
|---|---|---|
| key (required) | str | UID of the reference field to test. |
| query_object (required) | Query | Query whose conditions the referenced entries meet. |
Returns: Query. The same query, for chaining.
Validation
- where_in raises ValueError if key is not a string or query_object is not a Query. It needs both to build the condition.
- Calling where_in() with fewer than two arguments raises TypeError, because where_in takes key and query_object as positional parameters with no default.
- Errors that do occur come from the find() call that follows, not from where_in().
- 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_in stores {"<key>": {"$in_query": <conditions of query_object>}} under the query URL parameter and makes no request.
- The API takes this condition as the $in_query operator. See the Reference Search Equals request.
Known issue The condition from where_in never reaches the API. The find method sends only the field name as the query value, or replaces the condition when the query has a where condition. Pass the operator through the where method instead: where('<key>', QueryOperation.EQUALS, fields={'$in_query': <inner query>.parameters}).
Example
Workaround: send the reference condition through where
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
brand = stack.content_type('<REFERENCED_CONTENT_TYPE_UID>').query().where('title', QueryOperation.EQUALS, fields='Apple Inc.')
try:
result = stack.content_type('<CONTENT_TYPE_UID>') \
.query() \
.where('brand', QueryOperation.EQUALS, fields={'$in_query': brand.parameters}) \
.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 entry in result['entries']:
print(entry['title'])Edge case: the where_in call itself
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
brand = stack.content_type('<REFERENCED_CONTENT_TYPE_UID>').query().where('title', QueryOperation.EQUALS, fields='Apple Inc.')
try:
# Known issue: this request sends query=brand, without the reference condition.
result = stack.content_type('<CONTENT_TYPE_UID>').query().where_in('brand', brand).find()
print(result.get('entries'))
except ValueError as error:
# Fires when key is not a string or brand is not a Query
print('Invalid arguments:', error)
except Exception as error:
print('Request failed:', error)where_not_in
where_not_in builds a condition that matches entries whose reference field points to entries that do not meet another query.
| Name | Type | Description |
|---|---|---|
| key (required) | str | UID of the reference field to test. |
| query_object (required) | Query | Query whose conditions the referenced entries fail. |
Returns: Query. The same query, for chaining.
Validation
- where_not_in raises ValueError if key is not a string or query_object is not a Query. It needs both to build the condition.
- Calling where_not_in() with fewer than two arguments raises TypeError, because where_not_in takes key and query_object as positional parameters with no default.
- Errors that do occur come from the find() call that follows, not from where_not_in().
- 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_not_in stores {"<key>": {"$nin_query": <conditions of query_object>}} under the query URL parameter and makes no request.
- The API takes this condition as the $nin_query operator. See the Reference Search Not-equals request.
Known issue The condition from where_not_in never reaches the API. The find method sends only the field name as the query value, or replaces the condition when the query has a where condition. Pass the operator through the where method instead: where('<key>', QueryOperation.EQUALS, fields={'$nin_query': <inner query>.parameters}).
Example
Workaround: send the reference condition through where
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
brand = stack.content_type('<REFERENCED_CONTENT_TYPE_UID>').query().where('title', QueryOperation.EQUALS, fields='Apple Inc.')
try:
result = stack.content_type('<CONTENT_TYPE_UID>') \
.query() \
.where('brand', QueryOperation.EQUALS, fields={'$nin_query': brand.parameters}) \
.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 entry in result['entries']:
print(entry['title'])Edge case: the where_not_in call itself
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
brand = stack.content_type('<REFERENCED_CONTENT_TYPE_UID>').query().where('title', QueryOperation.EQUALS, fields='Apple Inc.')
try:
# Known issue: this request sends query=brand, without the reference condition.
result = stack.content_type('<CONTENT_TYPE_UID>').query().where_not_in('brand', brand).find()
print(result.get('entries'))
except ValueError as error:
# Fires when key is not a string or brand is not a Query
print('Invalid arguments:', error)
except Exception as error:
print('Request failed:', error)