Contentstack Delivery Python SDK
Overview
This reference covers the public API of the contentstack package, with one page per class. Use it to look up parameters, return types, validation behavior, and worked examples for every method you reach from contentstack.Stack.
Before you begin This reference assumes you have installed and initialized the SDK. If you have not, complete the Get Started with Python SDK guide first. This SDK requires Python 3.6 or later, and the package lists support for Python 3.6 through 3.10. This reference documents version 2.8.1, and the changelog lists behavior changes between releases.
Minimum Working Example
The following snippet creates a stack, reads one entry, and prints its title. It handles a network failure and an API rejection separately.
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>').fetch()
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['entry']['title'])SDK Structure
The SDK uses a builder pattern. contentstack.Stack takes your credentials, and each factory call from it returns an object for a narrower scope, such as one content type or one entry. Chainable methods on that object add a modifier and return the same object. A terminal call sends the request: fetch for a single item, find for a list, and find_one for the first match of a query. Every chain starts at the Stack, and every object a stack creates shares that stack's connection and request headers.
A chainable method that stores its value without checking it raises nothing for an invalid value, so the failure appears on the terminal call instead. A missing positional argument still raises TypeError at the call. The Validation section of each method page states which terminal call returns or raises its errors.
Besides fetch and find, the three kinds of call below end a chain:
- The sync methods of Stack (sync_init, pagination, and sync_token) send the request themselves.
- The locales, ancestors, and descendants methods of Term each send one request.
- The get_url method of ImageTransform returns a string and sends no request.
Class Overview
Set up the SDK.
| Class | Role | Accessed via |
|---|---|---|
| Stack | One stack, environment, region, and branch, and the start of every chain. | contentstack.Stack(...) |
Read content types, entries, and global fields.
| Class | Role | Accessed via |
|---|---|---|
| ContentType | One content type and its schema, or the list of content types. | stack.content_type(uid) |
| Entry | One published entry of a content type. | content_type.entry(uid) |
| Query | A filtered list of the published entries of one content type. | content_type.query() |
| Variants | One entry, or the entries of a content type, with the content of entry variants. | entry.variants(uid) |
| GlobalField | One global field and its schema, or the list of global fields. | stack.global_field(uid) |
Read assets and images.
| Class | Role | Accessed via |
|---|---|---|
| Asset | One published asset. | stack.asset(uid) |
| AssetQuery | The list of published assets in a stack. | stack.asset_query() |
| ImageTransform | An image URL with Image Delivery API parameters. It sends no request. | stack.image_transform(url, ...) |
Read taxonomies.
| Class | Role | Accessed via |
|---|---|---|
| Taxonomy | One published taxonomy, or a TaxonomyQuery that lists taxonomies and filters entries by term. | stack.taxonomy(uid) |
| Term | One published term of a taxonomy and its hierarchy. | taxonomy.term(uid) |
| TermQuery | The list of published terms of one taxonomy. | taxonomy.term() |
Task Index
| Task | Start here | Class |
|---|---|---|
| Fetch one entry by UID | fetch | Entry |
| Filter entries by a field value | where | Query |
| Page through the entries of a content type | skip | Query |
| Return referenced entries in full | include_reference | Query |
| Read an entry in another locale | locale | Entry |
| Read an entry with variant content | fetch | Variants |
| List the published assets in the stack | find | AssetQuery |
| Read one asset with its image dimensions | include_dimension | Asset |
| Filter entries by a taxonomy term and the terms below it | equal_and_below | Taxonomy |
| Sync all published content, then only what changed | sync_init | Stack |
| Build a resized or converted image URL | get_url | ImageTransform |
| Set the region, branch, timeout, or retry policy | Stack | Stack |
Key Usage Patterns
Each example below is complete, with its own import and stack, so you can run it as a script.
Filter entries by a field and resolve their references
import contentstack
from contentstack.basequery import QueryOperation
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# query() opens the filter. find() sends the request.
result = (
stack.content_type('<CONTENT_TYPE_UID>')
.query()
.where('price_in_usd', QueryOperation.IS_LESS_THAN, fields=600)
.include_reference('brand')
.order_by_descending('updated_at')
.limit(10)
.find()
)
for entry in result.get('entries', []):
print(entry['title'], entry.get('brand'))
except Exception as error:
print('Request failed:', error)Page through every entry of a content type
The SDK sends one request per find call and does not request further pages. The following loop combines skip and limit, and stops when it reaches the count that include_count adds.
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
page_size = 25
entries = []
try:
while True:
# A new query for each page, with the offset set to the entries read so far.
result = (
stack.content_type('<CONTENT_TYPE_UID>')
.query()
.skip(len(entries))
.limit(page_size)
.include_count()
.find()
)
page = result.get('entries', [])
entries.extend(page)
if not page or len(entries) >= result.get('count', 0):
break
print('read', len(entries), 'entries')
except Exception as error:
print('Request failed:', error)Filter entries by a taxonomy term and the terms below it
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
# stack.taxonomy() with no UID filters entries across taxonomies.
result = (
stack.taxonomy()
.equal_and_below('taxonomies.<TAXONOMY_UID>', '<TERM_UID>', levels=2)
.find()
)
for entry in result.get('entries', []):
print(entry['uid'], entry['title'])
except Exception as error:
print('Request failed:', error)Sync all published content, then only what changed
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.sync_init()
items = result.get('items', [])
# Each batch holds up to 100 records. Follow pagination_token to the last batch.
while 'pagination_token' in result:
result = stack.pagination(result['pagination_token'])
items.extend(result.get('items', []))
print('published items:', len(items))
# Store sync_token, then pass it on the next run to receive only the changes.
if 'sync_token' in result:
changes = stack.sync_token(result['sync_token'])
print('changed since the first sync:', len(changes.get('items', [])))
except Exception as error:
print('Request failed:', error)Build a resized image URL from an asset
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.asset('<ASSET_UID>').fetch()
asset = result.get('asset')
if asset:
# image_transform builds the URL and sends no request.
thumbnail = stack.image_transform(asset['url'], width=320, format='webp').get_url()
print(thumbnail)
except Exception as error:
print('Request failed:', error)Tell a network failure from an API rejection
import contentstack
from contentstack.controller import RequestError
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>').fetch()
except RequestError as error:
# No response arrived. The details sit in args[0], a dictionary, not in attributes.
print('Network failure:', error.args[0]['error'])
else:
if 'error_code' in result:
# The API answered and rejected the request, for example 141 for an unknown entry UID.
print('Delivery API error:', result['error_code'], result['error_message'])
for field, messages in result.get('errors', {}).items():
print(field, messages)
else:
print(result['entry']['title'])SDK-Wide Notes
| Concern | Behavior | Default when unset |
|---|---|---|
| Authentication | contentstack.Stack takes api_key, delivery_token, and environment, and sends them as the api_key, access_token, and environment headers on every request. No other class takes credentials. | Not applicable. The constructor raises PermissionError when any of the three is None or an empty string. |
| API rejections | A call that sends a request returns an API rejection as an ordinary dictionary with error_code, error_message, and errors keys, and no error key. Check the result for error_code even inside a try block. | Not applicable. |
| Network failures | A timeout, DNS error, or dropped connection raises RequestError. Import it from contentstack.controller, because the package root does not export it. Its attributes stay unset, so read the details from exc.args[0]. | Not applicable. |
| Regions and endpoints | Pass region to contentstack.Stack as a ContentstackRegion member: US, EU, AU, AZURE_NA, AZURE_EU, GCP_NA, or GCP_EU. With the default host, a string such as 'eu' raises AttributeError. A custom host replaces the region lookup. | ContentstackRegion.US. |
| Branches | Pass branch to contentstack.Stack. The SDK sends it as the branch header on every request. | None, so the SDK sends no branch header. |
| Rate limiting and retry | This SDK automatically retries on 408 and 429 with configurable delay and attempt limits. The default sends the initial request plus up to five retries, with no delay between them. Pass a retry_strategy to change it, as Implement Retry Mechanism with Python Delivery SDK describes. | Retry(total=5, backoff_factor=0, status_forcelist=[408, 429]). |
| Timeouts | Pass timeout to contentstack.Stack, in seconds. The SDK applies it to every request. | 30 seconds. |
| Shared request headers | Every object you build from one Stack shares the header dictionary of that stack. A method that changes a header, such as the environment method of Entry, changes every later request from that stack. | The headers the constructor set from your arguments. |
Warning This SDK requires the delivery token of the environment you pass. The constructor checks only that delivery_token is not empty, so a management token passes that check. The API then rejects the first request, and the SDK returns that rejection as a dictionary with an error_code key instead of raising. Pass a preview token inside live_preview, as its preview_token key.
SDK Limitations
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Query entries of several content types in one request | No | Each Query belongs to one content type. Run one query per content type and merge the results in your code. |
| Raise an exception on an API rejection | No | Check the returned dictionary for an error_code key, as in the Minimum Working Example above. |
| Read every page of a list in one call | No | Each find call and each sync call returns one page. Loop with skip and limit, as in Key Usage Patterns above. For a sync, pass each pagination_token to the pagination method. The AssetQuery class page gives the alternative for assets. |
| Scope an environment to one object | No | Every object shares the environment header of its stack. Create one Stack per environment, each with its own delivery token. |
| Back off between retries by default | No | Pass a retry_strategy with a non-zero backoff_factor to contentstack.Stack. |