Asset

View as Markdown

Asset

Assets are the media files uploaded to a stack, such as images, videos, PDFs, and audio files. Use this class to

  • read one published asset by its UID
  • add image dimensions, the relative URL, or fallback-locale content to the response
  • request extra asset field groups such as visual_markups

stack.asset() returns an Asset and takes one argument:

NameTypeDescription
uidstrUID of the asset to read.

To list assets instead of reading one, call stack.asset_query(), which returns an AssetQuery.

Instance State

stack.asset('<ASSET_UID>') is the only way to get an Asset, and every instance reaches the same methods.

  • stack.asset raises KeyError when the UID is None or is not a str, because the SDK builds the asset URL from it.
  • stack.asset() with no argument raises TypeError, because uid is a positional parameter with no default.
  • The constructor copies the environment from the Stack headers into the asset's query parameters.
    • fetch therefore sends environment in the query string and in the request headers.

Known issue stack.asset('') and a UID made only of spaces return an Asset instead of raising, and fetch then requests the asset endpoint with no asset UID in the path. Check that the UID variable is non-empty before you call stack.asset.

Class-Level Notes

Shared environment header.

  • The environment and remove_environment methods write to the Stack headers dictionary, which every object you create from that Stack reads.
  • Neither method changes the environment copy that the constructor put in the query string. Each method page includes a Known issue line with the consequence.
  • The Delivery API expects a delivery token that belongs to the environment you read from. See the access_token header in Get a single asset. To read assets from a second environment, create a second Stack with that environment and its delivery token.

Flags are one-way.

  • The relative_urls, include_dimension, and include_fallback methods each write the string 'true' under a fixed query parameter key.
  • No method removes a query parameter. Create a new stack.asset('<ASSET_UID>') to send a request without one, or overwrite the key through the params method.

Response shape.

  • fetch returns the parsed JSON body as a dict. The asset sits under the asset key, so read result['asset'].
  • An API rejection also returns a dict, with error_code and error_message keys instead of asset.

Rate limiting and retry.

  • The SDK retries a request that returns 408 or 429, sending the initial request plus up to five retries, with no delay between them.
  • Each request times out after 30 seconds unless you pass a different timeout to Stack.

Additional Resource Refer to the Stack class page for the retry_strategy and timeout options.

Capability Matrix

CapabilitySupportedNotes / Alternative
List the assets in a stackNoUse the find method of AssetQuery
Read a specific asset versionNo dedicated methodCall params('version', 2) through the params method
Set the locale of the requestNo dedicated methodCall params('locale', 'fr-fr') through the params method
Add asset metadata or the branch to the responseNo dedicated methodCall params('include_metadata', 'true') or params('include_branch', 'true')
Request two or more asset field groupsNoSee the Known issue on the asset_fields method

Method Index

Method NameReturnsDescription
fetchThe requested asset.Reads one published asset by its UID.
include_dimensionThe same asset, for chaining.Adds the height and width of an image.
include_fallbackThe same asset, for chaining.Returns fallback-locale content when a localization is missing.
relative_urlsThe same asset, for chaining.Requests the relative URL of the asset.
asset_fieldsThe same asset, for chaining.Requests extra asset field groups.
paramsThe same asset, for chaining.Sets one query parameter.
environmentThe same asset, for chaining.Sets the environment header on the Stack.
remove_environmentThe same asset, for chaining.Deletes the environment header from the Stack.

Class-Level Snippet

This snippet reads one image asset with its dimensions and relative URL, then prints its title and URL.

import contentstack

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

try:
    result = stack.asset('<ASSET_UID>') \
        .include_dimension() \
        .relative_urls() \
        .include_fallback() \
        .params('locale', 'fr-fr') \
        .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:
        asset = result['asset']
        print(asset['title'], asset['url'])

Methods

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

asset_fields

asset_fields requests extra asset field groups, such as visual_markups, in the response.

NameTypeDescription
field_names (required)str

Field group names, passed as separate arguments.

Default: Not applicable

Returns: Asset. The same asset, for chaining.

Known issue fetch sends the stored names as one Python list string, such as ['visual_markups'], instead of one value per field group, so the API does not receive the group names. To request one group, call params('asset_fields[]', 'visual_markups') through the params method instead. To request several groups, list the assets with the asset_fields method of AssetQuery, which sends each name separately.

Validation

  • There is no client-side validation. asset_fields converts each name with str() and stores it, so an unknown group name reaches the API unchanged.
  • Calling asset_fields() with no arguments is valid and changes nothing.
  • Errors that do occur come from the fetch() call that follows, not from asset_fields().
    • 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_fields appends the names to a list under the asset_fields[] query parameter and makes no request.
  • The SDK names four groups: user_defined_fields, embedded_metadata, ai_generated_metadata, and visual_markups.
    • The Delivery API defines the groups it accepts. See asset_fields[] in Get a single asset for the current list.
  • With visual_markups, the API returns the hotspot and bounding-box annotations of the asset under the visual_markups key, or an empty array when the asset has none. See asset_fields[] in Get a single asset.
  • A list or a tuple counts as several names. asset_fields(['user_defined_fields', 'visual_markups']) stores the same two names as two separate arguments.
  • A second call adds to the list instead of replacing it.

Example

Basic usage: request the visual markups of an asset

import contentstack

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

try:
    # One group through params, which sends the name as a plain value
    result = stack.asset('<ASSET_UID>').params('asset_fields[]', 'visual_markups').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'].get('visual_markups'))

All parameters: store several field groups on the asset

import contentstack

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

try:
    result = stack.asset('<ASSET_UID>') \
        .asset_fields('user_defined_fields', 'embedded_metadata') \
        .asset_fields(['ai_generated_metadata', 'visual_markups']) \
        .fetch()
    print(result.get('asset'))
except Exception as error:
    print('Request failed:', error)

environment

environment writes an environment name into the environment header that the Stack sends with every request.

NameTypeDescription
environment (required)str

Environment name to send in the request header.

Default: Not applicable

Returns: Asset. The same asset, for chaining.

Known issue environment does not change the environment that this asset's fetch sends in the query string, and it changes the header for every later request from the same Stack. To read assets from another environment, create a separate Stack with that environment and its delivery token.

Validation

  • There is no client-side validation. environment stores an empty string as given.
  • environment(None) changes nothing and returns the asset, so the header keeps its current value.
  • A value that is not a str reaches the header unchanged. The next request from that Stack then raises RequestError, because the HTTP library accepts only string header values.
  • Omitting the argument raises TypeError, because environment is a positional parameter with no default.
  • Errors that do occur come from the fetch() call that follows, not from environment().
    • 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. environment writes the name into the Stack headers dictionary and makes no request.
  • The asset keeps the environment that its constructor copied into the query string. The fetch() call that follows therefore sends the new name in the header and the original name in the query string.
  • Every request the same Stack sends afterwards carries the new header. Every Asset or AssetQuery you create from that Stack afterwards also copies the new name into its query string.
  • Get a single asset lists environment as a query parameter and takes an environment-specific delivery token in the access_token header.
  • Calling environment twice replaces the first value, because both calls write the same header key.

Example

Basic usage: set the environment header

import contentstack

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

try:
    result = stack.asset('<ASSET_UID>').environment('<ENVIRONMENT>').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']['title'])

Workaround: read from a second environment through its own stack

import contentstack

production = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', 'production')
staging = contentstack.Stack('<API_KEY>', '<STAGING_DELIVERY_TOKEN>', 'staging')

try:
    live = production.asset('<ASSET_UID>').fetch()
    draft = staging.asset('<ASSET_UID>').fetch()
    print(live.get('asset', {}).get('title'), draft.get('asset', {}).get('title'))
except Exception as error:
    print('Request failed:', error)

fetch

fetch reads one published asset by its UID and returns the parsed response body.

This method takes no parameters. It reads the asset UID and every query parameter the chain set from the instance.

Returns: dict. The requested asset.

Validation

  • There is no client-side validation. fetch sends whatever UID the instance holds. stack.asset checks the UID earlier, as the Instance State section of the Asset class page describes.
  • fetch raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API-level rejection, such as a UID that matches no published asset, returns as a normal result with an error_code key. It does not raise an exception.
    • Check the result for an error_code key even inside a try block.

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

Behavior

  • One call sends one Get a single asset request, GET /v3/assets/{asset_uid}, with every query parameter the chain set.
  • The request always carries the environment the constructor copied into the query string, plus whatever the include_dimension, include_fallback, relative_urls, asset_fields, and params methods set.
  • fetch returns the parsed JSON body unchanged. Read the asset from result['asset'].
  • fetch reads the Stack headers when it runs. An environment or remove_environment call made before fetch changes the headers it sends.
  • Calling fetch twice on one instance sends the same request twice. The SDK caches nothing.

Limitations

  • Does not list assets. Use the find method of AssetQuery instead.

Example

Basic usage: read one asset by UID

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:
        asset = result['asset']
        print(asset['uid'], asset['title'], asset['url'])

Response shaping: read an image with its dimensions and relative URL

import contentstack

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

try:
    result = stack.asset('<ASSET_UID>') \
        .include_dimension() \
        .relative_urls() \
        .fetch()
    print(result.get('asset'))
except Exception as error:
    print('Request failed:', error)

Edge case: check the UID before you build the asset

import contentstack

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

asset_uid = '   '

# stack.asset accepts an empty or blank UID, so check it first.
if not asset_uid.strip():
    print('No asset UID supplied')
else:
    try:
        result = stack.asset(asset_uid).fetch()
        print(result.get('asset'))
    except Exception as error:
        print('Request failed:', error)

include_dimension

include_dimension asks the API to add the height and width of an image asset to the response.

This method takes no parameters.

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation. include_dimension takes no input and cannot fail.
  • Errors that do occur come from the fetch() call that follows, not from include_dimension().
    • 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. include_dimension sets the include_dimension query parameter to 'true' and makes no request. The fetch() call that follows sends it.
  • The API returns dimensions for JPG, GIF, PNG, WebP, BMP, TIFF, SVG, and PSD images. See include_dimension in Get a single asset.
  • Calling include_dimension twice changes nothing, because both calls write the same value under the same key.

Example

Basic usage: read an image with its height and width

import contentstack

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

try:
    result = stack.asset('<ASSET_UID>').include_dimension().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'])

include_fallback

include_fallback asks the API to return the asset from the fallback locale when the requested locale has no published version.

This method takes no parameters.

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation. include_fallback takes no input and cannot fail.
  • Errors that do occur come from the fetch() call that follows, not from include_fallback().
    • 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. include_fallback sets the include_fallback query parameter to 'true' and makes no request. The fetch() call that follows sends it.
  • The API then returns the published asset details from the fallback locale when the requested locale holds no published version. See include_fallback in Get a single asset.
  • Asset has no locale method. Set the locale with params('locale', '<locale code>') through the params method.
  • Calling include_fallback twice changes nothing, because both calls write the same value under the same key.

Example

Basic usage: read a French asset with fallback

import contentstack

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

try:
    result = stack.asset('<ASSET_UID>') \
        .params('locale', 'fr-fr') \
        .include_fallback() \
        .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']['title'])

params

params sets one query parameter on the asset request, for a parameter that has no dedicated method.

NameTypeDescription
key (required)str

Query parameter name, such as locale.

Default: Not applicable
value (required)Any

Query parameter value to send.

Default: Not applicable

Returns: Asset. The same asset, for chaining.

Validation

  • params raises KeyError when key or value is None, or when key is not a str, because the SDK cannot build a query parameter from either.
  • Omitting either argument raises TypeError, because both are positional parameters with no default.
  • params accepts an empty string and any other non-null value, and stores it as given.
  • Errors that do occur come from the fetch() call that follows, not from params().
    • 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. params writes the pair into the asset's query parameters and makes no request. The fetch() call that follows sends it.
  • fetch converts the value with str(), so True arrives as True and a list arrives as its Python representation. Pass 'true' for a flag and a plain string for every other value.
  • Calling params with a key that already holds a value replaces it. That includes the keys other methods write, such as environment and include_dimension.
  • Get a single asset accepts version, include_branch, and include_metadata, and Asset has no dedicated method for any of them. Send them through params.

Example

Basic usage: read a specific version of an asset

import contentstack

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

try:
    result = stack.asset('<ASSET_UID>').params('version', '2').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']['title'])

Several parameters: add metadata and the branch to the response

import contentstack

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

try:
    result = stack.asset('<ASSET_UID>') \
        .params('include_metadata', 'true') \
        .params('include_branch', 'true') \
        .fetch()
    print(result.get('asset'))
except Exception as error:
    print('Request failed:', error)

Error handling: a null value raises before any request

import contentstack

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

selected_locale = None

try:
    asset = stack.asset('<ASSET_UID>').params('locale', selected_locale)
except KeyError as error:
    # Raised when the key or the value is None, or the key is not a str
    print('Invalid parameter:', error)

relative_urls

relative_urls asks the API to include the relative URL of the asset in the response.

This method takes no parameters.

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation. relative_urls takes no input and cannot fail.
  • Errors that do occur come from the fetch() call that follows, not from relative_urls().
    • 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. relative_urls sets the relative_urls query parameter to 'true' and makes no request. The fetch() call that follows sends it.
  • Calling relative_urls twice changes nothing, because both calls write the same value under the same key.
  • The method name is plural on Asset. The equivalent method on AssetQuery is the relative_url method, and both send the same relative_urls parameter.

Example

Basic usage: read an asset with its relative URL

import contentstack

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

try:
    result = stack.asset('<ASSET_UID>').relative_urls().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'])

remove_environment

remove_environment deletes the environment header from the headers that the Stack sends with every request.

This method takes no parameters. It changes the headers of the Stack the asset came from.

Returns: Asset. The same asset, for chaining.

Known issue remove_environment does not remove the environment from this asset's query string, and afterwards some other calls on the same Stack, for example ContentType.fetch and GlobalField.fetch, raise KeyError. Call it only on a Stack that you create for this one asset request.

Validation

  • There is no client-side validation. remove_environment takes no input.
  • Calling it when the header is already gone changes nothing and raises nothing.
  • Errors that do occur come from the fetch() call that follows, not from remove_environment().
    • 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. remove_environment deletes the environment key from the Stack headers dictionary and makes no request.
  • The asset keeps the environment that its constructor copied into the query string, so the fetch() call that follows still sends it there.
  • Every Asset or AssetQuery you create from that Stack afterwards sends no environment.
  • ContentType.fetch, ContentType.find, GlobalField.fetch, GlobalField.find, and Stack.sync_init read the header without a check, so they raise KeyError on that Stack.
  • The environment method puts the header back.

Example

Basic usage: drop the header on a dedicated stack

import contentstack

# A separate Stack, so the change does not affect the rest of the app
asset_stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = asset_stack.asset('<ASSET_UID>').remove_environment().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']['title'])

Edge case: restore the header before other calls on the same stack

import contentstack

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

try:
    asset = stack.asset('<ASSET_UID>').remove_environment()
    result = asset.fetch()

    # Put the header back so that ContentType and GlobalField calls work again
    asset.environment('<ENVIRONMENT>')
    content_type = stack.content_type('<CONTENT_TYPE_UID>').fetch()
    print(result.get('asset'), content_type.get('content_type'))
except Exception as error:
    print('Request failed:', error)