Skip to content

Data Templates

albert.collections.data_templates

Functions:

Name Description
generate_data_template_patches

DataTemplateId module-attribute

DataTemplateId = Annotated[
    str, AfterValidator(ensure_datatemplate_id)
]

logger module-attribute

logger = create_logger()

AlbertHTTPError

AlbertHTTPError(response: Response)

Bases: AlbertException

Base class for all erors due to HTTP responses.

Source code in src/albert/exceptions.py
def __init__(self, response: requests.Response):
    message = self._format_message(response)
    super().__init__(message)
    self.response = response

response instance-attribute

response = response

AlbertPaginator

AlbertPaginator(
    *,
    path: str,
    mode: PaginationMode,
    session: AlbertSession,
    deserialize: Callable[
        [Iterable[dict]], Iterable[ItemType]
    ],
    params: dict[str, str] | None = None,
)

Bases: Iterator[ItemType]

Helper class for pagination through Albert endpoints.

Two pagination modes are possible: - Offset-based via by the offset query parameter - Key-based via by the startKey query parameter and 'lastKey' response field

A custom deserialize function is provided when additional logic is required to load the raw items returned by the search listing, e.g., making additional Albert API calls.

Source code in src/albert/core/pagination.py
def __init__(
    self,
    *,
    path: str,
    mode: PaginationMode,
    session: AlbertSession,
    deserialize: Callable[[Iterable[dict]], Iterable[ItemType]],
    params: dict[str, str] | None = None,
):
    self.path = path
    self.mode = mode
    self.session = session
    self.deserialize = deserialize

    params = params or {}
    self.params = {k: v for k, v in params.items() if v is not None}

    if "startKey" in self.params:
        self.params["startKey"] = quote_plus(self.params["startKey"])

    self._iterator = self._create_iterator()

deserialize instance-attribute

deserialize = deserialize

mode instance-attribute

mode = mode

params instance-attribute

params = {k: _qfor (k, v) in items() if v is not None}

path instance-attribute

path = path

session instance-attribute

session = session

AlbertSession

AlbertSession(
    *,
    base_url: str,
    token: str | None = None,
    auth_manager: AlbertClientCredentials
    | AlbertSSOClient
    | None = None,
    retries: int | None = None,
)

Bases: Session

A session that has a base URL, which is prefixed to all request URLs.

Parameters:

Name Type Description Default
base_url str

The base URL to prefix to all relative request paths (e.g., "https://app.albertinvent.com").

required
token str | None

A static JWT token for authentication. Ignored if auth_manager is provided.

None
auth_manager AlbertClientCredentials | AlbertSSOClient

An authentication manager used to dynamically fetch and refresh tokens. If provided, it overrides token.

None
retries int

The number of automatic retries on failed requests (default is 3).

None

Methods:

Name Description
request
Source code in src/albert/core/session.py
def __init__(
    self,
    *,
    base_url: str,
    token: str | None = None,
    auth_manager: AlbertClientCredentials | AlbertSSOClient | None = None,
    retries: int | None = None,
):
    super().__init__()
    self.base_url = base_url
    self.headers.update(
        {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": f"albert-SDK V.{albert.__version__}",
        }
    )

    if token is None and auth_manager is None:
        raise ValueError("Either `token` or `auth_manager` must be specified.")

    self._auth_manager = auth_manager
    self._provided_token = token

    # Set up retry logic
    retries = retries if retries is not None else 3
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=0.3,
        status_forcelist=(500, 502, 503, 504, 403),
        raise_on_status=False,
    )
    adapter = HTTPAdapter(max_retries=retry)
    self.mount("http://", adapter)
    self.mount("https://", adapter)

base_url instance-attribute

base_url = base_url

request

request(
    method: str, path: str, *args, **kwargs
) -> Response
Source code in src/albert/core/session.py
def request(self, method: str, path: str, *args, **kwargs) -> requests.Response:
    self.headers["Authorization"] = f"Bearer {self._access_token}"
    full_url = urljoin(self.base_url, path) if not path.startswith("http") else path
    with handle_http_errors():
        response = super().request(method, full_url, *args, **kwargs)
        response.raise_for_status()
        return response

BaseCollection

BaseCollection(*, session: AlbertSession)

BaseCollection is the base class for all collection classes.

Parameters:

Name Type Description Default
session AlbertSession

The Albert API Session instance.

required
Source code in src/albert/collections/base.py
def __init__(self, *, session: AlbertSession):
    self.session = session

session instance-attribute

session = session

DCPatchDatum

Bases: PGPatchPayload

data class-attribute instance-attribute

data: list[GeneralPatchDatum] = Field(
    default_factory=list,
    description="The data to be updated in the data column.",
)

DataColumnValue pydantic-model

Bases: BaseAlbertModel

Show JSON schema:
{
  "$defs": {
    "AuditFields": {
      "description": "The audit fields for a resource",
      "properties": {
        "by": {
          "default": null,
          "title": "By",
          "type": "string"
        },
        "byName": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Byname"
        },
        "at": {
          "anyOf": [
            {
              "format": "date-time",
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "At"
        }
      },
      "title": "AuditFields",
      "type": "object"
    },
    "DataColumn": {
      "properties": {
        "status": {
          "anyOf": [
            {
              "$ref": "#/$defs/Status"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Created": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Updated": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "name": {
          "title": "Name",
          "type": "string"
        },
        "defalt": {
          "default": false,
          "title": "Defalt",
          "type": "boolean"
        },
        "Metadata": {
          "anyOf": [
            {
              "additionalProperties": {
                "anyOf": [
                  {
                    "type": "number"
                  },
                  {
                    "type": "integer"
                  },
                  {
                    "type": "string"
                  },
                  {
                    "$ref": "#/$defs/EntityLink"
                  },
                  {
                    "items": {
                      "$ref": "#/$defs/EntityLink"
                    },
                    "type": "array"
                  }
                ]
              },
              "type": "object"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Metadata"
        },
        "albertId": {
          "default": null,
          "title": "Albertid",
          "type": "string"
        }
      },
      "required": [
        "name"
      ],
      "title": "DataColumn",
      "type": "object"
    },
    "DataType": {
      "enum": [
        "number",
        "string",
        "enum"
      ],
      "title": "DataType",
      "type": "string"
    },
    "EntityLink": {
      "properties": {
        "id": {
          "title": "Id",
          "type": "string"
        },
        "name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Name"
        }
      },
      "required": [
        "id"
      ],
      "title": "EntityLink",
      "type": "object"
    },
    "EnumValidationValue": {
      "description": "Represents a value for an enum type validation.\n\nAttributes\n----------\ntext : str\n    The text of the enum value.\nid : str | None\n    The ID of the enum value. If not provided, the ID will be generated upon creation.",
      "properties": {
        "text": {
          "title": "Text",
          "type": "string"
        },
        "id": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Id"
        },
        "originalText": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Originaltext"
        }
      },
      "required": [
        "text"
      ],
      "title": "EnumValidationValue",
      "type": "object"
    },
    "Operator": {
      "enum": [
        "between",
        "lt",
        "lte",
        "gte",
        "gt",
        "eq"
      ],
      "title": "Operator",
      "type": "string"
    },
    "Status": {
      "description": "The status of a resource",
      "enum": [
        "active",
        "inactive"
      ],
      "title": "Status",
      "type": "string"
    },
    "Unit": {
      "description": "Unit is a Pydantic model representing a unit entity.\n\nAttributes\n----------\nid : str | None\n    The Albert ID of the unit. Set when the unit is retrieved from Albert.\nname : str\n    The name of the unit.\nsymbol : str | None\n    The symbol of the unit.\nsynonyms : List[str] | None\n    The list of synonyms for the unit.\ncategory : UnitCategory\n    The category of the unit.\nverified : bool | None\n    Whether the unit is verified.\nstatus : Status | None\n    The status of the unit. Allowed values are `active`, and `inactive`",
      "properties": {
        "status": {
          "anyOf": [
            {
              "$ref": "#/$defs/Status"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Created": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Updated": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "albertId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Albertid"
        },
        "name": {
          "title": "Name",
          "type": "string"
        },
        "symbol": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Symbol"
        },
        "Synonyms": {
          "anyOf": [
            {
              "items": {
                "type": "string"
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "title": "Synonyms"
        },
        "category": {
          "anyOf": [
            {
              "$ref": "#/$defs/UnitCategory"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "verified": {
          "anyOf": [
            {
              "type": "boolean"
            },
            {
              "type": "null"
            }
          ],
          "default": false,
          "title": "Verified"
        }
      },
      "required": [
        "name"
      ],
      "title": "Unit",
      "type": "object"
    },
    "UnitCategory": {
      "description": "UnitCategory is an enumeration of possible unit categories.\n\nAttributes\n----------\nLENGTH : str\n    Represents length units.\nVOLUME : str\n    Represents volume units.\nLIQUID_VOLUME : str\n    Represents liquid volume units.\nANGLES : str\n    Represents angle units.\nTIME : str\n    Represents time units.\nFREQUENCY : str\n    Represents frequency units.\nMASS : str\n    Represents mass units.\nCURRENT : str\n    Represents electric current units.\nTEMPERATURE : str\n    Represents temperature units.\nAMOUNT : str\n    Represents amount of substance units.\nLUMINOSITY : str\n    Represents luminous intensity units.\nFORCE : str\n    Represents force units.\nENERGY : str\n    Represents energy units.\nPOWER : str\n    Represents power units.\nPRESSURE : str\n    Represents pressure units.\nELECTRICITY_AND_MAGNETISM : str\n    Represents electricity and magnetism units.\nOTHER : str\n    Represents other units.\nWEIGHT : str\n    Represents weight units.",
      "enum": [
        "Length",
        "Volume",
        "Liquid volume",
        "Angles",
        "Time",
        "Frequency",
        "Mass",
        "Electric current",
        "Temperature",
        "Amount of substance",
        "Luminous intensity",
        "Force",
        "Energy",
        "Power",
        "Pressure",
        "Electricity and magnetism",
        "Other",
        "Weight",
        "Area",
        "Surface Area",
        "Binary",
        "Capacitance",
        "Speed",
        "Electrical conductivity",
        "Electrical permitivitty",
        "Density",
        "Resistance"
      ],
      "title": "UnitCategory",
      "type": "string"
    },
    "ValueValidation": {
      "properties": {
        "datatype": {
          "$ref": "#/$defs/DataType"
        },
        "value": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "items": {
                "$ref": "#/$defs/EnumValidationValue"
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Value"
        },
        "min": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Min"
        },
        "max": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Max"
        },
        "operator": {
          "anyOf": [
            {
              "$ref": "#/$defs/Operator"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        }
      },
      "required": [
        "datatype"
      ],
      "title": "ValueValidation",
      "type": "object"
    }
  },
  "properties": {
    "data_column": {
      "$ref": "#/$defs/DataColumn",
      "default": null
    },
    "id": {
      "default": null,
      "title": "Id",
      "type": "string"
    },
    "value": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Value"
    },
    "hidden": {
      "default": false,
      "title": "Hidden",
      "type": "boolean"
    },
    "Unit": {
      "anyOf": [
        {
          "$ref": "#/$defs/Unit"
        },
        {
          "$ref": "#/$defs/EntityLink"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Unit"
    },
    "calculation": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Calculation"
    },
    "sequence": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Sequence"
    },
    "validation": {
      "anyOf": [
        {
          "items": {
            "$ref": "#/$defs/ValueValidation"
          },
          "type": "array"
        },
        {
          "type": "null"
        }
      ],
      "title": "Validation"
    }
  },
  "title": "DataColumnValue",
  "type": "object"
}

Fields:

Validators:

calculation pydantic-field

calculation: str | None = None

data_column pydantic-field

data_column: DataColumn = None

data_column_id pydantic-field

data_column_id: str = None

hidden pydantic-field

hidden: bool = False

sequence pydantic-field

sequence: str | None = None

unit pydantic-field

unit: SerializeAsEntityLink[Unit] | None = None

validation pydantic-field

validation: list[ValueValidation] | None

value pydantic-field

value: str | None = None

check_for_id pydantic-validator

check_for_id()
Source code in src/albert/resources/data_templates.py
@model_validator(mode="after")
def check_for_id(self):
    if self.data_column_id is None and self.data_column is None:
        raise ValueError("Either data_column_id or data_column must be set")
    elif (
        self.data_column_id is not None
        and self.data_column is not None
        and self.data_column.id != self.data_column_id
    ):
        raise ValueError("If both are provided, data_column_id and data_column.id must match")
    elif self.data_column_id is None:
        self.data_column_id = self.data_column.id
    return self

DataTemplate

Bases: BaseTaggedResource

data_column_values class-attribute instance-attribute

data_column_values: list[DataColumnValue] | None = Field(
    alias="DataColumns", default=None
)

deleted_parameters class-attribute instance-attribute

deleted_parameters: list[ParameterValue] | None = Field(
    alias="DeletedParameters",
    default=None,
    frozen=True,
    exclude=True,
)

description class-attribute instance-attribute

description: str | None = None

id class-attribute instance-attribute

id: DataTemplateId | None = Field(None, alias='albertId')

metadata class-attribute instance-attribute

metadata: dict[str, MetadataItem] | None = Field(
    default=None, alias="Metadata"
)

name instance-attribute

name: str

parameter_values class-attribute instance-attribute

parameter_values: list[ParameterValue] | None = Field(
    alias="Parameters", default=None
)

security_class class-attribute instance-attribute

security_class: SecurityClass | None = None

users_with_access class-attribute instance-attribute

users_with_access: (
    list[SerializeAsEntityLink[User]] | None
) = Field(alias="ACL", default=None)

verified class-attribute instance-attribute

verified: bool = False

DataTemplateCollection

DataTemplateCollection(*, session: AlbertSession)

Bases: BaseCollection

DataTemplateCollection is a collection class for managing DataTemplate entities in the Albert platform.

Methods:

Name Description
add_data_columns

Adds data columns to a data template.

add_parameters

Adds parameters to a data template.

create

Creates a new data template.

delete

Deletes a data template by its ID.

get_all

Retrieve fully hydrated DataTemplate entities with optional filters.

get_by_id

Get a data template by its ID.

get_by_ids

Get a list of data templates by their IDs.

get_by_name

Get a data template by its name.

search

Search for DataTemplate matching the provided criteria.

update

Updates a data template.

Source code in src/albert/collections/data_templates.py
def __init__(self, *, session: AlbertSession):
    super().__init__(session=session)
    self.base_path = f"/api/{DataTemplateCollection._api_version}/datatemplates"

base_path instance-attribute

base_path = f'/api/{_api_version}/datatemplates'

add_data_columns

add_data_columns(
    *,
    data_template_id: DataTemplateId,
    data_columns: list[DataColumnValue],
) -> DataTemplate

Adds data columns to a data template.

Parameters:

Name Type Description Default
data_template_id str

The ID of the data template to add the columns to.

required
data_columns list[DataColumnValue]

The list of DataColumnValue objects to add to the data template.

required

Returns:

Type Description
DataTemplate

The updated DataTemplate object.

Source code in src/albert/collections/data_templates.py
def add_data_columns(
    self, *, data_template_id: DataTemplateId, data_columns: list[DataColumnValue]
) -> DataTemplate:
    """Adds data columns to a data template.

    Parameters
    ----------
    data_template_id : str
        The ID of the data template to add the columns to.
    data_columns : list[DataColumnValue]
        The list of DataColumnValue objects to add to the data template.

    Returns
    -------
    DataTemplate
        The updated DataTemplate object.
    """
    # if there are enum values, we need to add them as an allowed enum
    for column in data_columns:
        if (
            column.validation
            and len(column.validation) > 0
            and isinstance(column.validation[0].value, list)
        ):
            for enum_value in column.validation[0].value:
                self.session.put(
                    f"{self.base_path}/{data_template_id}/datacolumns/{column.sequence}/enums",
                    json=[
                        enum_value.model_dump(mode="json", by_alias=True, exclude_none=True)
                    ],
                )

    payload = {
        "DataColumns": [
            x.model_dump(mode="json", by_alias=True, exclude_none=True) for x in data_columns
        ]
    }
    self.session.put(
        f"{self.base_path}/{data_template_id}/datacolumns",
        json=payload,
    )
    return self.get_by_id(id=data_template_id)

add_parameters

add_parameters(
    *,
    data_template_id: DataTemplateId,
    parameters: list[ParameterValue],
) -> DataTemplate

Adds parameters to a data template.

Parameters:

Name Type Description Default
data_template_id str

The ID of the data template to add the columns to.

required
parameters list[ParameterValue]

The list of ParameterValue objects to add to the data template.

required

Returns:

Type Description
DataTemplate

The updated DataTemplate object.

Source code in src/albert/collections/data_templates.py
def add_parameters(
    self, *, data_template_id: DataTemplateId, parameters: list[ParameterValue]
) -> DataTemplate:
    """Adds parameters to a data template.

    Parameters
    ----------
    data_template_id : str
        The ID of the data template to add the columns to.
    parameters : list[ParameterValue]
        The list of ParameterValue objects to add to the data template.

    Returns
    -------
    DataTemplate
        The updated DataTemplate object.
    """
    # make sure the parameter values have a default validaion of string type.
    initial_enum_values = {}  # use index to track the enum values
    if parameters is None or len(parameters) == 0:
        return self.get_by_id(id=data_template_id)
    for i, param in enumerate(parameters):
        if (
            param.validation
            and len(param.validation) > 0
            and param.validation[0].datatype == DataType.ENUM
        ):
            initial_enum_values[i] = param.validation[0].value
            param.validation[0].value = None
            param.validation[0].datatype = DataType.STRING

    payload = {
        "Parameters": [
            x.model_dump(mode="json", by_alias=True, exclude_none=True) for x in parameters
        ]
    }
    # if there are enum values, we need to add them as an allowed enum
    response = self.session.put(
        f"{self.base_path}/{data_template_id}/parameters",
        json=payload,
    )
    returned_parameters = [ParameterValue(**x) for x in response.json()["Parameters"]]
    for i, param in enumerate(returned_parameters):
        if i in initial_enum_values:
            param.validation[0].value = initial_enum_values[i]
            param.validation[0].datatype = DataType.ENUM
    self._add_param_enums(
        data_template_id=data_template_id,
        new_parameters=returned_parameters,
    )
    dt_with_params = self.get_by_id(id=data_template_id)
    for i, param in enumerate(dt_with_params.parameter_values):
        if i in initial_enum_values:
            param.validation[0].value = initial_enum_values[i]
            param.validation[0].datatype = DataType.ENUM

    return self.update(data_template=dt_with_params)

create

create(*, data_template: DataTemplate) -> DataTemplate

Creates a new data template.

Parameters:

Name Type Description Default
data_template DataTemplate

The DataTemplate object to create.

required

Returns:

Type Description
DataTemplate

The registered DataTemplate object with an ID.

Source code in src/albert/collections/data_templates.py
def create(self, *, data_template: DataTemplate) -> DataTemplate:
    """Creates a new data template.

    Parameters
    ----------
    data_template : DataTemplate
        The DataTemplate object to create.

    Returns
    -------
    DataTemplate
        The registered DataTemplate object with an ID.
    """
    # Preprocess data_column_values to set validation to None if it is an empty list
    # Handle a bug in the API where validation is an empty list
    # https://support.albertinvent.com/hc/en-us/requests/9177
    if (
        isinstance(data_template.data_column_values, list)
        and len(data_template.data_column_values) == 0
    ):
        data_template.data_column_values = None
    if data_template.data_column_values is not None:
        for column_value in data_template.data_column_values:
            if isinstance(column_value.validation, list) and len(column_value.validation) == 0:
                column_value.validation = None
    # remove them on the initial post
    parameter_values = data_template.parameter_values
    data_template.parameter_values = None
    response = self.session.post(
        self.base_path,
        json=data_template.model_dump(mode="json", by_alias=True, exclude_none=True),
    )
    dt = DataTemplate(**response.json())
    dt.parameter_values = parameter_values
    if data_template.parameter_values is None or len(data_template.parameter_values) == 0:
        return dt
    else:
        return self.add_parameters(
            data_template_id=dt.id, parameters=data_template.parameter_values
        )

delete

delete(*, id: DataTemplateId) -> None

Deletes a data template by its ID.

Parameters:

Name Type Description Default
id str

The ID of the data template to delete.

required
Source code in src/albert/collections/data_templates.py
def delete(self, *, id: DataTemplateId) -> None:
    """Deletes a data template by its ID.

    Parameters
    ----------
    id : str
        The ID of the data template to delete.
    """
    self.session.delete(f"{self.base_path}/{id}")

get_all

get_all(
    *,
    name: str | None = None,
    user_id: str | None = None,
    order_by: OrderBy = DESCENDING,
    limit: int = 100,
    offset: int = 0,
) -> Iterator[DataTemplate]

Retrieve fully hydrated DataTemplate entities with optional filters.

This method returns complete entity data using get_by_ids. Use :meth:search for faster retrieval when you only need lightweight, partial (unhydrated) entities.

Source code in src/albert/collections/data_templates.py
def get_all(
    self,
    *,
    name: str | None = None,
    user_id: str | None = None,
    order_by: OrderBy = OrderBy.DESCENDING,
    limit: int = 100,
    offset: int = 0,
) -> Iterator[DataTemplate]:
    """Retrieve fully hydrated DataTemplate entities with optional filters.

    This method returns complete entity data using `get_by_ids`.
    Use :meth:`search` for faster retrieval when you only need lightweight, partial (unhydrated) entities.
    """

    def batched(iterable, size):
        """Yield lists of up to `size` IDs from an iterable of objects with an `id` attribute."""

        it = (item.id for item in iterable)
        while batch := list(islice(it, size)):
            yield batch

    id_batches = batched(
        self.search(name=name, user_id=user_id, order_by=order_by, limit=limit, offset=offset),
        limit,  # batch size
    )

    for batch in id_batches:
        try:
            hydrated_templates = self.get_by_ids(ids=batch)
            yield from hydrated_templates
        except AlbertHTTPError as e:
            logger.warning(f"Error hydrating batch {batch}: {e}")

get_by_id

get_by_id(*, id: DataTemplateId) -> DataTemplate

Get a data template by its ID.

Parameters:

Name Type Description Default
id DataTemplateId

The ID of the data template to get.

required

Returns:

Type Description
DataTemplate

The data template object on match or None

Source code in src/albert/collections/data_templates.py
def get_by_id(self, *, id: DataTemplateId) -> DataTemplate:
    """Get a data template by its ID.

    Parameters
    ----------
    id : DataTemplateId
        The ID of the data template to get.

    Returns
    -------
    DataTemplate
        The data template object on match or None
    """
    response = self.session.get(f"{self.base_path}/{id}")
    return DataTemplate(**response.json())

get_by_ids

get_by_ids(
    *, ids: list[DataTemplateId]
) -> list[DataTemplate]

Get a list of data templates by their IDs.

Parameters:

Name Type Description Default
ids list[DataTemplateId]

The list of DataTemplate IDs to get.

required

Returns:

Type Description
list[DataTemplate]

A list of DataTemplate objects with the provided IDs.

Source code in src/albert/collections/data_templates.py
def get_by_ids(self, *, ids: list[DataTemplateId]) -> list[DataTemplate]:
    """Get a list of data templates by their IDs.

    Parameters
    ----------
    ids : list[DataTemplateId]
        The list of DataTemplate IDs to get.

    Returns
    -------
    list[DataTemplate]
        A list of DataTemplate objects with the provided IDs.
    """
    url = f"{self.base_path}/ids"
    batches = [ids[i : i + 250] for i in range(0, len(ids), 250)]
    return [
        DataTemplate(**item)
        for batch in batches
        for item in self.session.get(url, params={"id": batch}).json()["Items"]
    ]

get_by_name

get_by_name(*, name: str) -> DataTemplate | None

Get a data template by its name.

Parameters:

Name Type Description Default
name str

The name of the data template to get.

required

Returns:

Type Description
DataTemplate | None

The matching data template object or None if not found.

Source code in src/albert/collections/data_templates.py
def get_by_name(self, *, name: str) -> DataTemplate | None:
    """Get a data template by its name.

    Parameters
    ----------
    name : str
        The name of the data template to get.

    Returns
    -------
    DataTemplate | None
        The matching data template object or None if not found.
    """
    hits = list(self.get_all(name=name))
    for h in hits:
        if h.name.lower() == name.lower():
            return h
    return None

search

search(
    *,
    name: str | None = None,
    user_id: str | None = None,
    order_by: OrderBy = DESCENDING,
    limit: int = 100,
    offset: int = 0,
) -> Iterator[DataTemplateSearchItem]

Search for DataTemplate matching the provided criteria.

⚠️ This method returns partial (unhydrated) entities to optimize performance. To retrieve fully detailed entities, use :meth:get_all instead.

Parameters:

Name Type Description Default
name Union[str, None]

The name of the data template to filter by, by default None.

None
user_id str

user_id to filter by, by default None.

None
order_by OrderBy

The order by which to sort the results, by default OrderBy.DESCENDING.

DESCENDING

Returns:

Type Description
Iterator[DataTemplateSearchItem]

An iterator of DataTemplateSearchItem objects matching the provided criteria.

Source code in src/albert/collections/data_templates.py
def search(
    self,
    *,
    name: str | None = None,
    user_id: str | None = None,
    order_by: OrderBy = OrderBy.DESCENDING,
    limit: int = 100,
    offset: int = 0,
) -> Iterator[DataTemplateSearchItem]:
    """Search for DataTemplate matching the provided criteria.

    ⚠️ This method returns partial (unhydrated) entities to optimize performance.
    To retrieve fully detailed entities, use :meth:`get_all` instead.

    Parameters
    ----------
    name : Union[str, None], optional
        The name of the data template to filter by, by default None.
    user_id : str, optional
        user_id to filter by, by default None.
    order_by : OrderBy, optional
        The order by which to sort the results, by default OrderBy.DESCENDING.

    Returns
    -------
    Iterator[DataTemplateSearchItem]
        An iterator of DataTemplateSearchItem objects matching the provided criteria.
    """

    params = {
        "limit": limit,
        "offset": offset,
        "order": OrderBy(order_by).value if order_by else None,
        "text": name,
        "userId": user_id,
    }

    return AlbertPaginator(
        mode=PaginationMode.OFFSET,
        path=f"{self.base_path}/search",
        session=self.session,
        deserialize=lambda items: [
            DataTemplateSearchItem.model_validate(x)._bind_collection(self) for x in items
        ],
        params=params,
    )

update

update(*, data_template: DataTemplate) -> DataTemplate

Updates a data template.

Parameters:

Name Type Description Default
data_template DataTemplate

The DataTemplate object to update. The ID must be set and matching the ID of the DataTemplate to update.

required

Returns:

Type Description
DataTemplate

The Updated DataTemplate object.

Source code in src/albert/collections/data_templates.py
def update(self, *, data_template: DataTemplate) -> DataTemplate:
    """Updates a data template.

    Parameters
    ----------
    data_template : DataTemplate
        The DataTemplate object to update. The ID must be set and matching the ID of the DataTemplate to update.

    Returns
    -------
    DataTemplate
        The Updated DataTemplate object.
    """

    existing = self.get_by_id(id=data_template.id)

    base_payload = self._generate_patch_payload(existing=existing, updated=data_template)

    path = f"{self.base_path}/{existing.id}"
    (
        general_patches,
        new_data_columns,
        data_column_enum_patches,
        new_parameters,
        parameter_enum_patches,
        parameter_patches,
    ) = generate_data_template_patches(
        initial_patches=base_payload,
        updated_data_template=data_template,
        existing_data_template=existing,
    )

    if len(new_data_columns) > 0:
        self.session.put(
            f"{self.base_path}/{existing.id}/datacolumns",
            json={
                "DataColumns": [
                    x.model_dump(mode="json", by_alias=True, exclude_none=True)
                    for x in new_data_columns
                ],
            },
        )
    if len(data_column_enum_patches) > 0:
        for sequence, enum_patches in data_column_enum_patches.items():
            if len(enum_patches) == 0:
                continue
            self.session.put(
                f"{self.base_path}/{existing.id}/datacolumns/{sequence}/enums",
                json=enum_patches,  # these are simple dicts for now
            )
    if len(new_parameters) > 0:
        self.session.put(
            f"{self.base_path}/{existing.id}/parameters",
            json={
                "Parameters": [
                    x.model_dump(mode="json", by_alias=True, exclude_none=True)
                    for x in new_parameters
                ],
            },
        )
    if len(parameter_enum_patches) > 0:
        for sequence, enum_patches in parameter_enum_patches.items():
            if len(enum_patches) == 0:
                continue
            self.session.put(
                f"{self.base_path}/{existing.id}/parameters/{sequence}/enums",
                json=enum_patches,  # these are simple dicts for now
            )
    if len(parameter_patches) > 0:
        payload = PGPatchPayload(data=parameter_patches)
        self.session.patch(
            path + "/parameters",
            json=payload.model_dump(mode="json", by_alias=True, exclude_none=True),
        )
    if len(general_patches.data) > 0:
        payload = GeneralPatchPayload(data=general_patches.data)
        self.session.patch(
            path,
            json=payload.model_dump(mode="json", by_alias=True, exclude_none=True),
        )
    return self.get_by_id(id=data_template.id)

DataTemplateSearchItem pydantic-model

Bases: BaseAlbertModel, HydrationMixin[DataTemplate]

Show JSON schema:
{
  "$defs": {
    "DataTemplateSearchItemDataColumn": {
      "properties": {
        "id": {
          "title": "Id",
          "type": "string"
        },
        "name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Name"
        },
        "localizedNames": {
          "$ref": "#/$defs/LocalizedNames"
        }
      },
      "required": [
        "id",
        "localizedNames"
      ],
      "title": "DataTemplateSearchItemDataColumn",
      "type": "object"
    },
    "LocalizedNames": {
      "properties": {
        "de": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "De"
        },
        "ja": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Ja"
        },
        "zh": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Zh"
        },
        "es": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Es"
        }
      },
      "title": "LocalizedNames",
      "type": "object"
    }
  },
  "properties": {
    "albertId": {
      "title": "Albertid",
      "type": "string"
    },
    "name": {
      "title": "Name",
      "type": "string"
    },
    "dataColumns": {
      "anyOf": [
        {
          "items": {
            "$ref": "#/$defs/DataTemplateSearchItemDataColumn"
          },
          "type": "array"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Datacolumns"
    }
  },
  "required": [
    "albertId",
    "name"
  ],
  "title": "DataTemplateSearchItem",
  "type": "object"
}

Fields:

data_columns pydantic-field

data_columns: (
    list[DataTemplateSearchItemDataColumn] | None
) = None

id pydantic-field

id: str

name pydantic-field

name: str

DataType

Bases: str, Enum

ENUM class-attribute instance-attribute

ENUM = 'enum'

NUMBER class-attribute instance-attribute

NUMBER = 'number'

STRING class-attribute instance-attribute

STRING = 'string'

EnumValidationValue pydantic-model

Bases: BaseAlbertModel

Represents a value for an enum type validation.

Attributes:

Name Type Description
text str

The text of the enum value.

id str | None

The ID of the enum value. If not provided, the ID will be generated upon creation.

Show JSON schema:
{
  "description": "Represents a value for an enum type validation.\n\nAttributes\n----------\ntext : str\n    The text of the enum value.\nid : str | None\n    The ID of the enum value. If not provided, the ID will be generated upon creation.",
  "properties": {
    "text": {
      "title": "Text",
      "type": "string"
    },
    "id": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Id"
    },
    "originalText": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Originaltext"
    }
  },
  "required": [
    "text"
  ],
  "title": "EnumValidationValue",
  "type": "object"
}

Fields:

id pydantic-field

id: str | None = None

original_text pydantic-field

original_text: str | None = None

text pydantic-field

text: str

OrderBy

Bases: str, Enum

ASCENDING class-attribute instance-attribute

ASCENDING = 'asc'

DESCENDING class-attribute instance-attribute

DESCENDING = 'desc'

PaginationMode

Bases: str, Enum

KEY class-attribute instance-attribute

KEY = 'key'

OFFSET class-attribute instance-attribute

OFFSET = 'offset'

ParameterValue pydantic-model

Bases: BaseAlbertModel

The value of a parameter in a parameter group.

Attributes:

Name Type Description
parameter Parameter

The Parameter resource this value is associated with. Provide either an id or a parameter keyword argument.

id str | None

The Albert ID of the Parameter resource this value is associated with. Provide either an id or a parameter keyword argument.

category ParameterCategory

The category of the parameter.

short_name str | None

The short name of the parameter value.

value str | None

The default value of the parameter. Can be a string or an InventoryItem (if, for example, the parameter is an instrumnt choice).

unit Unit | None

The unit of measure for the provided parameter value.

name str

The name of the parameter. Read-only.

sequence int

The sequence of the parameter. Read-only.

Show JSON schema:
{
  "$defs": {
    "ACL": {
      "description": "The Access Control List (ACL) for a user",
      "properties": {
        "id": {
          "description": "The id of the user for which this ACL applies",
          "title": "Id",
          "type": "string"
        },
        "fgc": {
          "anyOf": [
            {
              "$ref": "#/$defs/AccessControlLevel"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "The Fine-Grain Control Level"
        }
      },
      "required": [
        "id"
      ],
      "title": "ACL",
      "type": "object"
    },
    "AccessControlLevel": {
      "description": "The fine grain control",
      "enum": [
        "ProjectOwner",
        "ProjectEditor",
        "ProjectViewer",
        "ProjectAllTask",
        "ProjectPropertyTask",
        "InventoryOwner",
        "InventoryViewer",
        "CustomTemplateOwner",
        "CustomTemplateViewer"
      ],
      "title": "AccessControlLevel",
      "type": "string"
    },
    "AuditFields": {
      "description": "The audit fields for a resource",
      "properties": {
        "by": {
          "default": null,
          "title": "By",
          "type": "string"
        },
        "byName": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Byname"
        },
        "at": {
          "anyOf": [
            {
              "format": "date-time",
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "At"
        }
      },
      "title": "AuditFields",
      "type": "object"
    },
    "Cas": {
      "description": "Represents a CAS entity.",
      "properties": {
        "number": {
          "description": "The CAS number.",
          "title": "Number",
          "type": "string"
        },
        "name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Name of the CAS.",
          "title": "Name"
        },
        "description": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "The description or name of the CAS.",
          "title": "Description"
        },
        "notes": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Notes related to the CAS.",
          "title": "Notes"
        },
        "category": {
          "anyOf": [
            {
              "$ref": "#/$defs/CasCategory"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "The category of the CAS."
        },
        "casSmiles": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "CAS SMILES notation.",
          "title": "Cassmiles"
        },
        "inchiKey": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "InChIKey of the CAS.",
          "title": "Inchikey"
        },
        "iUpacName": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "IUPAC name of the CAS.",
          "title": "Iupacname"
        },
        "albertId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "The AlbertID of the CAS.",
          "title": "Albertid"
        },
        "hazards": {
          "anyOf": [
            {
              "items": {
                "$ref": "#/$defs/Hazard"
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Hazards associated with the CAS.",
          "title": "Hazards"
        },
        "wgk": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "German Water Hazard Class (WGK) number.",
          "title": "Wgk"
        },
        "ecListNo": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "European Community (EC) number.",
          "title": "Eclistno"
        },
        "type": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Type of the CAS.",
          "title": "Type"
        },
        "classificationType": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Classification type of the CAS.",
          "title": "Classificationtype"
        },
        "order": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "CAS order.",
          "title": "Order"
        }
      },
      "required": [
        "number"
      ],
      "title": "Cas",
      "type": "object"
    },
    "CasAmount": {
      "description": "CasAmount is a Pydantic model representing an amount of a given CAS.\n\nAttributes\n----------\nmin : float\n    The minimum amount of the CAS in the formulation.\nmax : float\n    The maximum amount of the CAS in the formulation.\nid : str | None\n    The Albert ID of the CAS Number Resource this amount represents. Provide either a Cas or an ID.\ncas : Cas | None\n    The CAS object associated with this amount. Provide either a Cas or an id.\ncas_smiles: str | None\n    The SMILES string of the CAS Number resource. Obtained from the Cas object when provided.\nnumber: str | None\n    The CAS number. Obtained from the Cas object when provided.",
      "properties": {
        "min": {
          "title": "Min",
          "type": "number"
        },
        "max": {
          "title": "Max",
          "type": "number"
        },
        "inventoryValue": {
          "anyOf": [
            {
              "type": "number"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Inventoryvalue"
        },
        "id": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Id"
        },
        "casCategory": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Cascategory"
        },
        "cas": {
          "anyOf": [
            {
              "$ref": "#/$defs/Cas"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "casSmiles": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Cassmiles"
        },
        "number": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Number"
        }
      },
      "required": [
        "min",
        "max"
      ],
      "title": "CasAmount",
      "type": "object"
    },
    "CasCategory": {
      "enum": [
        "User",
        "Verisk",
        "TSCA - Public",
        "TSCA - Private",
        "not TSCA",
        "CAS linked to External Database",
        "Unknown (Trade Secret)",
        "CL_Inventory Upload"
      ],
      "title": "CasCategory",
      "type": "string"
    },
    "Company": {
      "description": "Company is a Pydantic model representing a company entity.\n\nAttributes\n----------\nname : str\n    The name of the company.\nid : str | None\n    The Albert ID of the company. Set when the company is retrieved from Albert.\ndistance : float | None\n    The scores of a company in a search result, optional. Read-only.",
      "properties": {
        "status": {
          "anyOf": [
            {
              "$ref": "#/$defs/Status"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Created": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Updated": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "name": {
          "title": "Name",
          "type": "string"
        },
        "albertId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Albertid"
        },
        "distance": {
          "anyOf": [
            {
              "type": "number"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Distance"
        }
      },
      "required": [
        "name"
      ],
      "title": "Company",
      "type": "object"
    },
    "DataType": {
      "enum": [
        "number",
        "string",
        "enum"
      ],
      "title": "DataType",
      "type": "string"
    },
    "EntityLink": {
      "properties": {
        "id": {
          "title": "Id",
          "type": "string"
        },
        "name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Name"
        }
      },
      "required": [
        "id"
      ],
      "title": "EntityLink",
      "type": "object"
    },
    "EnumValidationValue": {
      "description": "Represents a value for an enum type validation.\n\nAttributes\n----------\ntext : str\n    The text of the enum value.\nid : str | None\n    The ID of the enum value. If not provided, the ID will be generated upon creation.",
      "properties": {
        "text": {
          "title": "Text",
          "type": "string"
        },
        "id": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Id"
        },
        "originalText": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Originaltext"
        }
      },
      "required": [
        "text"
      ],
      "title": "EnumValidationValue",
      "type": "object"
    },
    "Hazard": {
      "description": "Represents a chemical hazard.",
      "properties": {
        "subCategory": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Hazard subcategory",
          "title": "Subcategory"
        },
        "hCode": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Hazard code",
          "title": "Hcode"
        },
        "category": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "number"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Hazard category",
          "title": "Category"
        },
        "class": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Hazard classification",
          "title": "Class"
        },
        "hCodeText": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Hazard code text",
          "title": "Hcodetext"
        }
      },
      "title": "Hazard",
      "type": "object"
    },
    "InventoryCategory": {
      "enum": [
        "RawMaterials",
        "Consumables",
        "Equipment",
        "Formulas"
      ],
      "title": "InventoryCategory",
      "type": "string"
    },
    "InventoryItem": {
      "description": "An InventoryItem is a Pydantic model representing an item in the inventory. Can be a raw material, consumable, equipment, or formula.\nNote: Formulas should be registered via the Worksheet collection / Sheet resource.\n\nReturns\n-------\nInventoryItem\n    An InventoryItem that can be used to represent an item in the inventory. Can be a raw material, consumable, equipment, or formula.\n\nAttributes\n------\n\nname : str\n    The name of the InventoryItem.\nid : str | None\n    The Albert ID of the InventoryItem. Set when the InventoryItem is retrieved from Albert.\ndescription : str | None\n    The description of the InventoryItem.\ncategory : InventoryCategory\n    The category of the InventoryItem. Allowed values are `RawMaterials`, `Consumables`, `Equipment`, and `Formulas`.\nunit_category : InventoryUnitCategory\n    The unit category of the InventoryItem. Can be mass, volume, length, pressure, or units. By default, mass is used for RawMaterials and Formulas, and units is used for Equipment and Consumables.\nsecurity_class : SecurityClass | None\n    The security class of the InventoryItem. Optional. Can be confidential, shared, or restricted.\ncompany : Company | str | None\n    The company associated with the InventoryItem. Can be a Company object or a string. If a String is provided, a Company object with the name of the provided string will be first-or-created.\nminimum : list[InventoryMinimum] | None\n    The minimum amount of the InventoryItem that must be kept in stock at a given Location. Optional.\nalias : str | None\n    An alias for the InventoryItem. Optional.\ncas : list[CasAmount] | None\n    The CAS numbers associated with the InventoryItem. This is how a compositional breakdown can be provided. Optional.\nmetadata : dict[str, str | list[EntityLink] | EntityLink] | None\n    Metadata associated with the InventoryItem. Optional. Allowed metadata fields can be found in the CustomFields documentation.\nproject_id : str | None\n    The project ID associated with the InventoryItem. Read Only. Required for Formulas.\nformula_id : str | None\n    The formula ID associated with the InventoryItem. Read Only.\ntags : list[str|Tag] | None\n    The tags associated with the InventoryItem. Optional. If a string is provided, a Tag object with the name of the provided string will be first-or-created.",
      "properties": {
        "status": {
          "anyOf": [
            {
              "$ref": "#/$defs/Status"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Created": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Updated": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Tags": {
          "anyOf": [
            {
              "items": {
                "anyOf": [
                  {
                    "$ref": "#/$defs/Tag"
                  },
                  {
                    "$ref": "#/$defs/EntityLink"
                  }
                ]
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Tags"
        },
        "name": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Name"
        },
        "albertId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Albertid"
        },
        "description": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Description"
        },
        "category": {
          "$ref": "#/$defs/InventoryCategory"
        },
        "unitCategory": {
          "anyOf": [
            {
              "$ref": "#/$defs/InventoryUnitCategory"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "class": {
          "anyOf": [
            {
              "$ref": "#/$defs/SecurityClass"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Company": {
          "anyOf": [
            {
              "$ref": "#/$defs/Company"
            },
            {
              "$ref": "#/$defs/EntityLink"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Company"
        },
        "minimum": {
          "anyOf": [
            {
              "items": {
                "$ref": "#/$defs/InventoryMinimum"
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Minimum"
        },
        "alias": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Alias"
        },
        "Cas": {
          "anyOf": [
            {
              "items": {
                "$ref": "#/$defs/CasAmount"
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Cas"
        },
        "Metadata": {
          "anyOf": [
            {
              "additionalProperties": {
                "anyOf": [
                  {
                    "type": "number"
                  },
                  {
                    "type": "integer"
                  },
                  {
                    "type": "string"
                  },
                  {
                    "$ref": "#/$defs/EntityLink"
                  },
                  {
                    "items": {
                      "$ref": "#/$defs/EntityLink"
                    },
                    "type": "array"
                  }
                ]
              },
              "type": "object"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Metadata"
        },
        "parentId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Parentid"
        },
        "ACL": {
          "items": {
            "$ref": "#/$defs/ACL"
          },
          "title": "Acl",
          "type": "array"
        },
        "TaskConfig": {
          "anyOf": [
            {
              "items": {
                "additionalProperties": true,
                "type": "object"
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Taskconfig"
        },
        "formulaId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Formulaid"
        },
        "Symbols": {
          "anyOf": [
            {
              "items": {
                "additionalProperties": true,
                "type": "object"
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Symbols"
        },
        "unNumber": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Unnumber"
        },
        "recentAttachmentId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Recentattachmentid"
        }
      },
      "required": [
        "category"
      ],
      "title": "InventoryItem",
      "type": "object"
    },
    "InventoryMinimum": {
      "description": "Defined the minimum amount of an InventoryItem that must be kept in stock at a given Location.\n\nAttributes\n----------\nid : str\n    The unique identifier of the Location object associated with this InventoryMinimum.\n    Provide either a Location or a location id.\nlocation : Location\n    The Location object associated with this InventoryMinimum. Provide either a Location or a location id.\nminimum : float\n    The minimum amount of the InventoryItem that must be kept in stock at the given Location.",
      "properties": {
        "id": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Id"
        },
        "location": {
          "anyOf": [
            {
              "$ref": "#/$defs/Location"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "minimum": {
          "maximum": 1000000000000000,
          "minimum": 0,
          "title": "Minimum",
          "type": "number"
        }
      },
      "required": [
        "minimum"
      ],
      "title": "InventoryMinimum",
      "type": "object"
    },
    "InventoryUnitCategory": {
      "enum": [
        "mass",
        "volume",
        "length",
        "pressure",
        "units"
      ],
      "title": "InventoryUnitCategory",
      "type": "string"
    },
    "Location": {
      "description": "A location in Albert.\n\nAttributes\n----------\nname : str\n    The name of the location.\nid : str | None\n    The Albert ID of the location. Set when the location is retrieved from Albert.\nlatitude : float\n    The latitude of the location.\nlongitude : float\n    The longitude of the location.\naddress : str\n    The address of the location.\ncountry : str | None\n    The country code of the location. Must be two characters long.",
      "properties": {
        "status": {
          "anyOf": [
            {
              "$ref": "#/$defs/Status"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Created": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Updated": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "name": {
          "title": "Name",
          "type": "string"
        },
        "albertId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Albertid"
        },
        "latitude": {
          "title": "Latitude",
          "type": "number"
        },
        "longitude": {
          "title": "Longitude",
          "type": "number"
        },
        "address": {
          "title": "Address",
          "type": "string"
        },
        "country": {
          "anyOf": [
            {
              "maxLength": 2,
              "minLength": 2,
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Country"
        }
      },
      "required": [
        "name",
        "latitude",
        "longitude",
        "address"
      ],
      "title": "Location",
      "type": "object"
    },
    "Operator": {
      "enum": [
        "between",
        "lt",
        "lte",
        "gte",
        "gt",
        "eq"
      ],
      "title": "Operator",
      "type": "string"
    },
    "Parameter": {
      "description": "A parameter in Albert.\n\nAttributes\n----------\nname : str\n    The name of the parameter. Names must be unique.\nid : str | None\n    The Albert ID of the parameter. Set when the parameter is retrieved from Albert.\ncategory : ParameterCategory\n    The category of the parameter. Allowed values are `Normal` and `Special`. Read-only.\nrank : int\n    The rank of the returned parameter. Read-only.",
      "properties": {
        "status": {
          "anyOf": [
            {
              "$ref": "#/$defs/Status"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Created": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Updated": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "name": {
          "title": "Name",
          "type": "string"
        },
        "albertId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Albertid"
        },
        "Metadata": {
          "anyOf": [
            {
              "additionalProperties": {
                "anyOf": [
                  {
                    "type": "number"
                  },
                  {
                    "type": "integer"
                  },
                  {
                    "type": "string"
                  },
                  {
                    "$ref": "#/$defs/EntityLink"
                  },
                  {
                    "items": {
                      "$ref": "#/$defs/EntityLink"
                    },
                    "type": "array"
                  }
                ]
              },
              "type": "object"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Metadata"
        },
        "category": {
          "anyOf": [
            {
              "$ref": "#/$defs/ParameterCategory"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "rank": {
          "anyOf": [
            {
              "type": "integer"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Rank"
        }
      },
      "required": [
        "name"
      ],
      "title": "Parameter",
      "type": "object"
    },
    "ParameterCategory": {
      "description": "The category of a parameter",
      "enum": [
        "Normal",
        "Special"
      ],
      "title": "ParameterCategory",
      "type": "string"
    },
    "SecurityClass": {
      "description": "The security class of a resource",
      "enum": [
        "shared",
        "restricted",
        "confidential",
        "private",
        "public"
      ],
      "title": "SecurityClass",
      "type": "string"
    },
    "Status": {
      "description": "The status of a resource",
      "enum": [
        "active",
        "inactive"
      ],
      "title": "Status",
      "type": "string"
    },
    "Tag": {
      "description": "Tag is a Pydantic model representing a tag entity.\n\nAttributes\n----------\ntag : str\n    The name of the tag.\nid : str | None\n    The Albert ID of the tag. Set when the tag is retrieved from Albert.\n\nMethods\n-------\nfrom_string(tag: str) -> \"Tag\"\n    Creates a Tag object from a string.",
      "properties": {
        "status": {
          "anyOf": [
            {
              "$ref": "#/$defs/Status"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Created": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Updated": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "name": {
          "title": "Name",
          "type": "string"
        },
        "albertId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Albertid"
        }
      },
      "required": [
        "name"
      ],
      "title": "Tag",
      "type": "object"
    },
    "Unit": {
      "description": "Unit is a Pydantic model representing a unit entity.\n\nAttributes\n----------\nid : str | None\n    The Albert ID of the unit. Set when the unit is retrieved from Albert.\nname : str\n    The name of the unit.\nsymbol : str | None\n    The symbol of the unit.\nsynonyms : List[str] | None\n    The list of synonyms for the unit.\ncategory : UnitCategory\n    The category of the unit.\nverified : bool | None\n    Whether the unit is verified.\nstatus : Status | None\n    The status of the unit. Allowed values are `active`, and `inactive`",
      "properties": {
        "status": {
          "anyOf": [
            {
              "$ref": "#/$defs/Status"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Created": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "Updated": {
          "anyOf": [
            {
              "$ref": "#/$defs/AuditFields"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "albertId": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Albertid"
        },
        "name": {
          "title": "Name",
          "type": "string"
        },
        "symbol": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Symbol"
        },
        "Synonyms": {
          "anyOf": [
            {
              "items": {
                "type": "string"
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "title": "Synonyms"
        },
        "category": {
          "anyOf": [
            {
              "$ref": "#/$defs/UnitCategory"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        },
        "verified": {
          "anyOf": [
            {
              "type": "boolean"
            },
            {
              "type": "null"
            }
          ],
          "default": false,
          "title": "Verified"
        }
      },
      "required": [
        "name"
      ],
      "title": "Unit",
      "type": "object"
    },
    "UnitCategory": {
      "description": "UnitCategory is an enumeration of possible unit categories.\n\nAttributes\n----------\nLENGTH : str\n    Represents length units.\nVOLUME : str\n    Represents volume units.\nLIQUID_VOLUME : str\n    Represents liquid volume units.\nANGLES : str\n    Represents angle units.\nTIME : str\n    Represents time units.\nFREQUENCY : str\n    Represents frequency units.\nMASS : str\n    Represents mass units.\nCURRENT : str\n    Represents electric current units.\nTEMPERATURE : str\n    Represents temperature units.\nAMOUNT : str\n    Represents amount of substance units.\nLUMINOSITY : str\n    Represents luminous intensity units.\nFORCE : str\n    Represents force units.\nENERGY : str\n    Represents energy units.\nPOWER : str\n    Represents power units.\nPRESSURE : str\n    Represents pressure units.\nELECTRICITY_AND_MAGNETISM : str\n    Represents electricity and magnetism units.\nOTHER : str\n    Represents other units.\nWEIGHT : str\n    Represents weight units.",
      "enum": [
        "Length",
        "Volume",
        "Liquid volume",
        "Angles",
        "Time",
        "Frequency",
        "Mass",
        "Electric current",
        "Temperature",
        "Amount of substance",
        "Luminous intensity",
        "Force",
        "Energy",
        "Power",
        "Pressure",
        "Electricity and magnetism",
        "Other",
        "Weight",
        "Area",
        "Surface Area",
        "Binary",
        "Capacitance",
        "Speed",
        "Electrical conductivity",
        "Electrical permitivitty",
        "Density",
        "Resistance"
      ],
      "title": "UnitCategory",
      "type": "string"
    },
    "ValueValidation": {
      "properties": {
        "datatype": {
          "$ref": "#/$defs/DataType"
        },
        "value": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "items": {
                "$ref": "#/$defs/EnumValidationValue"
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Value"
        },
        "min": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Min"
        },
        "max": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "title": "Max"
        },
        "operator": {
          "anyOf": [
            {
              "$ref": "#/$defs/Operator"
            },
            {
              "type": "null"
            }
          ],
          "default": null
        }
      },
      "required": [
        "datatype"
      ],
      "title": "ValueValidation",
      "type": "object"
    }
  },
  "description": "The value of a parameter in a parameter group.\n\nAttributes\n----------\nparameter : Parameter\n    The Parameter resource this value is associated with. Provide either an id or a parameter keyword argument.\nid : str | None\n    The Albert ID of the Parameter resource this value is associated with. Provide either an id or a parameter keyword argument.\ncategory: ParameterCategory\n    The category of the parameter.\nshort_name : str | None\n    The short name of the parameter value.\nvalue : str | None\n    The default value of the parameter. Can be a string or an InventoryItem (if, for example, the parameter is an instrumnt choice).\nunit : Unit | None\n    The unit of measure for the provided parameter value.\nname : str\n    The name of the parameter. Read-only.\nsequence : int\n    The sequence of the parameter. Read-only.",
  "properties": {
    "parameter": {
      "$ref": "#/$defs/Parameter",
      "default": null
    },
    "id": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Id"
    },
    "category": {
      "anyOf": [
        {
          "$ref": "#/$defs/ParameterCategory"
        },
        {
          "type": "null"
        }
      ],
      "default": null
    },
    "shortName": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Shortname"
    },
    "value": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "$ref": "#/$defs/InventoryItem"
        },
        {
          "$ref": "#/$defs/EntityLink"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Value"
    },
    "Unit": {
      "anyOf": [
        {
          "$ref": "#/$defs/Unit"
        },
        {
          "$ref": "#/$defs/EntityLink"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Unit"
    },
    "Added": {
      "anyOf": [
        {
          "$ref": "#/$defs/AuditFields"
        },
        {
          "type": "null"
        }
      ],
      "default": null
    },
    "validation": {
      "anyOf": [
        {
          "items": {
            "$ref": "#/$defs/ValueValidation"
          },
          "type": "array"
        },
        {
          "type": "null"
        }
      ],
      "title": "Validation"
    },
    "name": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Name"
    },
    "sequence": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Sequence"
    },
    "originalShortName": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Originalshortname"
    },
    "originalName": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "title": "Originalname"
    }
  },
  "title": "ParameterValue",
  "type": "object"
}

Fields:

Validators:

added pydantic-field

added: AuditFields | None = None

category pydantic-field

category: ParameterCategory | None = None

id pydantic-field

id: str | None = None

name pydantic-field

name: str | None = None

original_name pydantic-field

original_name: str | None = None

original_short_name pydantic-field

original_short_name: str | None = None

parameter pydantic-field

parameter: Parameter = None

sequence pydantic-field

sequence: str | None = None

short_name pydantic-field

short_name: str | None = None

unit pydantic-field

unit: SerializeAsEntityLink[Unit] | None = None

validation pydantic-field

validation: list[ValueValidation] | None

value pydantic-field

value: str | SerializeAsEntityLink[InventoryItem] | None = (
    None
)

set_parameter_fields pydantic-validator

set_parameter_fields() -> ParameterValue
Source code in src/albert/resources/parameter_groups.py
@model_validator(mode="after")
def set_parameter_fields(self) -> "ParameterValue":
    if self.parameter is None and self.id is None:
        raise ValueError("Please provide either an id or an parameter object.")

    if self.parameter is not None:
        object.__setattr__(self, "id", self.parameter.id)
        object.__setattr__(self, "category", self.parameter.category)
        object.__setattr__(self, "name", self.parameter.name)

    return self

validate_parameter_value pydantic-validator

validate_parameter_value(value: Any) -> Any
Source code in src/albert/resources/parameter_groups.py
@field_validator("value", mode="before")
@classmethod
def validate_parameter_value(cls, value: Any) -> Any:
    # Bug in ParameterGroups sometimes returns incorrect JSON from batch endpoint
    # Set to None if value is a dict but no ID field
    # Reference: https://linear.app/albert-invent/issue/IN-10
    if isinstance(value, dict) and "id" not in value:
        return None
    return value

generate_data_template_patches

generate_data_template_patches(
    initial_patches: PatchPayload,
    updated_data_template: DataTemplate,
    existing_data_template: DataTemplate,
)
Source code in src/albert/utils/_patch.py
def generate_data_template_patches(
    initial_patches: PatchPayload,
    updated_data_template: DataTemplate,
    existing_data_template: DataTemplate,
):
    # First handle the data columns
    general_patches = initial_patches
    patches, new_data_columns, data_column_enum_patches = generate_data_column_patches(
        initial_data_column=existing_data_template.data_column_values,
        updated_data_column=updated_data_template.data_column_values,
    )

    tag_patches = handle_tags(
        existing_tags=existing_data_template.tags,
        updated_tags=updated_data_template.tags,
        attribute_name="tag",
    )
    # add the general patches
    general_patches.data.extend(patches)
    general_patches.data.extend(tag_patches)

    parameter_patches, new_parameters, parameter_enum_patches = generate_parameter_patches(
        initial_parameters=existing_data_template.parameter_values,
        updated_parameters=updated_data_template.parameter_values,
        parameter_attribute_name="parameters",
    )

    return (
        general_patches,
        new_data_columns,
        data_column_enum_patches,
        new_parameters,
        parameter_enum_patches,
        parameter_patches,
    )