Skip to content

Notes

albert.collections.notes

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

Note

Bases: BaseResource

Represents a Note on the Albert Platform. Users can be mentioned in notes by using f-string and the User.to_note_mention() method. This allows for easy tagging and referencing of users within notes. example: f"Hello {tagged_user.to_note_mention()}!"

attachments class-attribute instance-attribute

attachments: list[EntityLink] | None = Field(
    default=None,
    exclude=True,
    frozen=True,
    alias="Attachments",
)

id class-attribute instance-attribute

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

note instance-attribute

note: str

parent_id class-attribute instance-attribute

parent_id: str = Field(..., alias='parentId')

NotesCollection

NotesCollection(*, session: AlbertSession)

Bases: BaseCollection

NotesCollection is a collection class for managing Note entities in the Albert platform.

Methods:

Name Description
create

Creates a new note.

delete

Deletes a note by its ID.

get_all

Get all notes by their parent ID.

get_by_id

Retrieves a note by its ID.

update

Updates a note.

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

base_path instance-attribute

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

create

create(*, note: Note) -> Note

Creates a new note.

Parameters:

Name Type Description Default
note str

The note content.

required

Returns:

Type Description
Note

The created note.

Source code in src/albert/collections/notes.py
def create(self, *, note: Note) -> Note:
    """
    Creates a new note.

    Parameters
    ----------
    note : str
        The note content.

    Returns
    -------
    Note
        The created note.
    """
    response = self.session.post(
        self.base_path, json=note.model_dump(by_alias=True, exclude_unset=True, mode="json")
    )
    return Note(**response.json())

delete

delete(*, id: str) -> None

Deletes a note by its ID.

Parameters:

Name Type Description Default
id str

The ID of the note to delete.

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

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

get_all

get_all(
    *, parent_id: str, order_by: OrderBy = DESCENDING
) -> list[Note]

Get all notes by their parent ID.

Parameters:

Name Type Description Default
parent_id str

The parent ID of the notes to list.

required
order_by OrderBy

The order to list notes in, by default OrderBy.DESCENDING.

DESCENDING

Returns:

Type Description
List[Note]

The list of notes.

Source code in src/albert/collections/notes.py
def get_all(self, *, parent_id: str, order_by: OrderBy = OrderBy.DESCENDING) -> list[Note]:
    """
    Get all notes by their parent ID.

    Parameters
    ----------
    parent_id : str
        The parent ID of the notes to list.
    order_by : OrderBy, optional
        The order to list notes in, by default OrderBy.DESCENDING.

    Returns
    -------
    List[Note]
        The list of notes.
    """

    params = {"parentId": parent_id, "orderBy": order_by.value}
    return AlbertPaginator(
        session=self.session,
        path=self.base_path,
        mode=PaginationMode.KEY,
        params=params,
        deserialize=lambda items: [Note(**item) for item in items],
    )

get_by_id

get_by_id(*, id: str) -> Note

Retrieves a note by its ID.

Parameters:

Name Type Description Default
id str

The ID of the note to retrieve.

required

Returns:

Type Description
Note

The note if found, None otherwise.

Source code in src/albert/collections/notes.py
def get_by_id(self, *, id: str) -> Note:
    """
    Retrieves a note by its ID.

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

    Returns
    -------
    Note
        The note if found, None otherwise.
    """
    response = self.session.get(f"{self.base_path}/{id}")
    return Note(**response.json())

update

update(*, note: Note) -> Note

Updates a note.

Parameters:

Name Type Description Default
note Note

The note to update. The note must have an ID.

required

Returns:

Type Description
Note

The updated note as returned by the server.

Source code in src/albert/collections/notes.py
def update(self, *, note: Note) -> Note:
    """Updates a note.

    Parameters
    ----------
    note : Note
        The note to update. The note must have an ID.

    Returns
    -------
    Note
        The updated note as returned by the server.
    """
    patch = self._generate_patch_payload(
        existing=self.get_by_id(id=note.id), updated=note, generate_metadata_diff=False
    )
    self.session.patch(
        f"{self.base_path}/{note.id}",
        json=patch.model_dump(mode="json", by_alias=True, exclude_unset=True),
    )
    return self.get_by_id(id=note.id)

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'