Skip to content

Reference for hub_sdk/base/crud_client.py

Note

This file is available at https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/base/crud_client.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!



hub_sdk.base.crud_client.CRUDClient

Bases: APIClient

Represents a CRUD (Create, Read, Update, Delete) client for interacting with a specific resource.

Attributes:

Name Type Description
name str

The name associated with the CRUD operations (e.g., "User").

logger Logger

An instance of the logger for logging purposes.

Source code in hub_sdk/base/crud_client.py
class CRUDClient(APIClient):
    """
    Represents a CRUD (Create, Read, Update, Delete) client for interacting with a specific resource.

    Attributes:
        name (str): The name associated with the CRUD operations (e.g., "User").
        logger (logging.Logger): An instance of the logger for logging purposes.
    """

    def __init__(self, base_endpoint, name, headers):
        """
        Initialize a CRUDClient instance.

        Args:
            base_endpoint (str): The base endpoint URL for the API.
            name (str): The name associated with the CRUD operations (e.g., "User").
            headers (dict): Headers to be included in API requests.
        """
        super().__init__(f"{HUB_FUNCTIONS_ROOT}/v1/{base_endpoint}", headers)
        self.name = name
        self.logger = logger

    def create(self, data: dict) -> Optional[Response]:
        """
        Create a new entity using the API.

        Args:
            data (dict): The data to be sent as part of the creation request.

        Returns:
            (Optional[Response]): Response object from the create request, or None if upload fails.
        """
        try:
            return self.post("", json=data)
        except Exception as e:
            self.logger.error(f"Failed to create {self.name}: {e}")

    def read(self, id: str) -> Optional[Response]:
        """
        Retrieve details of a specific entity.

        Args:
            id (str): The unique identifier of the entity to retrieve.

        Returns:
            (Optional[Response]): Response object from the read request, or None if read fails.
        """
        try:
            return self.get(f"/{id}")
        except Exception as e:
            self.logger.error(f"Failed to read {self.name} with ID: {id}, {e}")

    def update(self, id: str, data: dict) -> Optional[Response]:
        """
        Update an existing entity using the API.

        Args:
            id (str): The unique identifier of the entity to update.
            data (dict): The updated data to be sent in the update request.

        Returns:
            (Optional[Response]): Response object from the update request, or None if update fails.
        """
        try:
            return self.patch(f"/{id}", json=data)
        except Exception as e:
            self.logger.error(f"Failed to update {self.name} with ID: {id}, {e}")

    def delete(self, id: str, hard: bool = False) -> Optional[Response]:
        """
        Delete an entity using the API.

        Args:
            id (str): The unique identifier of the entity to delete.
            hard (bool, optional): If True, perform a hard delete. If False, perform a soft delete.

        Returns:
            (Optional[Response]): Response object from the delete request, or None if delete fails.
        """
        try:
            return super().delete(f"/{id}", {"hard": hard})
        except Exception as e:
            self.logger.error(f"Failed to delete {self.name} with ID: {id}, {e}")

    def list(self, page: int = 0, limit: int = 10) -> Optional[Response]:
        """
        List entities using the API.

        Args:
            page (int, optional): The page number to retrieve.
            limit (int, optional): The maximum number of entities per page.

        Returns:
            (Optional[Response]): Response object from the list request, or None if it fails.
        """
        try:
            params = {"page": page, "limit": limit}
            return self.get("", params=params)
        except Exception as e:
            self.logger.error(f"Failed to list {self.name}: {e}")

__init__(base_endpoint, name, headers)

Initialize a CRUDClient instance.

Parameters:

Name Type Description Default
base_endpoint str

The base endpoint URL for the API.

required
name str

The name associated with the CRUD operations (e.g., "User").

required
headers dict

Headers to be included in API requests.

required
Source code in hub_sdk/base/crud_client.py
def __init__(self, base_endpoint, name, headers):
    """
    Initialize a CRUDClient instance.

    Args:
        base_endpoint (str): The base endpoint URL for the API.
        name (str): The name associated with the CRUD operations (e.g., "User").
        headers (dict): Headers to be included in API requests.
    """
    super().__init__(f"{HUB_FUNCTIONS_ROOT}/v1/{base_endpoint}", headers)
    self.name = name
    self.logger = logger

create(data)

Create a new entity using the API.

Parameters:

Name Type Description Default
data dict

The data to be sent as part of the creation request.

required

Returns:

Type Description
Optional[Response]

Response object from the create request, or None if upload fails.

Source code in hub_sdk/base/crud_client.py
def create(self, data: dict) -> Optional[Response]:
    """
    Create a new entity using the API.

    Args:
        data (dict): The data to be sent as part of the creation request.

    Returns:
        (Optional[Response]): Response object from the create request, or None if upload fails.
    """
    try:
        return self.post("", json=data)
    except Exception as e:
        self.logger.error(f"Failed to create {self.name}: {e}")

delete(id, hard=False)

Delete an entity using the API.

Parameters:

Name Type Description Default
id str

The unique identifier of the entity to delete.

required
hard bool

If True, perform a hard delete. If False, perform a soft delete.

False

Returns:

Type Description
Optional[Response]

Response object from the delete request, or None if delete fails.

Source code in hub_sdk/base/crud_client.py
def delete(self, id: str, hard: bool = False) -> Optional[Response]:
    """
    Delete an entity using the API.

    Args:
        id (str): The unique identifier of the entity to delete.
        hard (bool, optional): If True, perform a hard delete. If False, perform a soft delete.

    Returns:
        (Optional[Response]): Response object from the delete request, or None if delete fails.
    """
    try:
        return super().delete(f"/{id}", {"hard": hard})
    except Exception as e:
        self.logger.error(f"Failed to delete {self.name} with ID: {id}, {e}")

list(page=0, limit=10)

List entities using the API.

Parameters:

Name Type Description Default
page int

The page number to retrieve.

0
limit int

The maximum number of entities per page.

10

Returns:

Type Description
Optional[Response]

Response object from the list request, or None if it fails.

Source code in hub_sdk/base/crud_client.py
def list(self, page: int = 0, limit: int = 10) -> Optional[Response]:
    """
    List entities using the API.

    Args:
        page (int, optional): The page number to retrieve.
        limit (int, optional): The maximum number of entities per page.

    Returns:
        (Optional[Response]): Response object from the list request, or None if it fails.
    """
    try:
        params = {"page": page, "limit": limit}
        return self.get("", params=params)
    except Exception as e:
        self.logger.error(f"Failed to list {self.name}: {e}")

read(id)

Retrieve details of a specific entity.

Parameters:

Name Type Description Default
id str

The unique identifier of the entity to retrieve.

required

Returns:

Type Description
Optional[Response]

Response object from the read request, or None if read fails.

Source code in hub_sdk/base/crud_client.py
def read(self, id: str) -> Optional[Response]:
    """
    Retrieve details of a specific entity.

    Args:
        id (str): The unique identifier of the entity to retrieve.

    Returns:
        (Optional[Response]): Response object from the read request, or None if read fails.
    """
    try:
        return self.get(f"/{id}")
    except Exception as e:
        self.logger.error(f"Failed to read {self.name} with ID: {id}, {e}")

update(id, data)

Update an existing entity using the API.

Parameters:

Name Type Description Default
id str

The unique identifier of the entity to update.

required
data dict

The updated data to be sent in the update request.

required

Returns:

Type Description
Optional[Response]

Response object from the update request, or None if update fails.

Source code in hub_sdk/base/crud_client.py
def update(self, id: str, data: dict) -> Optional[Response]:
    """
    Update an existing entity using the API.

    Args:
        id (str): The unique identifier of the entity to update.
        data (dict): The updated data to be sent in the update request.

    Returns:
        (Optional[Response]): Response object from the update request, or None if update fails.
    """
    try:
        return self.patch(f"/{id}", json=data)
    except Exception as e:
        self.logger.error(f"Failed to update {self.name} with ID: {id}, {e}")