Global Fields

View as Markdown

Global Fields

A global field is a reusable field or group of fields that you define once and use in several content types of a stack. Use this class to

  • list the global fields in a stack
  • read the schema of one global field by its UID

stack.global_field() returns a GlobalField and takes one optional argument:

NameTypeDescription
global_field_uidstrUID of the global field. Omit it to list global fields.

Instance State

stack.global_field() returns a GlobalField with or without a UID. Both methods exist on every instance, and the UID decides whether fetch can build its request.

  • Call stack.global_field('<GLOBAL_FIELD_UID>') to read one global field with fetch.
  • Call stack.global_field() without a UID to list global fields with find.

See the Method Index below for both methods.

On an instance without a UID, fetch raises KeyError. find works on both instances and ignores the UID.

Warning The SDK checks the UID for None only, and the constructor checks nothing. stack.global_field('') passes, and fetch then requests /global_fields/ 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.global_field(...) 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 global fields 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

CapabilitySupportedNotes / Alternative
List only the global field that the UID namesNofind always lists every global field. Call fetch on an instance with that UID
Pass query parameters to fetchNofetch takes no arguments
Clear a parameter an earlier find call storedNoCreate a new GlobalField instance
Find the content types that use a global fieldNoRead each content type with the fetch method of ContentType

Method Index

The groups below follow the Instance State split: fetch needs a UID, and find works on any instance.

Read one global field. Available on stack.global_field('<GLOBAL_FIELD_UID>').

Method NameReturnsDescription
fetchThe requested global field.Reads the schema of one global field.

List global fields. Available on stack.global_field(), and on an instance with a UID, where it ignores the UID.

Method NameReturnsDescription
findThe global fields in the stack.Lists the global fields in the stack.

Class-Level Snippet

The following snippet lists the global fields in the stack, then reads the schema of one.

import contentstack

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

try:
    listing = stack.global_field().find()
    for field in listing.get('global_fields', []):
        print('global field:', field['uid'])

    result = stack.global_field('<GLOBAL_FIELD_UID>').fetch()
    if 'error_code' in result:
        print('Delivery API error:', result['error_code'], result['error_message'])
    else:
        print('fields:', [field['uid'] for field in result['global_field']['schema']])
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)

Methods

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

fetch

fetch reads the schema of the global field the instance holds.

This method takes no parameters. It reads the global field UID from the instance.

Returns: dict. The requested global field.

Validation

  • fetch raises KeyError when the instance holds no global field UID, because the request path needs one. stack.global_field() without a UID builds such an instance.
  • An empty string passes that check, and so does a value that is not a string. The SDK writes either into the request path as text.
  • Calling fetch with an argument raises TypeError, because it takes none.
  • 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

  • One call sends one Get a single global field request, GET /global_fields/{global_field_uid}.
  • When the global field nests other global fields, they appear in its schema, as the API reference describes.
  • fetch returns the parsed response body unchanged. The global field sits under the global_field 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 GlobalField class page.

Example

Basic usage: read the fields of a 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:
        global_field = result['global_field']
        print(global_field['title'])
        for field in global_field['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.global_field().fetch()
except KeyError as error:
    # Fires when the instance holds no global field UID
    print('Pass a global field UID to global_field():', error)

find

find lists the global fields in the stack.

NameTypeDescription
paramsdict

Query parameters to add to the request.

Default: None

Returns: dict. The global fields 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 keyword is params. find(param={...}) 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 global fields request, GET /global_fields, with the environment parameter and every key in params.
  • find ignores the UID of the instance. stack.global_field('<GLOBAL_FIELD_UID>').find() lists every global field, not the named one.
  • The API reference lists these query parameters for the request:
    • include_global_field_schema: adds the schema of each global field.
    • include_branch: adds the _branch key.
  • find returns the parsed response body unchanged. The global fields sit under the global_fields 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.
  • The SDK does not page through the results.

Example

Basic usage: list the global fields

import contentstack

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

try:
    result = stack.global_field().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 global_field in result.get('global_fields', []):
            print(global_field['uid'], global_field['title'])

All parameters: schemas and branch

import contentstack

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

try:
    result = stack.global_field().find(params={
        'include_global_field_schema': 'true',
        'include_branch': 'true',
    })
    for global_field in result.get('global_fields', []):
        print(global_field['uid'], global_field.get('_branch'))
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:
    seo = stack.global_field('<GLOBAL_FIELD_UID>')
    seo.find({'include_branch': 'true'})

    # fetch on the same instance also sends include_branch=true.
    result = seo.fetch()
    print(result.get('global_field', {}).get('_branch'))
except Exception as error:
    print('Request failed:', error)