Skip to content

Reference for hub_sdk/base/crud_client.py

Improvements

This page is sourced from https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/base/crud_client.py. Have an improvement or example to add? Open a Pull Request — thank you! 🙏


class hub_sdk.base.crud_client.CRUDClient

CRUDClient(self, base_endpoint: str, name: str, headers: dict)

Bases: APIClient

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

This class provides methods for performing standard CRUD operations on API resources, handling errors gracefully and providing logging for failed operations.

Args

NameTypeDescriptionDefault
base_endpointstrThe base endpoint URL for the API.required
namestrThe name associated with the CRUD operations (e.g., "User").required
headersdictHeaders to be included in API requests.required

Attributes

NameTypeDescription
namestrThe name associated with the CRUD operations (e.g., "User").
loggerlogging.LoggerAn instance of the logger for logging purposes.

Methods

NameDescription
createCreate a new entity using the API.
deleteDelete an entity using the API.
listList entities using the API with pagination support.
readRetrieve details of a specific entity.
updateUpdate an existing entity using the API.
Source code in hub_sdk/base/crud_client.pyView on GitHub
class CRUDClient(APIClient):
    """Represents a CRUD (Create, Read, Update, Delete) client for interacting with a specific resource.

    This class provides methods for performing standard CRUD operations on API resources, handling errors gracefully and
    providing logging for failed operations.

    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: str, name: str, headers: dict):
        """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


method hub_sdk.base.crud_client.CRUDClient.create

def create(self, data: dict) -> Response | None

Create a new entity using the API.

Args

NameTypeDescriptionDefault
datadictThe data to be sent as part of the creation request.required

Returns

TypeDescription
Optional[Response]Response object from the create request, or None if creation fails.
Source code in hub_sdk/base/crud_client.pyView on GitHub
def create(self, data: dict) -> Response | None:
    """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 creation fails.
    """
    try:
        return self.post("", json=data)
    except Exception as e:
        self.logger.error(f"Failed to create {self.name}: {e}")


method hub_sdk.base.crud_client.CRUDClient.delete

def delete(self, id: str, hard: bool = False) -> Response | None

Delete an entity using the API.

Args

NameTypeDescriptionDefault
idstrThe unique identifier of the entity to delete.required
hardbool, optionalIf True, perform a hard delete. If False, perform a soft delete.False

Returns

TypeDescription
Optional[Response]Response object from the delete request, or None if deletion fails.
Source code in hub_sdk/base/crud_client.pyView on GitHub
def delete(self, id: str, hard: bool = False) -> Response | None:
    """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 deletion 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}")


method hub_sdk.base.crud_client.CRUDClient.list

def list(self, page: int = 0, limit: int = 10) -> Response | None

List entities using the API with pagination support.

Args

NameTypeDescriptionDefault
pageint, optionalThe page number to retrieve.0
limitint, optionalThe maximum number of entities per page.10

Returns

TypeDescription
Optional[Response]Response object from the list request, or None if listing fails.
Source code in hub_sdk/base/crud_client.pyView on GitHub
def list(self, page: int = 0, limit: int = 10) -> Response | None:
    """List entities using the API with pagination support.

    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 listing 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}")


method hub_sdk.base.crud_client.CRUDClient.read

def read(self, id: str) -> Response | None

Retrieve details of a specific entity.

Args

NameTypeDescriptionDefault
idstrThe unique identifier of the entity to retrieve.required

Returns

TypeDescription
Optional[Response]Response object from the read request, or None if retrieval fails.
Source code in hub_sdk/base/crud_client.pyView on GitHub
def read(self, id: str) -> Response | None:
    """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 retrieval fails.
    """
    try:
        return self.get(f"/{id}")
    except Exception as e:
        self.logger.error(f"Failed to read {self.name} with ID: {id}, {e}")


method hub_sdk.base.crud_client.CRUDClient.update

def update(self, id: str, data: dict) -> Response | None

Update an existing entity using the API.

Args

NameTypeDescriptionDefault
idstrThe unique identifier of the entity to update.required
datadictThe updated data to be sent in the update request.required

Returns

TypeDescription
Optional[Response]Response object from the update request, or None if update fails.
Source code in hub_sdk/base/crud_client.pyView on GitHub
def update(self, id: str, data: dict) -> Response | None:
    """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}")