Skip to content

Locations

albert.collections.locations.LocationCollection

LocationCollection(*, session: AlbertSession)

Bases: BaseCollection

Manage Locations in the Albert platform.

A Location is a physical lab or site (for example, a building, plant, or campus) where work happens in Albert. Locations are referenced by Tasks and by Inventory Items to record where an activity is performed or where a material lives, and each Location can hold one or more Storage Locations (StorageLocation).

This collection is accessed as client.locations.

Example

from albert import Albert
client = Albert()
for location in client.locations.get_all(country="US"):
    print(location.id, location.name)

Parameters:

Name Type Description Default
session AlbertSession

The authenticated Albert session used for API calls.

required

Attributes:

Name Type Description
base_path str

The base API route for location requests.

Methods:

Name Description
create

Create a new location.

get_by_id

Get a single location by its Albert ID.

get_all

Iterate over locations, optionally filtered by name or country.

update

Update an existing location.

exists

Return the existing location matching the given name, or None.

get_or_create

Return the matching location if it exists, otherwise create it.

delete

Delete a location by its Albert ID.

Parameters:

Name Type Description Default
session AlbertSession

The authenticated Albert session used for API calls.

required
Source code in src/albert/collections/locations.py
def __init__(self, *, session: AlbertSession):
    """Initialize a LocationCollection.

    Parameters
    ----------
    session : AlbertSession
        The authenticated Albert session used for API calls.
    """
    super().__init__(session=session)
    self.base_path = f"/api/{LocationCollection._api_version}/locations"

base_path

base_path = (
    f"/api/{LocationCollection._api_version}/locations"
)

get_all

get_all(
    *,
    ids: list[str] | None = None,
    name: str | list[str] | None = None,
    country: str | None = None,
    exact_match: bool = False,
    start_key: str | None = None,
    max_items: int | None = None,
) -> Iterator[Location]

Iterate over Locations, optionally filtered by name or country.

Results are yielded lazily and pagination is handled automatically.

Example

for location in client.locations.get_all(name="Boston Lab"):
    print(location.id, location.name)

Parameters:

Name Type Description Default
ids list[str]

Restrict results to these Albert location IDs. Maximum of 100.

None
name str or list[str]

One or more location names to search for.

None
country str

Two-letter country code to filter by (for example, "US").

None
exact_match bool

If True, match name exactly instead of as a substring. Default is False.

False
start_key str

Pagination key to resume iteration from a previous page.

None
max_items int

Maximum number of locations to return in total. If None, all matching locations are returned.

None

Returns:

Type Description
Iterator[Location]

Locations matching the given filters.

Source code in src/albert/collections/locations.py
def get_all(
    self,
    *,
    ids: list[str] | None = None,
    name: str | list[str] | None = None,
    country: str | None = None,
    exact_match: bool = False,
    start_key: str | None = None,
    max_items: int | None = None,
) -> Iterator[Location]:
    """Iterate over Locations, optionally filtered by name or country.

    Results are yielded lazily and pagination is handled automatically.

    !!! example
        ```python
        for location in client.locations.get_all(name="Boston Lab"):
            print(location.id, location.name)
        ```

    Parameters
    ----------
    ids : list[str], optional
        Restrict results to these Albert location IDs. Maximum of 100.
    name : str or list[str], optional
        One or more location names to search for.
    country : str, optional
        Two-letter country code to filter by (for example, ``"US"``).
    exact_match : bool, optional
        If True, match ``name`` exactly instead of as a substring.
        Default is False.
    start_key : str, optional
        Pagination key to resume iteration from a previous page.
    max_items : int, optional
        Maximum number of locations to return in total. If None, all
        matching locations are returned.

    Returns
    -------
    Iterator[Location]
        Locations matching the given filters.
    """
    params = {
        "startKey": start_key,
        "country": country,
    }
    if ids:
        params["id"] = ids
    params["name"] = ensure_list(name)
    params["exactMatch"] = exact_match

    return AlbertPaginator(
        mode=PaginationMode.KEY,
        path=self.base_path,
        session=self.session,
        params=params,
        max_items=max_items,
        deserialize=lambda items: [Location(**item) for item in items],
    )

get_by_id

get_by_id(*, id: str) -> Location

Get a single Location by its Albert ID.

Example

location = client.locations.get_by_id(id="...")
print(location.name)

Parameters:

Name Type Description Default
id str

The Albert ID of the location to retrieve.

required

Returns:

Type Description
Location

The fully populated location.

Source code in src/albert/collections/locations.py
def get_by_id(self, *, id: str) -> Location:
    """Get a single Location by its Albert ID.

    !!! example
        ```python
        location = client.locations.get_by_id(id="...")
        print(location.name)
        ```

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

    Returns
    -------
    Location
        The fully populated location.
    """
    url = f"{self.base_path}/{id}"
    response = self.session.get(url)
    return Location(**response.json())

update

update(*, location: Location) -> Location

Update an existing Location.

Fetch a location (e.g. via get_by_id), modify the updatable fields on the returned object, then pass it here. The location is matched by its id.

Example

location = client.locations.get_by_id(id="...")
location.name = "Boston Lab (Bldg 2)"
updated = client.locations.update(location=location)

Parameters:

Name Type Description Default
location Location

The location to update. Its id must be set.

required

Returns:

Type Description
Location

The updated location, re-fetched from Albert.

Notes

The following fields can be updated: address, country, latitude, longitude, name.

Source code in src/albert/collections/locations.py
def update(self, *, location: Location) -> Location:
    """Update an existing Location.

    Fetch a location (e.g. via [`get_by_id`][albert.collections.locations.LocationCollection.get_by_id]), modify the updatable fields on
    the returned object, then pass it here. The location is matched by its ``id``.

    !!! example
        ```python
        location = client.locations.get_by_id(id="...")
        location.name = "Boston Lab (Bldg 2)"
        updated = client.locations.update(location=location)
        ```

    Parameters
    ----------
    location : Location
        The location to update. Its ``id`` must be set.

    Returns
    -------
    Location
        The updated location, re-fetched from Albert.

    Notes
    -----
    The following fields can be updated: ``address``, ``country``,
    ``latitude``, ``longitude``, ``name``.
    """
    # Fetch the current object state from the server or database
    current_object = self.get_by_id(id=location.id)
    # Generate the PATCH payload
    patch_payload = self._generate_patch_payload(
        existing=current_object,
        updated=location,
        stringify_values=True,
    )
    url = f"{self.base_path}/{location.id}"
    self.session.patch(url, json=patch_payload.model_dump(mode="json", by_alias=True))
    return self.get_by_id(id=location.id)

exists

exists(*, location: Location) -> Location | None

Return the existing Location matching the given name, or None.

The match is case-insensitive on name. Useful before creating a location to avoid duplicates.

Example

from albert.resources.locations import Location
candidate = Location(
    name="Boston Lab",
    latitude=42.3601,
    longitude=-71.0589,
    address="1 Main St",
    country="US",
)
existing = client.locations.exists(location=candidate)

Parameters:

Name Type Description Default
location Location

The location to look for. Its name is used to match.

required

Returns:

Type Description
Location or None

The matching registered location, or None if no match is found.

Source code in src/albert/collections/locations.py
def exists(self, *, location: Location) -> Location | None:
    """Return the existing Location matching the given name, or None.

    The match is case-insensitive on ``name``. Useful before creating a
    location to avoid duplicates.

    !!! example
        ```python
        from albert.resources.locations import Location
        candidate = Location(
            name="Boston Lab",
            latitude=42.3601,
            longitude=-71.0589,
            address="1 Main St",
            country="US",
        )
        existing = client.locations.exists(location=candidate)
        ```

    Parameters
    ----------
    location : Location
        The location to look for. Its ``name`` is used to match.

    Returns
    -------
    Location or None
        The matching registered location, or None if no match is found.
    """
    return self._find_by_name(location=location)

create

create(*, location: Location) -> Location

Create a new Location.

Example

from albert.resources.locations import Location
location = client.locations.create(
    location=Location(
        name="Boston Lab",
        latitude=42.3601,
        longitude=-71.0589,
        address="1 Main St",
        country="US",
    )
)

Parameters:

Name Type Description Default
location Location

The location to create.

required

Returns:

Type Description
Location

The newly created location, populated with its assigned id.

Source code in src/albert/collections/locations.py
def create(self, *, location: Location) -> Location:
    """Create a new Location.

    !!! example
        ```python
        from albert.resources.locations import Location
        location = client.locations.create(
            location=Location(
                name="Boston Lab",
                latitude=42.3601,
                longitude=-71.0589,
                address="1 Main St",
                country="US",
            )
        )
        ```

    Parameters
    ----------
    location : Location
        The location to create.

    Returns
    -------
    Location
        The newly created location, populated with its assigned ``id``.
    """
    payload = location.model_dump(
        by_alias=True,
        exclude_none=True,
        mode="json",
        exclude={"id", "status", "created", "updated"},
    )
    response = self.session.post(self.base_path, json=payload)

    return Location(**response.json())

get_or_create

get_or_create(*, location: Location) -> Location

Return the matching Location if it exists, otherwise create it.

Looks for an existing location with the same name (see exists) and returns it; if none is found, creates the location.

Example

from albert.resources.locations import Location
location = client.locations.get_or_create(
    location=Location(
        name="Boston Lab",
        latitude=42.3601,
        longitude=-71.0589,
        address="1 Main St",
        country="US",
    )
)

Parameters:

Name Type Description Default
location Location

The location to retrieve or create.

required

Returns:

Type Description
Location

The existing or newly created location.

Source code in src/albert/collections/locations.py
def get_or_create(self, *, location: Location) -> Location:
    """Return the matching Location if it exists, otherwise create it.

    Looks for an existing location with the same name (see [`exists`][albert.collections.locations.LocationCollection.exists])
    and returns it; if none is found, creates the location.

    !!! example
        ```python
        from albert.resources.locations import Location
        location = client.locations.get_or_create(
            location=Location(
                name="Boston Lab",
                latitude=42.3601,
                longitude=-71.0589,
                address="1 Main St",
                country="US",
            )
        )
        ```

    Parameters
    ----------
    location : Location
        The location to retrieve or create.

    Returns
    -------
    Location
        The existing or newly created location.
    """
    if location.id:
        return self.get_by_id(id=location.id)

    found = self._find_by_name(location=location)
    if found:
        return found

    try:
        return self.create(location=location)
    except BadRequestError:
        found = self._find_by_name(location=location)
        if found:
            return found
        raise

delete

delete(*, id: str) -> None

Delete a Location by its Albert ID.

Example

client.locations.delete(id="...")

Parameters:

Name Type Description Default
id str

The Albert ID of the location to delete.

required

Returns:

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

    !!! example
        ```python
        client.locations.delete(id="...")
        ```

    Parameters
    ----------
    id : str
        The Albert ID of the location to delete.

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