Skip to content

Lists

albert.collections.lists

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: _Lfor (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

ListItem

Bases: BaseResource

An item in a list.

Attributes:

Name Type Description
name str

The name of the list item.

id str | None

The Albert ID of the list item. Set when the list item is retrieved from Albert.

category ListItemCategory | None

The category of the list item. Allowed values are businessDefined, userDefined, projects, and extensions.

list_type str | None

The type of the list item. Allowed values are projectState for projects and extensions for extensions.

Methods:

Name Description
validate_list_type

category class-attribute instance-attribute

category: ListItemCategory | None = Field(default=None)

id class-attribute instance-attribute

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

list_type class-attribute instance-attribute

list_type: str | None = Field(
    default=None, alias="listType"
)

name instance-attribute

name: str

validate_list_type

validate_list_type() -> ListItem
Source code in src/albert/resources/lists.py
@model_validator(mode="after")
def validate_list_type(self) -> "ListItem":
    if (
        self.category == ListItemCategory.PROJECTS
        and self.list_type is not None
        and self.list_type != "projectState"
    ) or (
        self.category == ListItemCategory.EXTENSIONS
        and self.list_type is not None
        and self.list_type != "extensions"
    ):
        raise ValueError(
            f"List type {self.list_type} is not allowed for category {self.category}"
        )
    return self

ListItemCategory

Bases: str, Enum

BUSINESS_DEFINED class-attribute instance-attribute

BUSINESS_DEFINED = 'businessDefined'

EXTENSIONS class-attribute instance-attribute

EXTENSIONS = 'extensions'

INVENTORY class-attribute instance-attribute

INVENTORY = 'inventory'

PROJECTS class-attribute instance-attribute

PROJECTS = 'projects'

USER_DEFINED class-attribute instance-attribute

USER_DEFINED = 'userDefined'

ListsCollection

ListsCollection(*, session: AlbertSession)

Bases: BaseCollection

ListsCollection is a collection class for managing ListItem entities in the Albert platform.

Example
stages = [
    "1. Discovery",
    "2. Concept Validation",
    "3. Proof of Concept",
    "4. Prototype Development",
    "5. Preliminary Evaluation",
    "6. Feasibility Study",
    "7. Optimization",
    "8. Scale-Up",
    "9. Regulatory Assessment",
]
# Initialize the Albert client
client = Albert()

# Get the custom field this list is associated with
stage_gate_field = client.custom_fields.get_by_id(id="CF123")

# Create the list items
for s in stages:
    item = ListItem(
        name=s,
        category=stage_gate_field.category,
        list_type=stage_gate_field.name,
    )

    client.lists.create(list_item=item)

Parameters:

Name Type Description Default
session AlbertSession

The Albert session instance.

required

Methods:

Name Description
create

Creates a list entity.

delete

Delete a lists entry item by its ID.

get_all

Get all list entities with optional filters.

get_by_id

Retrieves a list entity by its ID.

get_matching_item

Get a list item by name and list type.

update

Update a list item.

Source code in src/albert/collections/lists.py
def __init__(self, *, session: AlbertSession):
    """
    Initializes the ListsCollection with the provided session.

    Parameters
    ----------
    session : AlbertSession
        The Albert session instance.
    """
    super().__init__(session=session)
    self.base_path = f"/api/{ListsCollection._api_version}/lists"

base_path instance-attribute

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

create

create(*, list_item: ListItem) -> ListItem

Creates a list entity.

Parameters:

Name Type Description Default
list_item ListItem

The list entity to create.

required

Returns:

Type Description
List

The created list entity.

Source code in src/albert/collections/lists.py
def create(self, *, list_item: ListItem) -> ListItem:
    """
    Creates a list entity.

    Parameters
    ----------
    list_item : ListItem
        The list entity to create.

    Returns
    -------
    List
        The created list entity.
    """
    response = self.session.post(
        self.base_path,
        json=list_item.model_dump(by_alias=True, exclude_none=True, mode="json"),
    )
    return ListItem(**response.json())

delete

delete(*, id: str) -> None

Delete a lists entry item by its ID.

Parameters:

Name Type Description Default
id str

The ID of the lists item.

required

Returns:

Type Description
None
Source code in src/albert/collections/lists.py
def delete(self, *, id: str) -> None:
    """
    Delete a lists entry item by its ID.

    Parameters
    ----------
    id : str
        The ID of the lists item.

    Returns
    -------
    None
    """
    url = f"{self.base_path}/{id}"
    self.session.delete(url)

get_all

get_all(
    *,
    limit: int = 100,
    names: list[str] | None = None,
    category: ListItemCategory | None = None,
    list_type: str | None = None,
    start_key: str | None = None,
) -> Iterator[ListItem]

Get all list entities with optional filters.

Parameters:

Name Type Description Default
limit int

The maximum number of list entities to return.

100
names list[str]

A list of names of the list entity to retrieve.

None
category ListItemCategory

The category of the list entity to retrieve.

None
list_type str

The type of list entity to retrieve.

None

Returns:

Type Description
Iterator[ListItem]

An iterator of ListItems.

Source code in src/albert/collections/lists.py
def get_all(
    self,
    *,
    limit: int = 100,
    names: list[str] | None = None,
    category: ListItemCategory | None = None,
    list_type: str | None = None,
    start_key: str | None = None,
) -> Iterator[ListItem]:
    """
    Get all list entities with optional filters.

    Parameters
    ----------
    limit : int, optional
        The maximum number of list entities to return.
    names : list[str], optional
        A list of names of the list entity to retrieve.
    category : ListItemCategory, optional
        The category of the list entity to retrieve.
    list_type : str, optional
        The type of list entity to retrieve.
    Returns
    ------
    Iterator[ListItem]
        An iterator of ListItems.
    """
    params = {
        "limit": limit,
        "startKey": start_key,
        "name": [names] if isinstance(names, str) else names,
        "category": category.value if isinstance(category, ListItemCategory) else category,
        "listType": list_type,
    }
    return AlbertPaginator(
        mode=PaginationMode.OFFSET,
        path=self.base_path,
        session=self.session,
        params=params,
        deserialize=lambda items: [ListItem(**item) for item in items],
    )

get_by_id

get_by_id(*, id: str) -> ListItem

Retrieves a list entity by its ID.

Parameters:

Name Type Description Default
id str

The ID of the list entity to retrieve.

required

Returns:

Type Description
List

A list entity.

Source code in src/albert/collections/lists.py
def get_by_id(self, *, id: str) -> ListItem:
    """
    Retrieves a list entity by its ID.

    Parameters
    ----------
    id : str
        The ID of the list entity to retrieve.

    Returns
    -------
    List
        A list entity.
    """
    response = self.session.get(f"{self.base_path}/{id}")
    return ListItem(**response.json())

get_matching_item

get_matching_item(
    *, name: str, list_type: str
) -> ListItem | None

Get a list item by name and list type.

Parameters:

Name Type Description Default
name str

The name of it item to retrieve.

required
list_type str

The type of list (can be the name of the custom field)

required

Returns:

Type Description
ListItem | None

A list item with the provided name and list type, or None if not found.

Source code in src/albert/collections/lists.py
def get_matching_item(self, *, name: str, list_type: str) -> ListItem | None:
    """Get a list item by name and list type.

    Parameters
    ----------
    name : str
        The name of it item to retrieve.
    list_type : str
        The type of list (can be the name of the custom field)

    Returns
    -------
    ListItem | None
        A list item with the provided name and list type, or None if not found.
    """
    for list_item in self.get_all(names=[name], list_type=list_type):
        if list_item.name.lower() == name.lower():
            return list_item
    return None

update

update(*, list_item=ListItem) -> ListItem

Update a list item.

Parameters:

Name Type Description Default
list_item ListItem

The list item to update.

ListItem

Returns:

Type Description
ListItem

The updated list item.

Source code in src/albert/collections/lists.py
def update(self, *, list_item=ListItem) -> ListItem:
    """Update a list item.

    Parameters
    ----------
    list_item : ListItem
        The list item to update.

    Returns
    -------
    ListItem
        The updated list item.
    """
    existing = self.get_by_id(id=list_item.id)
    patches = self._generate_patch_payload(
        existing=existing, updated=list_item, generate_metadata_diff=False
    )
    if len(patches.data) == 0:
        return existing
    self.session.patch(
        url=f"{self.base_path}/{list_item.id}",
        json=patches.model_dump(mode="json", by_alias=True, exclude_none=True),
    )
    return self.get_by_id(id=list_item.id)

PaginationMode

Bases: str, Enum

KEY class-attribute instance-attribute

KEY = 'key'

OFFSET class-attribute instance-attribute

OFFSET = 'offset'