Global Fields

View as Markdown

Global Fields

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

  • list, create and import the global fields of a stack
  • read, update, export and delete one global field

stack.global_fields() returns a GlobalFields object for each of these tasks and takes the following two optional arguments:

NameTypeDescription
global_field_uidstrUID of the global field. Omit it to list, create or import.
optionsdictRequest options. The SDK reads only the api_version key.

Instance State

stack.global_fields() always returns the same GlobalFields class, so Python never raises AttributeError for a call on the wrong instance. The UID you pass decides which methods do useful work.

  • Call stack.global_fields() without a UID to work across global fields, for example find and create.
  • Call stack.global_fields('<GLOBAL_FIELD_UID>') to work with one global field, for example fetch and delete.

The Method Index below lists the full set for each group.

When a method that needs a UID runs on an instance without one, the method produces one of the following results:

  • export raises Exception before any request.
  • fetch, update and delete send the request with None in the path, for example GET global_fields/None, and the API answers with an error body.

Warning The UID check in export tests only for None. An empty string passes it, and stack.global_fields('').fetch() sends GET global_fields/ instead of a single global field request. Check the UID variable before you pass it.

Class-Level Notes

The api_version option.

  • To work with nested global fields, pass options={'api_version': '3.2'} to stack.global_fields().
  • When options holds an api_version key, the SDK writes its value, as a string, into the api_version header of the client as soon as you call stack.global_fields().
  • After the first request from that object returns, the SDK removes the header. The outcomes are as follows:
    • Only the first request from the object includes api_version. Call stack.global_fields(..., options=...) again for each request that needs it.
    • Every object from the client shares the header dictionary. A request from another class that runs before that first request also carries api_version.
    • When the first request raises a network exception, the SDK does not remove the header, and it stays on later requests from the client.

Branch scoping.

  • stack.global_fields() takes no branch argument. Call the add_header method with the branch key to send a request to a branch.
  • The header stays on every later request from the client until you change it.

Content-Type header after an import.

  • imports sets the shared Content-Type header of the client to multipart/form-data and does not restore it. Every later JSON request from the same client, from any class, then includes that header.
  • After an import, call add_header('Content-Type', 'application/json') before you send a JSON body, or create a new Client.

Method Index

The groups below follow the Instance State split: the first group works without a UID, and the second needs stack.global_fields('<GLOBAL_FIELD_UID>').

Work across global fields. Available on stack.global_fields(). These methods do not read the UID.

Method NameReturnsDescription
findThe global fields in the stack, or the API error body.Lists the global fields of the stack.
createThe new global field, or the API error body.Creates a global field from a schema.
importsThe imported global field, or the API error body.Imports a global field from a JSON file.

Work with one global field. Available on stack.global_fields('<GLOBAL_FIELD_UID>').

Method NameReturnsDescription
fetchThe requested global field, or the API error body.Reads one global field by its UID.
updateThe updated global field, or the API error body.Replaces the schema of the global field.
exportThe exported global field schema, or the API error body.Returns the global field as JSON.
deleteThe deletion notice, or the API error body.Deletes the global field.

This class also inherits the add_header, add_header_dict, add_param and add_param_dict methods from Parameter.

Class-Level Snippet

The snippet below creates a global field, reads it back, then lists every global field in the stack with a count.

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')
stack = client.stack(api_key='<API_KEY>')

data = {
    "global_field": {
        "title": "docs-test-seo",
        "uid": "docs_test_seo",
        "schema": [
            {"display_name": "Meta Title", "uid": "meta_title", "data_type": "text"}
        ]
    }
}

try:
    created = stack.global_fields().create(data)
    print('created:', created.status_code)

    global_field = stack.global_fields('docs_test_seo').fetch()
    print('title:', global_field.json()['global_field']['title'])

    query = stack.global_fields()
    query.add_param('include_count', 'true')
    listing = query.find()
    print('global fields:', listing.json().get('count'))
except Exception as error:
    print('Global field request failed:', error)

Methods

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

create

create creates a global field in the stack from the schema you pass.

NameTypeDescription
data (required)dict

Request body with the global field under a global_field key.

Default: Not applicable
data["global_field"]["title"] (required)str

Sets the display name of the global field.

Default: Not applicable
data["global_field"]["uid"] (required)str

Sets the UID of the new global field.

Default: Not applicable
data["global_field"]["schema"] (required)list[dict]

Defines the fields inside the global field.

Default: Not applicable

Returns: requests.Response. The new global field, or the API error body.

Validation

  • create does not check data. The SDK serializes the dictionary with json.dumps and sends it unchanged. A value that json.dumps cannot serialize raises TypeError before the request.
  • Calling create without data raises TypeError, because data is a positional parameter with no default.
  • Errors surface as follows:
    • create raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API rejection returns as a normal Response with a 4xx status code. It does not raise an exception.
    • Check status_code and read json() for error_message, error_code, and errors.

Additional Resources Refer to Create a global field for the request body, and to Management API Errors for the error codes the API returns.

Behavior

  • Sends one POST request to /global_fields with data as the JSON request body.
  • create does not read the global field UID of the instance. The new UID comes from data["global_field"]["uid"].
  • When you pass options={'api_version': ...} to stack.global_fields(), create sends the api_version header and then removes it from the client. See the Global Fields class page.
  • Only the stack owner, administrators and developers can create global fields, as the Create a global field section states.

Example

Basic usage: create a global field with one text field

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')

data = {
    "global_field": {
        "title": "docs-test-seo",
        "uid": "docs_test_seo",
        "schema": [
            {"display_name": "Meta Title", "uid": "meta_title", "data_type": "text"}
        ]
    }
}

try:
    response = client.stack(api_key='<API_KEY>').global_fields().create(data)
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if response.status_code >= 400:
        # The API rejected the request and returned the error body
        print('API error:', response.status_code, response.json().get('error_message'))
    else:
        print(response.json()['global_field']['uid'])

Nested global field: create a global field that holds another one, using a management token

import contentstack_management

client = contentstack_management.Client(management_token='<MANAGEMENT_TOKEN>')

data = {
    "global_field": {
        "title": "docs-test-page-meta",
        "uid": "docs_test_page_meta",
        "schema": [
            {"display_name": "Heading", "uid": "heading", "data_type": "text"},
            {
                "display_name": "SEO",
                "uid": "seo",
                "data_type": "global_field",
                "reference_to": "docs_test_seo"
            }
        ]
    }
}

try:
    response = client.stack(api_key='<API_KEY>').global_fields(options={'api_version': '3.2'}).create(data)
    print(response.status_code, response.json())
except Exception as error:
    print('Request failed:', error)

delete

delete deletes the global field whose UID you passed to stack.global_fields().

This method takes no parameters. It reads the global field UID from the instance and sends the query parameters that the instance holds.

Returns: requests.Response. The deletion notice, or the API error body.

Warning You cannot undo the deletion. With force set to true, the API deletes the global field even when content types use it.

Validation

  • delete does not check the global field UID. On stack.global_fields() without a UID, it sends DELETE global_fields/None.
  • Errors surface as follows:
    • delete raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API rejection returns as a normal Response with a 4xx status code. It does not raise an exception.
    • Check status_code and read json() for error_message, error_code, and errors.
  • The API rejects the request when a content type uses the global field and the request does not carry force=true, as the Delete global field section states.

Additional Resources Refer to Delete global field for the request, and to Management API Errors for the error codes the API returns.

Behavior

  • Sends one DELETE request to /global_fields/{global_field_uid}.
  • delete sends no force parameter of its own. Call add_param('force', 'true') before delete to delete a global field that a content type uses.
  • When you pass options={'api_version': ...} to stack.global_fields(), delete sends the api_version header and then removes it from the client. See the Global Fields class page.

Example

Basic usage: delete a global field that no content type uses

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')

try:
    response = client.stack(api_key='<API_KEY>').global_fields('<GLOBAL_FIELD_UID>').delete()
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if response.status_code >= 400:
        # The API rejected the request and returned the error body
        print('API error:', response.status_code, response.json().get('error_message'))
    else:
        print(response.json().get('notice'))

Force delete: delete a global field that content types use, using a management token

import contentstack_management

client = contentstack_management.Client(management_token='<MANAGEMENT_TOKEN>')

try:
    global_field = client.stack(api_key='<API_KEY>').global_fields('<GLOBAL_FIELD_UID>')
    global_field.add_param('force', 'true')
    response = global_field.delete()
    print(response.status_code, response.json())
except Exception as error:
    print('Request failed:', error)

export

export returns the schema of the global field whose UID you passed to stack.global_fields(), as JSON that the imports method can read back.

This method takes no parameters. It reads the global field UID from the instance and sends the query parameters that the instance holds.

Returns: requests.Response. The exported global field schema, or the API error body.

Validation

  • export raises Exception when the instance holds no global field UID, because the request path needs one. The check tests only for None, so an empty string passes it.
  • Errors surface as follows:
    • export raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API rejection returns as a normal Response with a 4xx status code. It does not raise an exception.
    • Check status_code and read json() for error_message, error_code, and errors.

Additional Resources Refer to Export a global field for the request, and to Management API Errors for the error codes the API returns.

Behavior

  • Sends one GET request to /global_fields/{global_field_uid}/export and adds no default query parameters.
  • export returns the export in the response body and does not write a file. Write response.content to a file to keep it.
  • When you pass options={'api_version': ...} to stack.global_fields(), export sends the api_version header and then removes it from the client. See the Global Fields class page.
  • The client timeout defaults to 2 seconds. Pass a larger timeout to Client when you export a large global field.

Example

Basic usage: export a global field to a JSON file

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')

try:
    response = client.stack(api_key='<API_KEY>').global_fields('<GLOBAL_FIELD_UID>').export()
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if response.status_code >= 400:
        # The API rejected the request and returned the error body
        print('API error:', response.status_code, response.json().get('error_message'))
    else:
        with open('<FILE_PATH>', 'wb') as file:
            file.write(response.content)

Longer timeout: export with a management token

import contentstack_management

client = contentstack_management.Client(management_token='<MANAGEMENT_TOKEN>', timeout=30)

try:
    response = client.stack(api_key='<API_KEY>').global_fields('<GLOBAL_FIELD_UID>').export()
    print(response.status_code, response.json())
except Exception as error:
    print('Request failed:', error)

Error handling: call export without a global field UID

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')

try:
    response = client.stack(api_key='<API_KEY>').global_fields().export()
except Exception as error:
    # Raised before any request because the instance holds no global field UID
    print('Missing UID:', error)

fetch

fetch returns one global field, with its schema, by the UID you passed to stack.global_fields().

This method takes no parameters. It reads the global field UID from the instance and sends the query parameters that the instance holds.

Returns: requests.Response. The requested global field, or the API error body.

Validation

  • fetch does not check the global field UID. On stack.global_fields() without a UID, it sends GET global_fields/None.
  • Errors surface as follows:
    • fetch raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API rejection returns as a normal Response with a 4xx status code. It does not raise an exception.
    • Check status_code and read json() for error_message, error_code, and errors.

Additional Resources Refer to Get a single global field for the query parameters, and to Management API Errors for the error codes the API returns.

Behavior

  • Sends one GET request to /global_fields/{global_field_uid} and adds no default query parameters.
  • Use the add_param method to send the parameters that the Get a single global field section lists. For example, version reads an earlier version, and include_content_types lists the content types that use the global field.
  • When you pass options={'api_version': ...} to stack.global_fields(), fetch sends the api_version header and then removes it from the client. See the Global Fields class page.

Example

Basic usage: read one global field by UID

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')

try:
    response = client.stack(api_key='<API_KEY>').global_fields('<GLOBAL_FIELD_UID>').fetch()
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if response.status_code >= 400:
        # The API rejected the request and returned the error body
        print('API error:', response.status_code, response.json().get('error_message'))
    else:
        print(response.json()['global_field']['title'])

Nested global field: read with the api_version option and the content types that use it

import contentstack_management

client = contentstack_management.Client(management_token='<MANAGEMENT_TOKEN>')

try:
    global_field = client.stack(api_key='<API_KEY>').global_fields('<GLOBAL_FIELD_UID>', options={'api_version': '3.2'})
    global_field.add_param('include_content_types', 'true')
    response = global_field.fetch()
    print(response.status_code, response.json())
except Exception as error:
    print('Request failed:', error)

find

find returns every global field in the stack.

This method takes no parameters. It sends the query parameters that the instance holds.

Returns: requests.Response. The global fields in the stack, or the API error body.

Validation

  • find does not check anything before it sends the request.
  • Errors surface as follows:
    • find raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API rejection returns as a normal Response with a 4xx status code. It does not raise an exception.
    • Check status_code and read json() for error_message, error_code, and errors.

Additional Resources Refer to Get all global fields for the query parameters, and to Management API Errors for the error codes the API returns.

Behavior

  • Sends one GET request to /global_fields. find does not read the global field UID, so stack.global_fields('<GLOBAL_FIELD_UID>').find() still lists every global field.
  • find adds no default query parameters. Use the add_param method to send the parameters that the Get all global fields section lists, for example include_count, include_global_field_schema and include_content_types.
  • When you pass options={'api_version': ...} to stack.global_fields(), find sends the api_version header and then removes it from the client. See the Global Fields class page.
  • The SDK sends one request and does not page through the results.

Example

Basic usage: list the global fields of a stack

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')

try:
    response = client.stack(api_key='<API_KEY>').global_fields().find()
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if response.status_code >= 400:
        # The API rejected the request and returned the error body
        print('API error:', response.status_code, response.json().get('error_message'))
    else:
        for global_field in response.json()['global_fields']:
            print(global_field['uid'], global_field['title'])

Nested global fields: list with the count and nested schemas, using a management token

import contentstack_management

client = contentstack_management.Client(management_token='<MANAGEMENT_TOKEN>')

try:
    query = client.stack(api_key='<API_KEY>').global_fields(options={'api_version': '3.2'})
    query.add_param('include_count', 'true')
    query.add_param('include_global_field_schema', 'true')
    response = query.find()
    print(response.status_code, response.json())
except Exception as error:
    print('Request failed:', error)

imports

imports creates a global field in the stack by uploading a JSON file of its schema, such as the file that the export method returns.

NameTypeDescription
file_path (required)str

Path to the JSON file of the global field.

Default: Not applicable

Returns: requests.Response. The imported global field, or the API error body.

Validation

  • Calling imports without file_path raises TypeError, because file_path is a positional parameter with no default.
  • imports opens the file before it sends the request. A path that does not exist raises FileNotFoundError, and the SDK sends nothing.
  • imports does not check the file contents.
  • Errors surface as follows:
    • imports raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API rejection returns as a normal Response with a 4xx status code. It does not raise an exception.
    • Check status_code and read json() for error_message, error_code, and errors.

Additional Resources Refer to Import a global field for the request, and to Management API Errors for the error codes the API returns.

Behavior

  • Sends one POST request to /global_fields/import, with the file as a multipart form field named global_field.
  • imports does not read the global field UID of the instance. The UID of the new global field comes from the file.
  • imports sets the shared Content-Type header of the client to multipart/form-data and does not restore it. Every later JSON request from the same client carries that header. Call add_header('Content-Type', 'application/json') after the import, before you send a JSON body.
  • imports opens the file and does not close it.
  • When you pass options={'api_version': ...} to stack.global_fields(), imports sends the api_version header and then removes it from the client. See the Global Fields class page.
  • The client timeout defaults to 2 seconds. Pass a larger timeout to Client when you import a large file.

Example

Basic usage: import a global field from a JSON file

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>', timeout=30)

try:
    response = client.stack(api_key='<API_KEY>').global_fields().imports('<FILE_PATH>')
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if response.status_code >= 400:
        # The API rejected the request and returned the error body
        print('API error:', response.status_code, response.json().get('error_message'))
    else:
        print(response.json())

Restore the JSON header: import, then create another global field

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>', timeout=30)
global_fields = client.stack(api_key='<API_KEY>').global_fields()

try:
    response = global_fields.imports('<FILE_PATH>')
    print(response.status_code, response.json())
    # imports leaves multipart/form-data on the shared headers
    global_fields.add_header('Content-Type', 'application/json')
    created = global_fields.create({
        "global_field": {
            "title": "docs-test-author",
            "uid": "docs_test_author",
            "schema": [{"display_name": "Name", "uid": "name", "data_type": "text"}]
        }
    })
    print(created.status_code, created.json())
except Exception as error:
    print('Request failed:', error)

Error handling: a file path that does not exist

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')

try:
    response = client.stack(api_key='<API_KEY>').global_fields().imports('<FILE_PATH>')
except FileNotFoundError as error:
    # Raised before any request because the SDK cannot open the file
    print('File not found:', error)

update

update replaces the schema of the global field whose UID you passed to stack.global_fields().

NameTypeDescription
data (required)dict

Request body with the updated global field under a global_field key.

Default: Not applicable
data["global_field"]["title"] (required)str

Sets the display name of the global field.

Default: Not applicable
data["global_field"]["schema"] (required)list[dict]

Lists every field the global field keeps.

Default: Not applicable

Returns: requests.Response. The updated global field, or the API error body.

Validation

  • update does not check data. The SDK serializes the dictionary with json.dumps and sends it unchanged. A value that json.dumps cannot serialize raises TypeError before the request.
  • Calling update without data raises TypeError, because data is a positional parameter with no default.
  • update does not check the global field UID. On stack.global_fields() without a UID, it sends PUT global_fields/None.
  • Errors surface as follows:
    • update raises an exception only for network failures (timeout, DNS error, dropped connection).
    • An API rejection returns as a normal Response with a 4xx status code. It does not raise an exception.
    • Check status_code and read json() for error_message, error_code, and errors.

Additional Resources Refer to Update a global field for the request body, and to Management API Errors for the error codes the API returns.

Behavior

  • Sends one PUT request to /global_fields/{global_field_uid} with data as the JSON request body.
  • The body replaces the global field schema. Start from the current schema, which the fetch method returns, and change it, so the update keeps the fields you want.
  • When you pass options={'api_version': ...} to stack.global_fields(), update sends the api_version header and then removes it from the client. See the Global Fields class page.

Example

Basic usage: rename a global field and keep its schema

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')
global_field = client.stack(api_key='<API_KEY>').global_fields('<GLOBAL_FIELD_UID>')

try:
    current = global_field.fetch().json()['global_field']
    current['title'] = 'docs-test-seo-updated'
    response = global_field.update({"global_field": current})
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if response.status_code >= 400:
        # The API rejected the request and returned the error body
        print('API error:', response.status_code, response.json().get('error_message'))
    else:
        print(response.json()['global_field']['title'])

Full body: replace the schema of a nested global field, using a management token

import contentstack_management

client = contentstack_management.Client(management_token='<MANAGEMENT_TOKEN>')

data = {
    "global_field": {
        "title": "docs-test-seo",
        "schema": [
            {"display_name": "Meta Title", "uid": "meta_title", "data_type": "text"},
            {"display_name": "Meta Description", "uid": "meta_description", "data_type": "text"}
        ]
    }
}

try:
    response = client.stack(api_key='<API_KEY>').global_fields('<GLOBAL_FIELD_UID>', options={'api_version': '3.2'}).update(data)
    print(response.status_code, response.json())
except Exception as error:
    print('Request failed:', error)