Skip to content

UN Numbers

albert.collections.un_numbers

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

PaginationMode

Bases: str, Enum

KEY class-attribute instance-attribute

KEY = 'key'

OFFSET class-attribute instance-attribute

OFFSET = 'offset'

UnNumber

Bases: BaseResource

A UN number entity. UN Numbers are highly controlled within Albert.

Attributes:

Name Type Description
un_number str

The UN number.

id str

The Albert ID of the UN number. Set when the UN number is retrieved from Albert.

storage_class_name str

The name of the storage class.

shipping_description str

The shipping description.

storage_class_number str

The storage class number.

un_classification str

The UN classification.

id class-attribute instance-attribute

id: str = Field(alias='albertId')

shipping_description class-attribute instance-attribute

shipping_description: str = Field(
    alias="shippingDescription"
)

storage_class_name class-attribute instance-attribute

storage_class_name: str = Field(alias='storageClassName')

storage_class_number class-attribute instance-attribute

storage_class_number: str = Field(
    alias="storageClassNumber"
)

un_classification class-attribute instance-attribute

un_classification: str = Field(alias='unClassification')

un_number class-attribute instance-attribute

un_number: str = Field(alias='unNumber')

UnNumberCollection

UnNumberCollection(*, session: AlbertSession)

Bases: BaseCollection

UnNumberCollection is a collection class for managing UnNumber entities in the Albert platform.

Note

Creating UN Numbers is not supported via the SDK, as UN Numbers are highly controlled by Albert.

Parameters:

Name Type Description Default
session AlbertSession

The Albert session instance.

required

Methods:

Name Description
create

This method is not implemented as UN Numbers cannot be created through the SDK.

get_all

Get all UN Numbers matching the provided criteria.

get_by_id

Retrieve a UN Number by its ID.

get_by_name

Retrieve a UN Number by its name.

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

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

base_path instance-attribute

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

create

create() -> None

This method is not implemented as UN Numbers cannot be created through the SDK.

Source code in src/albert/collections/un_numbers.py
def create(self) -> None:
    """
    This method is not implemented as UN Numbers cannot be created through the SDK.
    """
    raise NotImplementedError()

get_all

get_all(
    *,
    name: str | None = None,
    exact_match: bool = False,
    limit: int = 50,
    start_key: str | None = None,
) -> Iterator[UnNumber]

Get all UN Numbers matching the provided criteria.

Parameters:

Name Type Description Default
name str | None

The name of the UN Number to search for, by default None

None
exact_match bool

Weather to return exact matches only, by default False

False

Yields:

Type Description
Iterator[UnNumber]

The UN Numbers matching the search criteria

Source code in src/albert/collections/un_numbers.py
def get_all(
    self,
    *,
    name: str | None = None,
    exact_match: bool = False,
    limit: int = 50,
    start_key: str | None = None,
) -> Iterator[UnNumber]:
    """Get all UN Numbers matching the provided criteria.

    Parameters
    ----------
    name : str | None, optional
        The name of the UN Number to search for, by default None
    exact_match : bool, optional
        Weather to return exact matches only, by default False

    Yields
    ------
    Iterator[UnNumber]
        The UN Numbers matching the search criteria
    """
    params = {"limit": limit, "startKey": start_key}
    if name:
        params["name"] = name
        params["exactMatch"] = json.dumps(exact_match)
    return AlbertPaginator(
        mode=PaginationMode.KEY,
        path=self.base_path,
        session=self.session,
        params=params,
        deserialize=lambda items: [UnNumber(**item) for item in items],
    )

get_by_id

get_by_id(*, id: str) -> UnNumber

Retrieve a UN Number by its ID.

Parameters:

Name Type Description Default
id str

The ID of the UN Number to retrieve.

required

Returns:

Type Description
UnNumber

The corresponding UN Number

Source code in src/albert/collections/un_numbers.py
def get_by_id(self, *, id: str) -> UnNumber:
    """Retrieve a UN Number by its ID.

    Parameters
    ----------
    id : str
        The ID of the UN Number to retrieve.

    Returns
    -------
    UnNumber
        The corresponding UN Number
    """
    url = f"{self.base_path}/{id}"
    response = self.session.get(url)
    return UnNumber(**response.json())

get_by_name

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

Retrieve a UN Number by its name.

Parameters:

Name Type Description Default
name str

The name of the UN Number to retrieve

required

Returns:

Type Description
UnNumber | None

The corresponding UN Number or None if not found

Source code in src/albert/collections/un_numbers.py
def get_by_name(self, *, name: str) -> UnNumber | None:
    """Retrieve a UN Number by its name.

    Parameters
    ----------
    name : str
        The name of the UN Number to retrieve

    Returns
    -------
    UnNumber | None
        The corresponding UN Number or None if not found
    """
    found = self.get_all(exact_match=True, name=name)
    return next(found, None)