Utilities and Helpers

The UniFi Controller API includes several utility modules to help with common tasks.

Logging Utilities

unifi_controller_api.logging.get_logger(name=None)[source]

Get a logger with the appropriate name.

Parameters:

name (Optional[str]) – Optional specific logger name. If not provided, uses the module’s __name__.

Return type:

Logger

Returns:

A logger instance for the specified name

unifi_controller_api.logging.log_extra_fields(logger, obj_name, obj_id, extra_fields, max_length=300)[source]

Log extra fields found in an object using the provided logger.

Parameters:
  • logger (Logger) – Logger to use

  • obj_name (str) – Name of the object type (e.g., ‘Device’, ‘Site’).

  • obj_id (str) – Identifier for the specific object (e.g., MAC address, site name).

  • extra_fields (Dict[str, Any]) – Dictionary of extra fields.

  • max_length (int) – Maximum length for field values in the log. Default is 300.

unifi_controller_api.logging.log_api_response(logger, url, response_data, status_code, truncate=True, max_length=500)[source]

Log API response data using the provided logger.

Parameters:
  • logger (Logger) – Logger to use

  • url (str) – The API URL that was called.

  • response_data (Dict[str, Any]) – The response data as a dictionary.

  • status_code (int) – HTTP status code.

  • truncate (bool) – Whether to truncate large response values. Default is True.

  • max_length (int) – Maximum length for response in the log if truncated. Default is 500.

Exception Handling

exception unifi_controller_api.exceptions.UnifiControllerError[source]

Bases: Exception

Base exception for UnifiController errors.

exception unifi_controller_api.exceptions.UnifiAuthenticationError[source]

Bases: UnifiControllerError

Raised when authentication with the UniFi Controller fails.

exception unifi_controller_api.exceptions.UnifiAPIError[source]

Bases: UnifiControllerError

Raised when an API call to the UniFi Controller fails.

exception unifi_controller_api.exceptions.UnifiDataError[source]

Bases: UnifiControllerError

Raised when there is an error parsing data from the UniFi Controller.

exception unifi_controller_api.exceptions.UnifiModelError[source]

Bases: UnifiControllerError

Raised when there is an error loading or processing device models.

Utility Functions

Utility functions for the UniFi Controller API package.

unifi_controller_api.utils.get_api_field_mapping(model_class)[source]

Create a mapping between API field names and model attribute names.

Examines dataclass fields with metadata to find mappings between API field names (like ‘user-num_sta’) and Python attribute names (like ‘user_num_sta’).

Parameters:

model_class (Type) – The dataclass model to examine for field mappings

Return type:

Dict[str, str]

Returns:

Dictionary mapping UniFi API field names to Python model attribute names

unifi_controller_api.utils.filter_valid_fields(data, model_class)[source]

Filter a dictionary to only include fields that are valid for the model class.

Parameters:
  • data (Dict[str, Any]) – Input dictionary with potentially invalid fields

  • model_class (Type) – The model class to filter fields for

Return type:

Dict[str, Any]

Returns:

Dictionary containing only fields that are valid parameters for the model class

unifi_controller_api.utils.extract_extra_fields(data, model_class)[source]

Extract fields from a dictionary that are not valid for the model class.

Parameters:
  • data (Dict[str, Any]) – Input dictionary with potentially invalid fields

  • model_class (Type) – The model class to check fields against

Return type:

Dict[str, Any]

Returns:

Dictionary containing only fields that are NOT valid parameters for the model class

unifi_controller_api.utils.map_api_data_to_model(data, model_class)[source]

Maps API data to model fields, handling special field names and separating model fields from extra fields.

This function handles: - Direct field matches - Fields with api_key metadata mapping - Nested data structures - Extra fields preservation

Parameters:
  • data (Dict[str, Any]) – Input dictionary from API response

  • model_class (Type) – The dataclass model to map data to

Returns:

  • model_fields: Dictionary of fields that map to the model’s attributes

  • extra_fields: Dictionary of extra fields that don’t directly map to the model

Return type:

Tuple containing (model_fields, extra_fields) where

unifi_controller_api.utils.resolve_model_names(devices, model_db_path=None)[source]

Centralized function to resolve model names for a list of UnifiDevice objects.

This function is used to populate the model_name field based on the device model code, using the device-models.json database.

Parameters:
  • devices (List[UnifiDevice]) – List of UnifiDevice objects to resolve model names for

  • model_db_path (Optional[str]) – Path to the device model database JSON file. If None, uses the built-in device-models.json file.

Return type:

None

This function modifies the devices in-place, setting their model_name attribute. It only sets model_name if it’s not already set, preserving existing values.

Raises:

UnifiModelError – If the device model database cannot be loaded.

Parameters:
Return type:

None

Common Usage Examples

Setting Up Logging

from unifi_controller_api.logging import setup_logger

# Set up a logger with a specific name and level
logger = setup_logger("my_app", log_level="INFO")

# Use the logger
logger.info("Connected to UniFi Controller")
logger.error("Failed to connect")

Handling Exceptions

from unifi_controller_api import UnifiController
from unifi_controller_api.exceptions import UnifiLoginError, UnifiError

try:
    controller = UnifiController("https://unifi.example.com", "admin", "wrong_password")
except UnifiLoginError as e:
    print(f"Login failed: {e}")
except UnifiError as e:
    print(f"Other UniFi error: {e}")