ContentType
ContentType
A content type defines the structure of the entries created from it. Use this class to
- list the content types in a stack
- read the schema of one content type
- open one entry, a query over the entries, or entry variants of a content type
stack.content_type() returns a ContentType and takes one optional argument:
| Name | Type | Description |
|---|---|---|
| content_type_uid | str | UID of the content type. Omit it to list content types. |
Instance State
stack.content_type() returns a ContentType with or without a UID, and the argument decides which methods work.
- Call stack.content_type('<CONTENT_TYPE_UID>') to work with one content type. This instance reads the schema (fetch) and opens the entries (entry, query).
- Call stack.content_type() without a UID to list content types with find.
See the Method Index below for the full set in each group.
On an instance without a UID, entry and query raise PermissionError, and fetch raises KeyError. variants raises nothing and builds a request for a content type named None. find works on both instances and ignores the UID.
Warning Every UID check in this class tests for None only. stack.content_type('') passes them all, and the SDK sends a request with an empty path segment where the UID belongs. Check that a UID variable is non-empty before you pass it.
Class-Level Notes
Query parameters stay on the instance.
- fetch and find read and write one parameter dictionary on the instance, and neither clears it.
- A params dictionary you pass to find stays on the instance. Later find and fetch calls on the same instance send it again.
- Create a new stack.content_type(...) instance for each request that needs different parameters.
Environment.
- fetch and find send the stack's environment header value as an environment query parameter.
- Known issue: In 2.8.1, after the remove_environment method of an Entry or Asset on the same stack runs, fetch and find raise KeyError. Use a separate Stack for the objects you call remove_environment on.
Branch.
- The stack sends its branch header on every request of this class. Pass include_branch to find to get the _branch key in the response, as the Get all content types reference describes.
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.
- Pass a retry_strategy with a non-zero backoff_factor to the Stack constructor if you expect 429 responses.
Additional Resource The Stack class page lists the retry_strategy constructor argument and its default.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| List only the content type that the UID names | No | find always lists every content type. Call fetch on an instance with that UID |
| Pass query parameters to fetch | No | fetch takes no arguments |
| Clear a parameter an earlier find call stored | No | Create a new ContentType instance |
| Chainable filters on the content type list | No | Pass the parameters as a dictionary to find |
Method Index
The groups below follow the Instance State split: the first group needs a UID, and find works on any instance.
Read one content type and its entries. Available on stack.content_type('<CONTENT_TYPE_UID>').
| Method Name | Returns | Description |
|---|---|---|
| fetch | The requested content type. | Reads the schema of the content type. |
| entry | A new Entry for the given UID. | Opens one entry of the content type. |
| query | A new Query over the entries of this content type. | Opens a query over the entries. |
| variants | A new Variants for the given variant UIDs. | Opens entry variants across the entries. |
List content types. Available on stack.content_type(), and on an instance with a UID, where it ignores the UID.
| Method Name | Returns | Description |
|---|---|---|
| find | The content types in the stack. | Lists the content types in the stack. |
Class-Level Snippet
This snippet counts the content types in the stack, reads the schema of one, and lists five of its entries.
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
listing = stack.content_type().find({'include_count': 'true'})
print('content types:', listing.get('count'))
product = stack.content_type('<CONTENT_TYPE_UID>')
schema = product.fetch()
if 'error_code' in schema:
print('Delivery API error:', schema['error_code'], schema['error_message'])
else:
print('fields:', [field['uid'] for field in schema['content_type']['schema']])
entries = product.query().limit(5).find()
print('entries:', len(entries.get('entries', [])))
except Exception as error:
# Raised only for network failures (timeout, DNS error, dropped connection)
print('Request failed:', error)Methods
Each method of the ContentType class has its own section below, with its parameters, validation rules, behavior, and examples.
entry
entry opens one entry of the content type by its UID.
| Name | Type | Description |
|---|---|---|
| entry_uid (required) | str | UID of the entry to open. |
Returns: Entry. A new Entry for the given UID.
Validation
- entry raises PermissionError when the instance holds no content type UID, because the entry path includes it.
- entry raises PermissionError when entry_uid is None.
- Calling entry() with no argument raises TypeError, because entry_uid is positional with no default.
- An empty string passes both checks. The SDK then requests the entries path with no entry 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 entry().
- 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. An unknown entry UID returns error_code 141.
- 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. entry makes no request. The fetch method of Entry sends it.
- Each call returns a new Entry that shares the connection and headers of the stack. The Entry class page lists the methods you can chain before fetch, such as locale and include_reference.
- To read several entries, use the query method instead.
Example
Basic usage: read one entry
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'])Chained options: read the entry in a locale
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
entry = stack.content_type('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>')
result = entry.locale('fr-fr').fetch()
print(result.get('entry', {}).get('locale'))
except Exception as error:
print('Request failed:', error)Error handling: a content type without a UID
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
entry = stack.content_type().entry('<ENTRY_UID>')
except PermissionError as error:
# Fires when the content type or the entry UID is None
print('Pass both UIDs:', error)fetch
fetch reads the schema of the content type the instance holds.
This method takes no parameters. It reads the content type UID from the instance.
Returns: dict. The requested content type.
Validation
- fetch raises KeyError when the instance holds no content type UID, because the request path needs one. stack.content_type() without a UID builds such an instance.
- An empty string passes that check. The SDK then requests /content_types/ with an empty UID segment.
- 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. An unknown content type UID returns error_code 118.
- 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 content type request, GET /content_types/{content_type_uid}.
- The response holds the content type schema but none of its entries. Use the query or entry method for the entries.
- fetch returns the parsed response body unchanged. The content type sits under the content_type key.
- fetch sends the environment parameter, plus every parameter an earlier find call on the same instance stored. See Query parameters stay on the instance on the ContentType class page.
Example
Basic usage: read the fields of a 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:
content_type = result['content_type']
print(content_type['title'])
for field in content_type['schema']:
print(' -', field['uid'], field['data_type'])Error handling: an instance without a UID
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type().fetch()
except KeyError as error:
# Fires when the instance holds no content type UID
print('Pass a content type UID to content_type():', error)find
find lists the content types in the stack.
| Name | Type | Description |
|---|---|---|
| params | dict | Query parameters to add to the request. |
Returns: dict. The content types in the stack.
Validation
- There is no client-side validation of the keys or values in params. The SDK sends them as given.
- A params value that is not a dictionary fails in the merge. A string raises ValueError, and an integer raises TypeError.
- The SDK converts each value with str(), so the boolean True reaches the API as True. Pass the string 'true', as the API reference shows.
- find raises an exception only for network failures (timeout, DNS error, dropped connection).
- An API-level rejection returns as a normal result with an error_code key. It does not raise an exception.
- Check the result for an error_code key even inside a try block.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- One call sends one Get all content types request, GET /content_types, with the environment parameter and every key in params.
- find ignores the UID of the instance. stack.content_type('<CONTENT_TYPE_UID>').find() lists every content type, not the named one.
- The API reference lists these query parameters for the request:
- include_count: adds the total number of content types as count.
- include_global_field_schema: adds the schema of each global field a content type uses.
- include_branch: adds the _branch key.
- find returns the parsed response body unchanged. The content types sit under the content_types key.
- params stays on the instance, so a later find or fetch on the same instance sends it again. A params key named environment replaces the stack's environment for that call only.
- One call makes one request. The SDK does not page through the results.
Example
Basic usage: list the content types
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.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 content_type in result.get('content_types', []):
print(content_type['uid'], content_type['title'])All parameters: count, global field schemas, and branch
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type().find(params={
'include_count': 'true',
'include_global_field_schema': 'true',
'include_branch': 'true',
})
print('content types:', result.get('count'))
except Exception as error:
print('Request failed:', error)Edge case: parameters stay on the instance
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
listing = stack.content_type()
with_count = listing.find({'include_count': 'true'})
# The same instance sends include_count again on this call.
again = listing.find()
# A new instance starts with no stored parameters.
plain = stack.content_type().find()
print('count' in again, 'count' in plain)
except Exception as error:
print('Request failed:', error)query
query opens a query over the entries of the content type.
This method takes no parameters. It reads the content type UID from the instance.
Returns: Query. A new Query over the entries of this content type.
Validation
- query raises PermissionError when the instance holds no content type UID, because the entries path includes it.
- An empty string passes that check. The SDK then requests /content_types//entries.
- Errors that do occur after construction 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 makes no request. The find method of Query sends it.
- Each call returns a new Query with no conditions. The Query class page lists the filters, sorting, and paging methods you can chain.
- To read one entry by its UID, use the entry method instead.
Example
Basic usage: list the first 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.get('entries', []):
print(entry['uid'], entry['title'])Chained options: count the entries in a locale
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').query().locale('en-us').include_count().find()
print('entries:', result.get('count'))
except Exception as error:
print('Request failed:', error)variants
variants opens the entry variants of the content type for one or more variant UIDs.
| Name | Type | Description |
|---|---|---|
| variant_uid (required) | str | list[str] | Variant UID or alias, or a list of them. |
| branch | str | Branch for the variant request. |
| params | dict | Query parameters for the variant request. |
Returns: Variants. A new Variants for the given variant UIDs.
Validation
- There is no client-side validation, and variants never raises except for a missing argument.
- Calling variants() with no argument raises TypeError, because variant_uid is positional with no default.
- A variant_uid that is neither a string nor a list, such as a tuple, adds no variant header. The request then returns base entries with no error.
- On an instance without a content type UID, variants builds a request for a content type named None.
- Errors that do occur come from the find call that follows, not from variants().
- The object has no entry UID, so its fetch method raises ValueError. Use find, or the variants method of Entry for one entry.
- 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. variants makes no request. The find method sends a Get multiple variants of an entry request, GET /content_types/{content_type_uid}/entries.
- find sends variant_uid in the x-cs-variant-uid header. The SDK joins a list with commas.
- The API accepts up to five variant UIDs or aliases by default, and the first one you list takes priority on conflicting fields.
- branch replaces the stack's branch header for that one request. The SDK restores the stack's header afterward.
- params reaches the request as query parameters, such as locale.
- The Entry Variants class page lists the methods of the returned object, and marks the inherited methods whose values the variant request does not send.
Example
Basic usage: entries with one variant applied
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
result = stack.content_type('<CONTENT_TYPE_UID>').variants('<VARIANT_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.get('entries', []):
print(entry['uid'], entry['title'])All parameters: two variants on a branch, in one locale
import contentstack
stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')
try:
variants = stack.content_type('<CONTENT_TYPE_UID>').variants(
['<VARIANT_UID>', '<SECOND_VARIANT_UID>'],
branch='development',
params={'locale': 'en-us'},
)
result = variants.find()
print('entries:', len(result.get('entries', [])))
except Exception as error:
print('Request failed:', error)