Parameter

View as Markdown

Parameter

Parameter is the base class of every resource class in the SDK, for example Stack, Entry, and Assets. It gives each object four methods that add request headers and query parameters to its calls. Use these methods to

  • send a header the SDK does not set, such as api_version or branch
  • send a query parameter the method does not take as an argument, such as include_count or locale

You never create a Parameter yourself. Every object that a Client returns, from client.stack() down to entry.variants(), inherits these methods, so you call them on the object you already hold.

Class-Level Notes

Every object from one client shares the headers.

  • Every object that one Client creates writes to and reads from one header dictionary, the one the client stores.
  • add_header and add_header_dict write into that shared dictionary. A header you add on an Entry also goes out on the next Asset, Stack, or Entry request from the same client.
  • The SDK writes to the same dictionary in two other places:
    • client.stack('<API_KEY>') sets the api_key header. A second client.stack('<OTHER_API_KEY>') replaces it for every stack object from that client.
    • A branch argument, for example stack.content_types('<CONTENT_TYPE_UID>', branch='<BRANCH_UID>'), sets the branch header. It stays on every later request from that client until something replaces it.
  • No method removes a header. To stop sending one, set its value to None with add_header. The requests library leaves a header whose value is None out of the request.
  • Use a separate Client for each stack or branch that you work with at the same time.

Query parameters belong to one object.

  • add_param and add_param_dict write to the params dictionary of the object you call them on. Another object, even one from the same client, does not see them.
  • The parameters stay on the object and go out with every later call that sends them. No method removes a parameter.
  • Most request methods send the recorded parameters. A few do not read them, for example Assets.publish, Assets.unpublish, and Assets.delete_folder, so a parameter you add has no effect on those calls.
  • Some methods write their own arguments into the same dictionary. For example, Entry.create records locale, and the value stays on the Entry object for its later calls.

Client-side only.

  • None of the four methods sends a request or checks a value. A value the API rejects fails on the request method you call next.

Method Index

Method NameReturnsDescription
add_headerThe method returns nothing.Adds one header to every request from the client.
add_header_dictThe method returns nothing.Adds several headers to every request from the client.
add_paramThe method returns nothing.Adds one query parameter to this object's requests.
add_param_dictThe method returns nothing.Adds several query parameters to this object's requests.

Class-Level Snippet

The snippet below adds a branch header and two query parameters, then lists the entries of a content type with them.

import contentstack_management

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

# The header goes on every later request from this client
entry.add_header('branch', '<BRANCH_UID>')

# The parameters go only on requests from this entry object
entry.add_param_dict({'include_count': 'true', 'locale': '<LOCALE_CODE>'})

try:
    response = entry.find()
    print(response.status_code, response.json().get('count'))
except Exception as error:
    print('Request failed:', error)

Methods

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

add_header

add_header adds one header to the header dictionary that every object from the same client sends.

NameTypeDescription
key (required)str

Name of the header, for example branch.

Default: Not applicable
value (required)str | None

Value to send. None stops sending the header.

Default: Not applicable

Returns: None. The method returns nothing.

Validation

  • add_header does not check key or value. It stores both as given and makes no request.
  • Omitting either argument raises TypeError, because both are positional parameters with no default.
  • A value that is not a string or None, for example the number 2, fails later. The next request from the client raises requests.exceptions.InvalidHeader, because the requests library accepts only string or bytes header values.
  • Errors that the API returns come from the request method you call next, not from add_header.

Behavior

  • Client-side only. add_header writes the pair into the header dictionary that the client holds, and makes no request.
  • Every object from the same client shares that dictionary. The header goes out on every later request from the client, whichever object sends it.
  • A second call with the same key replaces the value. The last call wins.
  • A header with the value None stays in the dictionary, but the requests library leaves it out of the request. Use this to stop sending a header that you or the SDK set earlier.
  • add_header also replaces a header that the SDK set, for example api_key from client.stack() or Content-Type.

Example

Basic usage: send a branch header on an entry request

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')
entry = client.stack(api_key='<API_KEY>').content_types('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>')
entry.add_header('branch', '<BRANCH_UID>')

try:
    response = entry.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()['entry']['title'])

Edge case: the header reaches every object from the client

import contentstack_management

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

# Added on an entry object, sent by the asset request as well
stack.content_types('<CONTENT_TYPE_UID>').entry().add_header('branch', '<BRANCH_UID>')

try:
    response = stack.assets().find()
    print(response.status_code, response.json())
except Exception as error:
    print('Request failed:', error)

Stop sending a header: set its value to None

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')
stack = client.stack(api_key='<API_KEY>')
content_type = stack.content_types('<CONTENT_TYPE_UID>', branch='<BRANCH_UID>')

# The branch argument set a shared branch header. None leaves it out of later requests.
content_type.add_header('branch', None)

try:
    response = content_type.entry().find()
    print(response.status_code, response.json())
except Exception as error:
    print('Request failed:', error)

add_header_dict

add_header_dict adds every pair in a dictionary to the header dictionary that every object from the same client sends.

NameTypeDescription
headers (required)dict

Header names mapped to the values to send.

Default: Not applicable

Returns: None. The method returns nothing.

Validation

  • add_header_dict does not check the names or the values. It merges the dictionary into the client headers with dict.update and makes no request.
  • Omitting headers raises TypeError, because it is a positional parameter with no default.
  • Passing None or another value that dict.update cannot read, such as a string, raises TypeError or ValueError at once.
  • A value that is not a string or None fails later. The next request from the client raises requests.exceptions.InvalidHeader.
  • Errors that the API returns come from the request method you call next, not from add_header_dict.

Behavior

  • Client-side only. add_header_dict merges the pairs into the header dictionary that the client holds, and makes no request.
  • Every object from the same client shares that dictionary, so the headers go out on every later request from the client.
  • A name that already exists takes the new value. Names that the dictionary does not mention keep their values.
  • A header with the value None stays in the dictionary, but the requests library leaves it out of the request.
  • Use the add_header method to add a single header.

Example

Basic usage: send a branch and an API version header

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')
entry = client.stack(api_key='<API_KEY>').content_types('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>')
entry.add_header_dict({'branch': '<BRANCH_UID>', 'api_version': '3.2'})

try:
    response = entry.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()['entry']['title'])

Error handling: a None argument raises TypeError

import contentstack_management

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

extra_headers = None

try:
    entry.add_header_dict(extra_headers)
except TypeError as error:
    # Fires because dict.update cannot read None
    print('Pass a dictionary of headers:', error)

add_param

add_param adds one query parameter to the requests that this object sends.

NameTypeDescription
key (required)str

Name of the query parameter, for example locale.

Default: Not applicable
value (required)Any

Value to send. None leaves the parameter out.

Default: Not applicable

Returns: None. The method returns nothing.

Validation

  • add_param does not check key or value. It stores both in the params dictionary of the object and makes no request.
  • Omitting either argument raises TypeError, because both are positional parameters with no default.
  • Errors that the API returns come from the request method you call next, not from add_param.

Behavior

  • Client-side only. add_param writes the pair into the params dictionary of the object you call it on, and makes no request.
  • The parameter belongs to this object only. Another object from the same client does not send it.
  • The parameter stays on the object and goes out with every later call that sends params. No method removes it.
  • A second call with the same key replaces the value. A method that writes the same key itself, for example locale in Entry.create, also replaces it.
  • The requests library encodes each value on the request in one of the following ways:
    • A Python True becomes the text True. Pass the string 'true' for a flag.
    • A list becomes one key=value pair per item.
    • None leaves the parameter out of the request.
  • A few methods do not send params, for example Assets.publish. A parameter you add has no effect on those calls.

Example

Basic usage: list entries in one locale

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')
entry = client.stack(api_key='<API_KEY>').content_types('<CONTENT_TYPE_UID>').entry()
entry.add_param('locale', '<LOCALE_CODE>')

try:
    response = entry.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 item in response.json()['entries']:
            print(item['uid'], item['title'])

Flag parameter: pass the string 'true', not True

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')
entry = client.stack(api_key='<API_KEY>').content_types('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>')

# A Python True would go out as the text True
entry.add_param('include_publish_details', 'true')

try:
    response = entry.fetch()
    print(response.status_code, response.json())
except Exception as error:
    print('Request failed:', error)

add_param_dict

add_param_dict adds every pair in a dictionary to the query parameters that this object sends.

NameTypeDescription
parameters (required)dict

Parameter names mapped to the values to send.

Default: Not applicable

Returns: None. The method returns nothing.

Validation

  • add_param_dict does not check the names or the values. It merges the dictionary into the params dictionary of the object with dict.update and makes no request.
  • Omitting parameters raises TypeError, because it is a positional parameter with no default.
  • Passing None or another value that dict.update cannot read, such as a string, raises TypeError or ValueError at once.
  • Errors that the API returns come from the request method you call next, not from add_param_dict.

Behavior

  • Client-side only. add_param_dict merges the pairs into the params dictionary of the object you call it on, and makes no request.
  • The parameters belong to this object only, and stay on it for every later call that sends params.
  • A name that already exists takes the new value. Names that the dictionary does not mention keep their values.
  • The requests library encodes the values the same way as for the add_param method. A Python True becomes the text True, so pass the string 'true' for a flag.

Example

Basic usage: list entries with a count and publish details

import contentstack_management

client = contentstack_management.Client(authtoken='<AUTHTOKEN>')
entry = client.stack(api_key='<API_KEY>').content_types('<CONTENT_TYPE_UID>').entry()
entry.add_param_dict({
    'include_count': 'true',
    'include_publish_details': 'true',
    'locale': '<LOCALE_CODE>'
})

try:
    response = entry.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:
        print('Total entries:', response.json().get('count'))

Error handling: a None argument raises TypeError

import contentstack_management

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

extra_params = None

try:
    entry.add_param_dict(extra_params)
except TypeError as error:
    # Fires because dict.update cannot read None
    print('Pass a dictionary of query parameters:', error)