Stack

View as Markdown

Stack

A stack holds the content and assets of one project. Stack is the entry point to this SDK: create it once with your credentials, then call its factory methods to reach every other class. Use this class to

  • connect to one stack, environment, region, and branch
  • open content types, assets, global fields, and taxonomies
  • synchronize published content through the Sync API
  • build an image URL with resize, crop, and format parameters

contentstack.Stack(api_key, delivery_token, environment, **options) takes the arguments below:

NameTypeDescription
api_keystrAPI key of the stack. Required.
delivery_tokenstrDelivery token of the environment. Required.
environmentstrEnvironment to read published content from. Required.
hoststrDelivery host. Defaults to cdn.contentstack.io, which makes the SDK pick the host for region.
versionstrAPI version segment of the base URL. Defaults to v3.
regionContentstackRegionRegion of the stack. Defaults to ContentstackRegion.US.
timeoutintSeconds each request waits for the server. Defaults to 30.
retry_strategyRetryurllib3 retry policy for every request. Defaults to Retry(total=5, backoff_factor=0, status_forcelist=[408, 429]).
live_previewdictLive preview configuration. Defaults to None.
branchstrBranch to read content from. Defaults to None.
early_accesslistEarly access feature names to send. Defaults to None.
loggerLoggerLogger the instance holds. Defaults to the contentstack.stack module logger.
  • Stack raises PermissionError when api_key, delivery_token, or environment is None or an empty string. The check runs in the constructor, before any request.
  • region takes a ContentstackRegion member: US, EU, AU, AZURE_NA, AZURE_EU, GCP_NA, or GCP_EU. Import the enum with from contentstack.stack import ContentstackRegion.
  • The SDK holds logger on the instance and writes no log records to it.

Warning Pass region as a ContentstackRegion member, not as a string. With the default host, region='eu' raises AttributeError in the constructor, because the SDK reads region.value.

Class-Level Notes

Region and host.

  • While host keeps its default value, the SDK looks up the delivery host for region in the regions.json file that ships with the package. For example, ContentstackRegion.EU resolves to eu-cdn.contentstack.com.
  • A host you pass replaces that lookup. The SDK uses the string as given and ignores region for delivery requests.
  • The base URL of every request is https://<host>/<version>. Read it from stack.endpoint.

Headers.

  • The constructor sends your credentials as the api_key, access_token, and environment headers on every request. No other class takes credentials.
  • branch adds a branch header. early_access adds an x-header-ea header containing the list joined with a comma and a space.
  • Every object you build from a stack shares the header dictionary of that stack. A method that changes it, such as the environment method of Entry, changes every later request from the same stack.
  • Known issue: In 2.8.1, the remove_environment method of Entry or Asset makes later calls on the same stack raise KeyError. This affects the sync methods and the fetch and find methods of ContentType and GlobalField. Use a separate Stack for the objects you call remove_environment on.

Warning Pass early_access as a list of strings. The SDK joins the value item by item, so the string 'taxonomy' sends the header value t, a, x, o, n, o, m, y.

Settings stay fixed after construction.

  • The constructor builds the headers, the base URL, the timeout, and the retry policy once, and hands them to the connection object.
  • If you assign a new value to stack.api_key, stack.timeout, or stack.endpoint later, the requests do not change. Create a second Stack for different credentials, a different host, or a different timeout.

Live preview.

  • The SDK acts on live_preview only when the dictionary has a truthy enable key.
  • For a preview request, include management_token or preview_token in the dictionary. The SDK reads no other token key.
  • With a truthy enable and no host, the SDK writes the content management host of the region into the dictionary. For ContentstackRegion.US, that host is api.contentstack.io.
  • When the dictionary has preview_token, the constructor adds a preview_token header to every request.
  • The live_preview_query method sets the content type, entry, and hash to preview.
  • Known issue: In 2.8.1, any live_preview dictionary, including {'enable': False}, makes the fetch method of Entry raise ValueError until live_preview_query has named that entry's content type. Keep a second Stack without live_preview for ordinary delivery requests.

Sync.

  • sync_init, pagination, and sync_token call the Synchronization endpoint and share one parameter dictionary on the instance.
  • The SDK does not page through sync results. Pass the pagination_token from each response to pagination until a response contains a sync_token, then store the sync_token for the next sync_token call.

How errors reach you.

  • The SDK raises an exception only for network failures (timeout, DNS error, dropped connection).
  • An API-level rejection returns as a normal dictionary with an error_code key. It does not raise an exception. A sync rejection lists its messages per field under an errors key, for example result['errors']['sync_token'].
  • Check the result for those keys even inside a try block.

Rate limiting and retry.

  • This SDK retries 408 and 429 responses automatically: the initial request plus up to five retries, with no delay between them, because the default backoff_factor is 0.
  • A rate limit needs time to reset. Pass a retry_strategy with a non-zero backoff_factor if you expect 429 responses.

Capability Matrix

CapabilitySupportedNotes / Alternative
Raise an exception on an API rejectionNoCheck the returned dictionary for error_code, or errors on a sync call
Page through sync results automaticallyNoPass each pagination_token to pagination
region as a stringNoPass a ContentstackRegion member, such as ContentstackRegion.EU
Change credentials, host, or timeout after constructionNoCreate a second Stack
Back off between retries by defaultNoPass a retry_strategy with a non-zero backoff_factor

Method Index

The groups below follow what you want to reach. Every method is available on every Stack instance.

Open a content module. Available on every instance. These return an object and make no request. The request runs on the fetch or find call you chain to it.

Method NameReturnsDescription
content_typeA new ContentType for the given UID.Opens one content type, or the list of them.
global_fieldA new GlobalField for the given UID.Opens one global field, or the list of them.
taxonomyA new Taxonomy for the given UID, or a TaxonomyQuery when you omit it.Opens one taxonomy, or a query across taxonomies.
assetA new Asset for the given UID.Opens one asset by its UID.
asset_queryA new AssetQuery for the assets in the stack.Opens a query across the assets in the stack.
image_transformA new ImageTransform for the given image URL.Holds an image URL and its transformation parameters.

Synchronize content. Available on every instance. These send the request and return the parsed response.

Method NameReturnsDescription
sync_initThe first batch of published entries and assets.Starts a sync of the published content.
paginationThe next batch of sync items.Continues a sync with a pagination token.
sync_tokenThe content changed since the last completed sync.Fetches the changes since a sync token.

Configure live preview. Available on every instance. It has an effect only when live_preview sets enable.

Method NameReturnsDescription
live_preview_queryThe same stack, for chaining.Sets the content type, entry, and hash to preview.

Read the configuration. Available on every instance. These seven are properties, so read them without parentheses.

Method NameReturnsDescription
get_api_keyThe API key the stack was created with.Reads the API key.
get_delivery_tokenThe delivery token the stack was created with.Reads the delivery token.
get_environmentThe environment the stack was created with.Reads the environment.
get_branchThe branch the stack was created with.Reads the branch.
get_early_accessThe early access list the stack was created with.Reads the early access feature names.
get_live_previewThe live preview dictionary the stack holds.Reads the live preview configuration.
get_headersThe header dictionary the stack sends.Reads the request headers.

Class-Level Snippet

This snippet creates a stack for the EU region on a branch, reads one entry, and builds a resized image URL.

import contentstack
from contentstack.stack import ContentstackRegion

stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    region=ContentstackRegion.EU,
    branch='main',
    timeout=15,
)

print('base URL:', stack.endpoint)

try:
    # content_type and entry make no request. fetch sends it.
    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'])

# image_transform builds a URL and makes no request.
thumbnail = stack.image_transform(
    'https://images.contentstack.io/v3/assets/<API_KEY>/<ASSET_UID>/<FILE_UID>/hero.jpg',
    width=320,
    format='webp',
).get_url()
print('thumbnail:', thumbnail)

Methods

Each method of the Stack class has its own section below, with its parameters, validation rules, behavior, and examples.

asset

asset opens one asset by its UID.

NameTypeDescription
uid (required)str

UID of the asset to open.

Default: Not applicable

Returns: Asset. A new Asset for the given UID.

Validation

  • asset raises KeyError when uid is None or not a string, because the asset UID becomes part of the request path.
  • Calling asset() with no argument raises TypeError, because uid is positional with no default.
  • An empty or whitespace-only string passes both checks. The SDK then requests the asset path with no UID in it. Check that a UID variable is non-empty before you pass it.
  • Errors that do occur after construction come from the fetch call that follows, not from asset().
    • fetch 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 makes no request. The fetch method of Asset sends it.
  • Each call returns a new Asset that shares the connection and headers of this stack.
  • To list assets instead of reading one, use the asset_query method.

Example

Basic usage: read one asset

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.asset('<ASSET_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['asset']['url'])

Error handling: a missing UID

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

asset_uid = None

try:
    asset = stack.asset(asset_uid)
except KeyError as error:
    # Fires when the UID is None or not a string
    print('Provide an asset UID as a string:', error)

asset_query

asset_query opens a query across the assets in the stack.

This method takes no parameters.

Returns: AssetQuery. A new AssetQuery for the assets in the stack.

Validation

  • There is no client-side validation, and asset_query never raises.
  • Errors that do occur come from the find call that follows, not from asset_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. asset_query makes no request. The find method of AssetQuery sends it.
  • Each call returns a new AssetQuery that shares the connection and headers of this stack. The AssetQuery class page lists the filters you can chain.
  • To read one asset by its UID, use the asset method.

Example

Basic usage: list the assets in the stack

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.asset_query().find()
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if 'error_code' in result:
        # The Delivery API rejected the request and returned the error body
        print('Delivery API error:', result['error_code'], result['error_message'])
    else:
        for asset in result.get('assets', []):
            print(asset['uid'], asset['url'])

content_type

content_type opens one content type by its UID, or the list of content types when you omit the UID.

NameTypeDescription
content_type_uidstr

UID of the content type to open.

Default: None

Returns: ContentType. A new ContentType for the given UID.

Validation

  • There is no client-side validation. content_type stores None, an empty string, or a non-string value as given, and never raises.
  • Errors that do occur come from the ContentType method you call next, not from content_type().
    • Without a UID, entry and query raise PermissionError and fetch raises KeyError. See Instance State on the ContentType class page.
    • fetch and find raise 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. content_type makes no request. The fetch and find methods of ContentType send it.
  • Each call returns a new ContentType that shares the connection and headers of this stack.
  • Pass the UID to read the content type or its entries. Omit it to list the content types in the stack with find.
  • An empty string passes through to the request URL as an empty path segment. Check that a UID variable is non-empty before you pass it.

Example

Basic usage: read the schema of one content type

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.content_type('<CONTENT_TYPE_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['content_type']['title'])

No UID: list the content types in the stack

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.content_type().find({'include_count': 'true'})
    print('content types:', result.get('count'))
except Exception as error:
    print('Request failed:', error)

get_api_key

get_api_key returns the API key you passed to the Stack constructor.

This method takes no parameters. It reads the api_key attribute of the instance.

Returns: str. The API key the stack was created with.

Validation

  • There is no client-side validation. The constructor already rejects a None or empty API key with PermissionError, so get_api_key always returns a non-empty value.
  • get_api_key is a property. stack.get_api_key() with parentheses raises TypeError, because Python calls the returned string.

Behavior

  • Client-side only. get_api_key makes no request.
  • It returns the api_key attribute. The SDK copies that value into the api_key header once, in the constructor, so assigning stack.api_key later changes what get_api_key returns but not what the SDK sends.

Example

Basic usage: read the API key back

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

# A property: no parentheses.
print('API key:', stack.get_api_key)

get_branch

get_branch returns the branch you passed to the Stack constructor, or None when you passed none.

This method takes no parameters. It reads the branch attribute of the instance.

Returns: str or None. The branch the stack was created with.

Validation

  • There is no client-side validation. The constructor stores branch as given, including an empty string.
  • get_branch is a property. stack.get_branch() with parentheses raises TypeError, because Python calls the returned value.

Behavior

  • Client-side only. get_branch makes no request.
  • When the constructor received branch, the SDK also sends it as the branch header on every request. None means the SDK sends no branch header.
  • It returns the constructor value. The variants method of Entry sets a different branch header for the length of one request, and get_branch does not reflect that.

Example

Basic usage: read the branch, with a fallback label

import contentstack

stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    branch='development',
)

branch = stack.get_branch
print('branch:', branch if branch is not None else 'none (no branch header)')

get_delivery_token

get_delivery_token returns the delivery token you passed to the Stack constructor.

This method takes no parameters. It reads the delivery_token attribute of the instance.

Returns: str. The delivery token the stack was created with.

Validation

  • There is no client-side validation. The constructor already rejects a None or empty delivery token with PermissionError, so get_delivery_token always returns a non-empty value.
  • get_delivery_token is a property. stack.get_delivery_token() with parentheses raises TypeError, because Python calls the returned string.

Behavior

  • Client-side only. get_delivery_token makes no request.
  • It returns the delivery_token attribute. The SDK copies that value into the access_token header once, in the constructor, so assigning stack.delivery_token later changes what get_delivery_token returns but not what the SDK sends.

Example

Basic usage: confirm which token the stack uses

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

# Print only the last four characters, so the token stays out of your logs.
print('delivery token ends with:', stack.get_delivery_token[-4:])

get_early_access

get_early_access returns the early access feature names you passed to the Stack constructor, or None when you passed none.

This method takes no parameters. It reads the early_access attribute of the instance.

Returns: list or None. The early access list the stack was created with.

Validation

  • There is no client-side validation. get_early_access returns the constructor value unchanged, whatever its type.
  • get_early_access is a property. stack.get_early_access() with parentheses raises TypeError, because Python calls the returned value.

Behavior

  • Client-side only. get_early_access makes no request.
  • It returns the list itself, not the header. The SDK sends the joined form, such as taxonomy, teams, in the x-header-ea header. Read stack.get_headers.get('x-header-ea') for that string.
  • An empty list still adds the x-header-ea header, with an empty value. None adds no header.

Example

Basic usage: read the list and the header it produces

import contentstack

stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    early_access=['taxonomy', 'teams'],
)

print('early access list:', stack.get_early_access)
print('x-header-ea:', stack.get_headers.get('x-header-ea'))

get_environment

get_environment returns the environment you passed to the Stack constructor.

This method takes no parameters. It reads the environment attribute of the instance.

Returns: str. The environment the stack was created with.

Validation

  • There is no client-side validation. The constructor already rejects a None or empty environment with PermissionError, so get_environment always returns a non-empty value.
  • get_environment is a property. stack.get_environment() with parentheses raises TypeError, because Python calls the returned string.

Behavior

  • Client-side only. get_environment makes no request.
  • It returns the constructor value, not the environment the next request sends. The environment method of Entry rewrites the shared environment header, and get_environment does not reflect that change. Read stack.get_headers.get('environment') for the value the SDK sends.

Example

Basic usage: compare the configured and the current environment

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

print('configured environment:', stack.get_environment)
print('environment header:', stack.get_headers.get('environment'))

get_headers

get_headers returns the dictionary of headers the SDK sends with every request from this stack.

This method takes no parameters. It reads the headers attribute of the instance.

Returns: dict. The header dictionary the stack sends.

Validation

  • There is no client-side validation, and reading get_headers cannot raise.
  • get_headers is a property. stack.get_headers() with parentheses raises TypeError, because Python calls the returned dictionary.

Behavior

  • Client-side only. get_headers makes no request.
  • Right after construction the dictionary holds api_key, access_token, and environment, plus each optional header the constructor added:
    • branch, when you passed branch.
    • x-header-ea, when you passed early_access.
    • preview_token, when live_preview enables preview and contains preview_token.
  • It returns the live dictionary that every object from this stack sends, not a snapshot. The SDK adds User-Agent and X-User-Agent on the first request, and methods such as the environment method of Entry and the live_preview_query method change it later.
  • A key you add to the returned dictionary reaches every later request from this stack.

Example

Basic usage: list the headers the next request sends

import contentstack

stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    branch='development',
)

for name, value in stack.get_headers.items():
    # Keep tokens out of your logs.
    shown = '***' if name in ('access_token', 'preview_token') else value
    print(name, '=', shown)

get_live_preview

get_live_preview returns the live preview dictionary the stack holds, or None when you passed no live_preview.

This method takes no parameters. It reads the live_preview attribute of the instance.

Returns: dict or None. The live preview dictionary the stack holds.

Validation

  • There is no client-side validation. get_live_preview returns the stored value, whatever it holds.
  • get_live_preview is a property. stack.get_live_preview() with parentheses raises TypeError, because Python calls the returned value.

Behavior

  • Client-side only. get_live_preview makes no request.
  • It returns the same dictionary object you passed to the constructor, not a copy. The SDK writes into that dictionary, so it holds these keys in addition to the ones you passed:
    • host, which the constructor adds when enable is truthy and you passed no host.
    • live_preview, content_type_uid, entry_uid, url, and any other key you pass, which the live_preview_query method adds.
    • The responses an entry fetch stores during a preview.
  • A change you make to the returned dictionary changes the configuration the SDK uses for the next request.

Example

Basic usage: confirm that a preview query took effect

import contentstack

stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    live_preview={'enable': True, 'preview_token': '<PREVIEW_TOKEN>'},
)

stack.live_preview_query(
    live_preview_query={
        'live_preview': '<LIVE_PREVIEW_HASH>',
        'content_type_uid': '<CONTENT_TYPE_UID>',
        'entry_uid': '<ENTRY_UID>',
    }
)

config = stack.get_live_preview
print('preview host:', config['host'])
print('preview URL:', config.get('url'))

global_field

global_field opens one global field by its UID, or the list of global fields when you omit the UID.

NameTypeDescription
global_field_uidstr

UID of the global field to open.

Default: None

Returns: GlobalField. A new GlobalField for the given UID.

Validation

  • There is no client-side validation. global_field stores None, an empty string, or a non-string value as given, and never raises.
  • Errors that do occur come from the GlobalField method you call next, not from global_field().
    • Without a UID, fetch raises KeyError. See Instance State on the GlobalField class page.
    • fetch and find raise 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. global_field makes no request. The fetch and find methods of GlobalField send it.
  • Each call returns a new GlobalField that shares the connection and headers of this stack.
  • Pass the UID to read one global field with fetch. Omit it to list the global fields with find.
  • An empty string passes through to the request URL as an empty path segment. Check that a UID variable is non-empty before you pass it.

Example

Basic usage: read one global field

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.global_field('<GLOBAL_FIELD_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['global_field']['title'])

No UID: list the global fields in the stack

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.global_field().find()
    for field in result.get('global_fields', []):
        print(field['uid'])
except Exception as error:
    print('Request failed:', error)

image_transform

image_transform pairs an image URL with the Image Delivery API parameters to apply to it.

NameTypeDescription
image_url (required)str

URL of the image to resize or convert.

Default: Not applicable
kwargsAny

Transformation parameters, such as width or format.

Default: None

Returns: ImageTransform. A new ImageTransform for the given image URL.

Validation

  • image_transform raises PermissionError when image_url is None or an empty string, because the SDK has no URL to append the parameters to.
  • Calling image_transform() with no argument raises TypeError, because image_url is positional with no default.
  • The SDK does not check parameter names or values. The Image Delivery API processes them when a client requests the finished URL.

Behavior

  • Client-side only. image_transform makes no request, and neither does the get_url method of ImageTransform.
  • Every keyword argument becomes one query parameter of the finished URL, in the order you pass them.
  • A parameter whose name has a hyphen, such as bg-color or resize-filter, is not a valid Python keyword. Pass it by unpacking a dictionary, as in **{'bg-color': 'FFFFFF'}.
  • The keyword logger sets the logger of the instance and never reaches the URL.
  • The ImageTransform class page lists the parameters the Image Delivery API accepts.

Example

Basic usage: a resized WebP version of an image

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

image_url = 'https://images.contentstack.io/v3/assets/<API_KEY>/<ASSET_UID>/<FILE_UID>/hero.jpg'

try:
    transform = stack.image_transform(image_url, width=640, format='webp', quality=80)
except PermissionError as error:
    # Fires when image_url is None or an empty string
    print('Provide an image URL:', error)
else:
    print(transform.get_url())

Hyphenated parameters: unpack a dictionary

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

image_url = 'https://images.contentstack.io/v3/assets/<API_KEY>/<ASSET_UID>/<FILE_UID>/logo.png'

transform = stack.image_transform(
    image_url,
    pad='20',
    **{'bg-color': 'FFFFFF', 'resize-filter': 'lanczos3'},
)
print(transform.get_url())

live_preview_query

live_preview_query sets the content type, entry, and live preview hash that the next entry request previews.

NameTypeDescription
kwargsAny

Keyword arguments. The SDK reads only live_preview_query, a dictionary.

Default: None

Returns: Stack. The same stack, for chaining.

Validation

  • There is no client-side validation, and live_preview_query never raises. It returns the stack unchanged, with no error, unless all three conditions below hold:
    • The constructor received a live_preview dictionary.
    • That dictionary has a truthy enable key.
    • You pass a live_preview_query keyword argument that holds a dictionary.
  • live_preview_query ignores every other keyword argument. live_preview_query(content_type_uid='blog') changes nothing, because the keys belong inside the live_preview_query dictionary.
  • Errors that do occur come from the fetch call of the entry you preview next, not from live_preview_query().
    • fetch raises an exception only for network failures (timeout, DNS error, dropped connection), apart from the live preview Known issue on the Stack class page.
    • 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. live_preview_query updates the live preview dictionary and makes no request.
  • The SDK merges every key of the live_preview_query dictionary into the live preview dictionary that get_live_preview returns. A key you omit keeps its earlier value, except the two header keys below.
  • The SDK reads these keys:
    • live_preview: the preview hash. Defaults to init when you omit it.
    • content_type_uid: the content type to preview. Only an entry of this content type gets preview content.
    • entry_uid: the entry to preview.
    • release_id and preview_timestamp: the SDK sends each one as a request header when present, and removes the header when absent. Both headers reach every later request from this stack.
  • The SDK builds the preview URL https://<host>/v3/content_types/<content_type_uid>/entries/<entry_uid>?live_preview=<hash> from those keys and the host of the live preview dictionary. Without entry_uid, the URL stops at /entries and includes no hash.
  • live_preview_query returns the stack, so you can chain content_type directly onto it.

Example

Basic usage: preview one entry

import contentstack

stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    live_preview={'enable': True, 'preview_token': '<PREVIEW_TOKEN>'},
)

try:
    result = stack.live_preview_query(
        live_preview_query={
            'live_preview': '<LIVE_PREVIEW_HASH>',
            'content_type_uid': '<CONTENT_TYPE_UID>',
            'entry_uid': '<ENTRY_UID>',
        }
    ).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('preview content:', result)

All parameters: preview a release at a point in time

import contentstack

stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    live_preview={'enable': True, 'preview_token': '<PREVIEW_TOKEN>'},
)

stack.live_preview_query(
    live_preview_query={
        'live_preview': '<LIVE_PREVIEW_HASH>',
        'content_type_uid': '<CONTENT_TYPE_UID>',
        'entry_uid': '<ENTRY_UID>',
        'release_id': '<RELEASE_UID>',
        'preview_timestamp': '2025-03-07T12:00:00Z',
    }
)

print('preview URL:', stack.get_live_preview['url'])
print('release header:', stack.get_headers.get('release_id'))

Edge case: the call changes nothing without enable

import contentstack

# No live_preview dictionary, so the stack ignores the preview query.
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

stack.live_preview_query(live_preview_query={'live_preview': '<LIVE_PREVIEW_HASH>'})

# Still None: nothing recorded the query.
print('live preview config:', stack.get_live_preview)

pagination

pagination fetches the next batch of a sync with the pagination token from the previous sync response.

NameTypeDescription
pagination_token (required)str

Pagination token from the previous sync response.

Default: Not applicable

Returns: dict. The next batch of sync items.

Validation

  • There is no client-side validation that raises. An empty string reaches the API as an empty pagination_token.
  • Calling pagination() with no argument raises TypeError, because pagination_token is positional with no default.
  • A token that is not a string leaves the sync parameters of the previous sync call in place, so pagination(None) repeats the previous sync request with no error.
  • pagination raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API-level rejection returns as a normal result with an errors key. For an invalid token, result['errors']['pagination_token'] lists the messages.
    • Check the result for an errors key even inside a try block.

Additional Resource Refer to Delivery API Errors for the full error code list.

Behavior

  • One call sends one Sync using pagination token request, GET /stacks/sync, with the pagination_token and the environment parameter.
  • A string token replaces the sync parameters the stack holds. The SDK does not resend the filters you passed to sync_init.
  • Each batch holds up to 100 records. The response contains another pagination_token while more batches remain, and a sync_token on the last batch.
  • pagination returns the parsed response body unchanged.

Limitations

  • Does not fetch the remaining batches for you. Call pagination once per token, as the loop in the example below does.

Example

Basic usage: fetch the next batch of a sync

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.pagination('<PAGINATION_TOKEN>')
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if 'errors' in result:
        # The Delivery API rejected the request and listed the errors per field
        print('Delivery API error:', result['errors'])
    else:
        print('items in this batch:', len(result.get('items', [])))

Loop: follow tokens until the sync token arrives

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.sync_init()
    while 'pagination_token' in result:
        result = stack.pagination(result['pagination_token'])
    print('sync token for next time:', result.get('sync_token'))
except Exception as error:
    print('Request failed:', error)

sync_init

sync_init starts a sync and returns the first batch of entries and assets published to the environment.

NameTypeDescription
content_type_uidstr

Syncs only the entries of this content type.

Default: None
start_fromstr

Syncs only content published from this ISO 8601 date.

Default: None
localestr

Syncs only content in this locale.

Default: None
publish_typestr

Comma-separated event types to sync, such as entry_published.

Default: None

Returns: dict. The first batch of published entries and assets.

Validation

  • There is no client-side validation that raises. sync_init skips any argument that is not a string, with no error. start_from=datetime(2024, 1, 1) therefore sends no start date and syncs from the beginning. Pass dates as ISO 8601 strings.
  • An empty string is a string, so sync_init sends it as an empty query parameter.
  • sync_init raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API-level rejection returns as a normal result with an errors key, which lists the messages for each rejected field. It does not raise an exception.
    • Check the result for an errors key even inside a try block.

Additional Resource Refer to Delivery API Errors for the full error code list.

Behavior

  • One call sends one Initial Sync request, GET /stacks/sync. The request includes init=true and each argument you pass.
  • publish_type reaches the API as the type query parameter. The other three arguments keep their names.
  • The SDK adds the environment parameter from the stack headers.
  • sync_init returns the parsed response body unchanged. Its items key holds the synced entries and assets.
  • When the sync holds more than 100 records, the response contains a pagination_token for the next batch. Otherwise it contains a sync_token for the next sync. See the Sync using pagination token reference.
  • Known issue: In 2.8.1, sync_init adds its arguments to the sync parameters the stack already holds and never clears them. A second sync_init call on the same stack keeps the filters of the first, and a call after pagination or sync_token also resends that token. Create a new Stack for each initial sync.

Limitations

  • Does not fetch every batch. Pass each pagination_token to the pagination method until a response contains a sync_token.

Example

Basic usage: sync everything published to the environment

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.sync_init()
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if 'errors' in result:
        # The Delivery API rejected the request and listed the errors per field
        print('Delivery API error:', result['errors'])
    else:
        print('items in this batch:', len(result.get('items', [])))

All parameters: sync one content type, locale, and event type from a date

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.sync_init(
        content_type_uid='<CONTENT_TYPE_UID>',
        start_from='2024-01-01T00:00:00.000Z',
        locale='en-us',
        publish_type='entry_published,entry_unpublished',
    )
    print('items in this batch:', len(result.get('items', [])))
except Exception as error:
    print('Request failed:', error)

Complete sync: follow every pagination token

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

items = []
try:
    result = stack.sync_init()
    items.extend(result.get('items', []))
    while 'pagination_token' in result:
        result = stack.pagination(result['pagination_token'])
        items.extend(result.get('items', []))
    print('synced items:', len(items))
    # Store the sync token and pass it to sync_token() next time.
    print('sync token:', result.get('sync_token'))
except Exception as error:
    print('Request failed:', error)

sync_token

sync_token fetches the content published, unpublished, or deleted since the sync that returned the token.

NameTypeDescription
sync_token (required)str

Sync token from the last completed sync.

Default: Not applicable

Returns: dict. The content changed since the last completed sync.

Validation

  • There is no client-side validation that raises. An empty string reaches the API as an empty sync_token.
  • Calling sync_token() with no argument raises TypeError, because sync_token is positional with no default.
  • A token that is not a string leaves the sync parameters of the previous sync call in place, so sync_token(None) repeats the previous sync request with no error.
  • sync_token raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API-level rejection returns as a normal result with an errors key. For an invalid token, result['errors']['sync_token'] lists the messages.
    • Check the result for an errors key even inside a try block.

Additional Resource Refer to Delivery API Errors for the full error code list.

Behavior

  • One call sends one Subsequent Sync request, GET /stacks/sync, with the sync_token and the environment parameter.
  • A string token replaces the sync parameters the stack holds.
  • When the changes hold more than 100 records, the response contains a pagination_token instead of a new sync_token. Pass it to the pagination method until a sync_token arrives, and store that token for the next call.
  • sync_token returns the parsed response body unchanged.

Example

Basic usage: fetch the changes since the last sync

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.sync_token('<SYNC_TOKEN>')
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if 'errors' in result:
        # The Delivery API rejected the request and listed the errors per field
        print('Delivery API error:', result['errors'])
    else:
        print('changed items:', len(result.get('items', [])))

Large change set: follow pagination tokens, then store the new sync token

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

changes = []
try:
    result = stack.sync_token('<SYNC_TOKEN>')
    changes.extend(result.get('items', []))
    while 'pagination_token' in result:
        result = stack.pagination(result['pagination_token'])
        changes.extend(result.get('items', []))
    print('changed items:', len(changes))
    print('next sync token:', result.get('sync_token'))
except Exception as error:
    print('Request failed:', error)

taxonomy

taxonomy opens one published taxonomy by its UID, or a query across taxonomies when you omit the UID.

NameTypeDescription
taxonomy_uidstr

UID of the taxonomy to open.

Default: None

Returns: Taxonomy or TaxonomyQuery. A new Taxonomy for the given UID, or a TaxonomyQuery when you omit it.

Instance State

  • Call stack.taxonomy('<TAXONOMY_UID>') to work with one taxonomy. This returns a Taxonomy, which reads the taxonomy (fetch) and opens its terms (term).
  • Call stack.taxonomy() to work across taxonomies. This returns a TaxonomyQuery, which lists taxonomies (find, limit) and filters entries by term (in_, below).
  • The two classes share no methods except param. A method that only the other class has raises AttributeError. The Taxonomy class page lists both sets.

Warning taxonomy tests the UID for truthiness, so stack.taxonomy('') returns a TaxonomyQuery, not an error. A UID variable that is unexpectedly empty then lists taxonomies instead of reading one, or raises AttributeError on fetch.

Validation

  • There is no client-side validation beyond the truthiness test above. taxonomy never raises.
  • Errors that do occur come from the fetch or find call that follows, not from taxonomy().
    • fetch and find raise 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. taxonomy makes no request. The fetch and find methods send it.
  • Each call returns a new object that shares the connection and headers of this stack.

Example

Basic usage: read one taxonomy

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.taxonomy('<TAXONOMY_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)

No UID: list the published taxonomies

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.taxonomy().limit(10).find()
    for taxonomy in result.get('taxonomies', []):
        print(taxonomy['uid'])
except Exception as error:
    print('Request failed:', error)