UniFi API Client

The UnifiController class is the main interface for interacting with the UniFi Controller API.

class unifi_controller_api.api_client.UnifiController(controller_url, username, password, is_udm_pro=False, verify_ssl=True, auto_model_mapping=True, model_db_path=None, auth_retry_enabled=True, auth_retry_count=3, auth_retry_delay=1)[source]

Bases: object

Client for interacting with the Unifi Controller API.

This class provides methods to authenticate, fetch data about sites and devices, and generate reports from a Unifi Controller.

Note

This client interacts with the UniFi Controller’s undocumented private API. Response structures and endpoint behavior may change without notice between controller versions. While this library attempts to provide stable methods and data models, users should be prepared for potential inconsistencies and check the _extra_fields attribute on returned dataclass objects for unexpected data.

Initialize the Unifi Controller client and authenticate.

Parameters:
  • controller_url – Base URL of the Unifi Controller.

  • username – Username for authentication.

  • password – Password for authentication.

  • is_udm_pro – Whether the controller is a UniFi OS device. Set to True for: UDM, UDM Pro, UDR, Cloud Key Gen2 (2.0.24+), UX, UDW, UCG-Ultra, CK-Enterprise, and EFG. Defaults to False.

  • verify_ssl – Whether to verify SSL certificates. Can be: - True: Verify SSL certificates (default, recommended) - False: Disable verification (insecure, not recommended) - str: Path to a CA bundle file or directory with certificates of trusted CAs

  • auto_model_mapping – Whether to automatically populate model_name using the device-models.json database. Defaults to True.

  • model_db_path – Optional custom path to the device model database JSON file. If None, uses the built-in device-models.json file. Defaults to None.

  • auth_retry_enabled – Whether to automatically retry authentication when session expires. Defaults to True.

  • auth_retry_count – Maximum number of authentication retry attempts (1-10). Defaults to 3.

  • auth_retry_delay – Delay in seconds between retry attempts (0.1-30). Defaults to 1.

__init__(controller_url, username, password, is_udm_pro=False, verify_ssl=True, auto_model_mapping=True, model_db_path=None, auth_retry_enabled=True, auth_retry_count=3, auth_retry_delay=1)[source]

Initialize the Unifi Controller client and authenticate.

Parameters:
  • controller_url – Base URL of the Unifi Controller.

  • username – Username for authentication.

  • password – Password for authentication.

  • is_udm_pro – Whether the controller is a UniFi OS device. Set to True for: UDM, UDM Pro, UDR, Cloud Key Gen2 (2.0.24+), UX, UDW, UCG-Ultra, CK-Enterprise, and EFG. Defaults to False.

  • verify_ssl – Whether to verify SSL certificates. Can be: - True: Verify SSL certificates (default, recommended) - False: Disable verification (insecure, not recommended) - str: Path to a CA bundle file or directory with certificates of trusted CAs

  • auto_model_mapping – Whether to automatically populate model_name using the device-models.json database. Defaults to True.

  • model_db_path – Optional custom path to the device model database JSON file. If None, uses the built-in device-models.json file. Defaults to None.

  • auth_retry_enabled – Whether to automatically retry authentication when session expires. Defaults to True.

  • auth_retry_count – Maximum number of authentication retry attempts (1-10). Defaults to 3.

  • auth_retry_delay – Delay in seconds between retry attempts (0.1-30). Defaults to 1.

authenticate(username, password)[source]

Authenticate with the Unifi Controller.

For UniFi OS devices (UDM, UDM Pro, UDR, etc.), uses /api/auth/login followed by changing the API path to /proxy/network. For legacy controllers, uses /api/login directly.

Parameters:
  • username – Username for authentication. Must be a local account, not a cloud account.

  • password – Password for authentication.

Raises:

UnifiAuthenticationError – If authentication fails.

invoke_get_rest_api_call(url, headers=None)[source]

Make a GET request to the UniFi Controller REST API with automatic session renewal.

When a 401 Unauthorized error is received (indicating an expired session), this method will automatically attempt to re-authenticate and retry the request according to the configured retry settings.

Parameters:
  • url – The URL to send the GET request to.

  • headers – Optional additional headers to include in the request.

Returns:

The response object on success.

Raises:
get_unifi_site(include_health, raw=True)[source]

Get information about Unifi sites.

Fetches site data from either /api/stat/sites (with health) or /api/self/sites (without health) based on the include_health flag. This interacts with undocumented private API endpoints, and the response structure may vary between controller versions.

Parameters:
  • include_health (bool) – If True, includes detailed health metrics for each site. Requires potentially more controller resources.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to UnifiSite dataclass objects.

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API. If raw=False, returns a List[UnifiSite] where known fields from the API response are mapped to the dataclass attributes. Undocumented or new fields are captured in the _extra_fields attribute (a Dict[str, Any]) on each UnifiSite instance.

Return type:

Union[List[Dict[str, Any]], List[UnifiSite]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

Note

The specific health metrics included when include_health=True may vary between controller versions.

get_unifi_site_device(site_name, detailed=False, raw=True, mac=None)[source]

Get information about devices on a specific Unifi site.

Fetches device data from the controller using either /api/s/{site_name}/stat/device (detailed) or /api/s/{site_name}/stat/device-basic (basic). Can optionally filter by one or more MAC addresses. This interacts with undocumented private API endpoints, and the response structure may vary between controller versions.

Parameters:
  • site_name (str) – The short name (ID) of the site to fetch devices from.

  • detailed (bool) – If True, fetches detailed device information via /api/s/{site_name}/stat/device. If False (default), fetches basic info via /api/s/{site_name}/stat/device-basic.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to UnifiDevice dataclass objects.

  • mac (Optional[Union[str, List[str]]]) – Optional MAC address string or list of MAC strings to filter results by. Defaults to None (no filtering).

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API. If raw=False, returns a List[UnifiDevice] mapping known fields. Undocumented or new fields from the API response are stored in the _extra_fields attribute (a Dict[str, Any]) on each UnifiDevice instance. The model_name field is auto-populated if auto_model_mapping is enabled during client initialization.

Return type:

Union[List[Dict[str, Any]], List[UnifiDevice]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

  • UnifiModelError – If auto_model_mapping is enabled and the device model database cannot be loaded or parsed when raw=False.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

Note

The structure of the returned data can vary between UniFi Controller versions as the underlying API is undocumented. Check raw results or _extra_fields if expecting specific data not present in the dataclass definition.

get_unifi_site_client(site_name, raw=True)[source]

Get information about active clients (stations) on a specific Unifi site.

Uses the /api/s/{site_name}/stat/sta endpoint which typically provides data for currently connected clients, including network details like IP address. This interacts with an undocumented private API endpoint, and the response structure may vary between controller versions.

Parameters:
  • site_name (str) – The short name (ID) of the site to fetch clients from.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to UnifiClient dataclass objects.

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API. If raw=False, returns a List[UnifiClient] mapping known fields. Undocumented or new fields from the API response are stored in the _extra_fields attribute (a Dict[str, Any]) on each UnifiClient instance.

Return type:

Union[List[Dict[str, Any]], List[UnifiClient]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

Note

This endpoint primarily returns active clients. To get historical or offline clients, use methods like get_all_clients_history or get_offline_clients_v2. The specific fields returned can vary between controller versions.

get_unifi_site_event(site_name, history_hours=720, start_index=0, limit=3000, raw=True)[source]

Get event logs for a specific Unifi site.

Retrieves events from the /api/s/{site_name}/stat/event endpoint, which includes device connections/disconnections, configuration changes, etc. This interacts with an undocumented private API endpoint (using POST), and the response structure may vary between controller versions.

Parameters:
  • site_name (str) – The short name (ID) of the site to fetch events from.

  • history_hours (int) – Look back duration in hours. Defaults to 720 (30 days).

  • start_index (int) – Offset for pagination. Defaults to 0.

  • limit (int) – Maximum number of events to return. Defaults to 3000.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to UnifiEvent dataclass objects.

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API. If raw=False, returns a List[UnifiEvent] mapping known fields. Undocumented or new fields from the API response are stored in the _extra_fields attribute (a Dict[str, Any]) on each UnifiEvent instance.

Return type:

Union[List[Dict[str, Any]], List[UnifiEvent]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

Note

The API uses a POST request for this endpoint, even though it’s fetching data. The specific event types and keys available can vary between controller versions.

get_unifi_site_alarm(site_name, archived=None, raw=True)[source]

Get alarm logs for a specific Unifi site.

Retrieves alarms (system alerts, warnings) from /api/s/{site_name}/list/alarm. Can optionally filter by archived status. This interacts with an undocumented private API endpoint, and the response structure may vary between controller versions.

Parameters:
  • site_name (str) – The short name (ID) of the site to fetch alarms from.

  • archived (Optional[bool]) – Filter by archived status: - None (default): Return all alarms. - False: Return only active (unarchived) alarms. - True: Return only archived alarms.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to UnifiAlarm dataclass objects.

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API. If raw=False, returns a List[UnifiAlarm] mapping known fields. Undocumented or new fields from the API response are stored in the _extra_fields attribute (a Dict[str, Any]) on each UnifiAlarm instance.

Return type:

Union[List[Dict[str, Any]], List[UnifiAlarm]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

get_unifi_site_wlanconf(site_name, wlan_id=None, raw=True)[source]

Get WLAN configurations for a specific Unifi site.

Retrieves WLAN (Wireless Network) settings from /api/s/{site_name}/rest/wlanconf. Can optionally fetch a single WLAN configuration by its ID. This interacts with an undocumented private API endpoint, and the response structure may vary between controller versions.

Parameters:
  • site_name (str) – The short name (ID) of the site to fetch WLAN configurations from.

  • wlan_id (Optional[str]) – The _id of a specific WLAN to fetch. If None (default), fetches all WLANs for the site.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to UnifiWlanConf dataclass objects.

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API. If raw=False, returns a List[UnifiWlanConf] mapping known fields. Undocumented or new fields from the API response are stored in the _extra_fields attribute (a Dict[str, Any]) on each UnifiWlanConf instance.

Return type:

Union[List[Dict[str, Any]], List[UnifiWlanConf]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

get_unifi_site_rogueap(site_name, within_hours=24, raw=True)[source]

Get neighboring APs (often termed “rogue” APs) detected by UniFi APs on a specific site.

Retrieves data from /api/s/{site_name}/stat/rogueap. This interacts with an undocumented private API endpoint (using POST), and the response structure may vary between controller versions.

Parameters:
  • site_name (str) – The short name (ID) of the site to fetch neighboring APs from.

  • within_hours (int) – Look back duration in hours for discovered APs. Defaults to 24.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to UnifiRogueAp dataclass objects.

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API. If raw=False, returns a List[UnifiRogueAp] mapping known fields. Undocumented or new fields from the API response are stored in the _extra_fields attribute (a Dict[str, Any]) on each UnifiRogueAp instance.

Return type:

Union[List[Dict[str, Any]], List[UnifiRogueAp]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

Note

The API uses a POST request for this endpoint. To see APs explicitly marked as ‘known rogue’, use get_known_rogueaps().

get_unifi_site_networkconf(site_name, network_id=None, raw=True)[source]

Get network configurations (LANs, VLANs, VPNs, etc.) for a specific Unifi site.

Retrieves network settings from /api/s/{site_name}/rest/networkconf. Can optionally fetch a single network configuration by its ID. This interacts with an undocumented private API endpoint, and the response structure may vary between controller versions.

Parameters:
  • site_name (str) – The short name (ID) of the site to fetch network configurations from.

  • network_id (Optional[str]) – The _id of a specific network to fetch. If None (default), fetches all networks for the site.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to UnifiNetworkConf dataclass objects.

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API. If raw=False, returns a List[UnifiNetworkConf] mapping known fields. Undocumented or new fields from the API response are stored in the _extra_fields attribute (a Dict[str, Any]) on each UnifiNetworkConf instance.

Return type:

Union[List[Dict[str, Any]], List[UnifiNetworkConf]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

normalize_mac(mac_address)[source]

Normalize MAC address to colon-separated format.

Parameters:

mac_address – MAC address string in any format (with or without separators).

Returns:

MAC address with colons between each pair of characters.

Return type:

str

load_device_models(force_reload=False)[source]

Load the device models database from a JSON file.

Parameters:

force_reload – Whether to force reload the device models database. Defaults to False.

Returns:

The device models database.

Return type:

dict

Raises:

UnifiModelError – If the device models database cannot be loaded.

generate_device_report(sites, output_csv_path, device_models_json_path=None, fields=None)[source]

Generate a CSV report of devices across multiple sites.

Parameters:
  • sites – List of sites to include in the report.

  • output_csv_path – Path where the CSV report will be saved.

  • device_models_json_path – Path to the JSON file with device model information. If None, uses the default path. Defaults to None.

  • fields – List of fields to include in the report. If None, uses DEFAULT_REPORT_FIELDS. Defaults to None.

Raises:
devices_report(sites, device_models_json_path=None)[source]

Generate a detailed device report across multiple sites.

This method provides comprehensive information about all devices across the specified sites.

Parameters:
  • sites (Union[List[UnifiSite], List[Dict[str, Any]]]) – List of sites to include in the report. Can be UnifiSite objects or raw dicts.

  • device_models_json_path – Path to the JSON file with device model information. If None, uses the default path. Defaults to None.

Returns:

A list of UnifiDevice objects with enhanced model information.

Return type:

list

Raises:
get_unifi_site_health(site_name, raw=True)[source]

Get detailed health information for a specific UniFi site.

Uses the /api/s/{site_name}/stat/health endpoint which provides subsystem-level health data in a more lightweight format than the full site data. This interacts with an undocumented private API endpoint, and the response structure may vary between controller versions.

Parameters:
  • site_name (str) – The name of the site to fetch health data for.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to a UnifiHealth object.

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API, where each dictionary represents a subsystem. If raw=False, returns a UnifiHealth object containing a dictionary of UnifiSubsystemHealth objects keyed by subsystem name. Undocumented or new fields from the API response are stored in the _extra_fields attribute (a Dict[str, Any]) on each UnifiSubsystemHealth instance within the subsystems dictionary.

Return type:

Union[List[Dict[str, Any]], UnifiHealth]

Raises:
get_unifi_site_portconf(site_name, raw=True)[source]

Get port profile configurations for a specific UniFi site.

Retrieves port profiles (switch port settings templates) from /api/s/{site_name}/rest/portconf. These profiles define settings like operation mode, PoE, VLANs, STP, LLDP, etc., that can be applied to ports. This interacts with an undocumented private API endpoint, and the response structure may vary between controller versions.

Parameters:
  • site_name (str) – The short name (ID) of the site to fetch port profiles from.

  • raw (bool) – If True (default), returns the raw API response as a list of dictionaries. If False, attempts to map the response to UnifiPortConf dataclass objects.

Returns:

If raw=True (default), returns a List[Dict[str, Any]] representing the direct JSON response data from the API. If raw=False, returns a List[UnifiPortConf] mapping known fields. Undocumented or new fields from the API response are stored in the _extra_fields attribute (a Dict[str, Any]) on each UnifiPortConf instance.

Return type:

Union[List[Dict[str, Any]], List[UnifiPortConf]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

authorize_client_guest(site_name, mac, minutes, up_kbps=None, down_kbps=None, megabytes=None, ap_mac=None)[source]

Authorize a client device (guest) using the /cmd/stamgr endpoint.

Issues a command to grant network access to a guest client for a specified duration, optionally with bandwidth or data usage limits. This method interacts with an undocumented private API endpoint /api/s/{site_name}/cmd/stamgr.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Client MAC address to authorize.

  • minutes (int) – Duration in minutes until authorization expires.

  • up_kbps (Optional[int]) – Optional upload speed limit in Kbps.

  • down_kbps (Optional[int]) – Optional download speed limit in Kbps.

  • megabytes (Optional[int]) – Optional data transfer limit in Megabytes (MB). The API parameter name is ‘bytes’, but expects MB value.

  • ap_mac (Optional[str]) – Optional MAC address of the AP the client is connected to. Providing this might speed up authorization propagation.

Returns:

Raw API response data as a list of dictionaries.

The structure may vary between controller versions. Typically contains details of the authorized client if successful. Check the meta field in the full HTTP response (not directly returned here) for definitive success/failure confirmation.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

unauthorize_client_guest(site_name, mac)[source]

Unauthorize a client device (guest) using the /cmd/stamgr endpoint.

Revokes network access previously granted via guest authorization. This interacts with an undocumented private API endpoint /api/s/{site_name}/cmd/stamgr.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Client MAC address to unauthorize.

Returns:

Raw API response data as a list of dictionaries.

Typically an empty list on success. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

reconnect_client(site_name, mac)[source]

Reconnect (kick) a client device using the /cmd/stamgr endpoint.

Forces a wireless client to disconnect and attempt to reconnect. This interacts with an undocumented private API endpoint /api/s/{site_name}/cmd/stamgr.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Client MAC address to reconnect.

Returns:

Raw API response data as a list of dictionaries.

Typically an empty list on success. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

block_client(site_name, mac)[source]

Block a client device using the /cmd/stamgr endpoint.

Prevents a client device from associating with the network on this site. This interacts with an undocumented private API endpoint /api/s/{site_name}/cmd/stamgr.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Client MAC address to block.

Returns:

Raw API response data as a list of dictionaries.

Often contains the updated client object, reflecting the blocked status. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

unblock_client(site_name, mac)[source]

Unblock a client device using the /cmd/stamgr endpoint.

Removes a block previously placed on a client device for this site. This interacts with an undocumented private API endpoint /api/s/{site_name}/cmd/stamgr.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Client MAC address to unblock.

Returns:

Raw API response data as a list of dictionaries.

Often contains the updated client object. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

forget_client(site_name, macs)[source]

Forget one or more client devices using the /cmd/stamgr endpoint.

This command removes historical data (like connection logs, DPI stats) associated with the specified client(s). This interacts with an undocumented private API endpoint /api/s/{site_name}/cmd/stamgr.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • macs (Union[str, List[str]]) – A single MAC address string or a list of MAC address strings to forget.

Returns:

Raw API response data as a list of dictionaries.

Typically an empty list on success. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

This action is irreversible. It may take some time to complete on controllers with large datasets. Introduced around controller v5.9.X.

create_client_user(site_name, mac, user_group_id, name=None, note=None, is_guest=None, is_wired=None)[source]

Create a new user/client-device entry using the /group/user endpoint.

This method is typically used to define properties for known clients, often before they connect or when they are offline. It pre-populates the client record. This interacts with an undocumented private API endpoint /api/s/{site_name}/group/user.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Client MAC address.

  • user_group_id (str) – _id of the user group the client should belong to. Obtainable via list_user_groups().

  • name (Optional[str]) – Optional name (alias) for the client.

  • note (Optional[str]) – Optional note for the client.

  • is_guest (Optional[bool]) – Optional flag indicating if the client is a guest.

  • is_wired (Optional[bool]) – Optional flag indicating if the client is wired.

Returns:

Raw API response as a list of dictionaries, typically

containing the created client object. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

set_client_note(site_name, client_id, note=None)[source]

Add, modify, or remove a note for a client device using its user ID.

Uses the /upd/user/{client_id} endpoint (typically via POST). This interacts with an undocumented private API endpoint.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • client_id (str) – The _id of the client device (obtainable from client lists like get_all_known_clients or get_unifi_site_client).

  • note (Optional[str]) – The note text. An empty string or None removes the note.

Returns:

Raw API response data as a list of dictionaries, often

containing the updated client object. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

set_client_name(site_name, client_id, name=None)[source]

Set or remove the name (alias) for a client device using its user ID.

Uses the /upd/user/{client_id} endpoint (typically via POST). For the REST equivalent, see set_client_name_rest. This interacts with an undocumented private API endpoint.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • client_id (str) – The _id of the client device.

  • name (Optional[str]) – The name for the client. An empty string or None removes the name.

Returns:

Raw API response data as a list of dictionaries, often

containing the updated client object. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

get_client_details(site_name, mac)[source]

Fetch details for a single client device by MAC address.

Uses the /stat/user/{mac} endpoint. This interacts with an undocumented private API endpoint.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Client MAC address.

Returns:

Raw API response as a list of dictionaries, typically

containing a single client object with details. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

assign_client_to_group(site_name, client_id, group_id)[source]

Assign a client device to a different user group.

Uses the /upd/user/{client_id} endpoint (typically via POST). This interacts with an undocumented private API endpoint.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • client_id (str) – The _id of the client device.

  • group_id (str) – The _id of the target user group. Obtainable via list_user_groups().

Returns:

Raw API response data as a list of dictionaries, often

containing the updated client object. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

set_client_fixed_ip(site_name, client_id, use_fixed_ip, network_id=None, fixed_ip=None)[source]

Enable/disable or modify a client’s fixed IP address using the REST endpoint.

Updates client settings via PUT /api/s/{site_name}/rest/user/{client_id}. This interacts with an undocumented private API endpoint.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • client_id (str) – The _id of the client device.

  • use_fixed_ip (bool) – True to enable and set a fixed IP, False to disable.

  • network_id (Optional[str]) – Required if use_fixed_ip is True. The _id of the network (subnet) for the fixed IP. Obtainable via get_unifi_site_networkconf().

  • fixed_ip (Optional[str]) – Required if use_fixed_ip is True. The desired fixed IP address string (e.g., “192.168.1.100”).

Returns:

Raw API response as a list of dictionaries, typically

containing the updated client object. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • ValueError – If use_fixed_ip is True but network_id or fixed_ip is missing.

  • UnifiAPIError – If the API request fails.

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

set_client_name_rest(site_name, client_id, name)[source]

Update a client device’s name (alias) using the REST endpoint.

Updates client settings via PUT /api/s/{site_name}/rest/user/{client_id}. Use this instead of set_client_name for REST-based updates.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • client_id (str) – The _id of the client device.

  • name (str) – The new name for the client. Cannot be empty.

Returns:

Raw API response as a list of dictionaries, typically

containing the updated client object. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
list_user_groups(site_name)[source]

Fetch user groups configured for the site using the /list/usergroup endpoint.

User groups define bandwidth limits that can be applied to clients. This interacts with an undocumented private API endpoint /api/s/{site_name}/list/usergroup. Response structure may vary between controller versions.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

Raw API response as a list of dictionaries, where each

dictionary represents a user group object. Known keys include: _id (str), name (str), site_id (str), qos_rate_max_down (int, Kbps, -1=unlimited), qos_rate_max_up (int, Kbps, -1=unlimited). Actual structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider using a dataclass like UnifiUserGroup to represent the returned objects for better type safety and clarity in future development.

create_user_group(site_name, name, qos_rate_max_down_kbps=-1, qos_rate_max_up_kbps=-1)[source]

Create a new user group using the REST endpoint /rest/usergroup.

User groups define bandwidth limits that can be applied to clients. This interacts with an undocumented private API endpoint /api/s/{site_name}/rest/usergroup. Response structure may vary between controller versions.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • name (str) – Name for the new user group. Must be unique within the site.

  • qos_rate_max_down_kbps (int) – Download bandwidth limit in Kilobits per second (Kbps). Use -1 for unlimited. Defaults to -1.

  • qos_rate_max_up_kbps (int) – Upload bandwidth limit in Kilobits per second (Kbps). Use -1 for unlimited. Defaults to -1.

Returns:

Raw API response as a list of dictionaries, typically

containing the newly created user group object with its assigned _id. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., name conflict, invalid params, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider using a dataclass like UnifiUserGroup to represent the returned object for better type safety and clarity in future development.

edit_user_group(site_name, group_id, name=None, qos_rate_max_down_kbps=None, qos_rate_max_up_kbps=None)[source]

Modify an existing user group using the REST endpoint PUT /rest/usergroup/{group_id}.

Only provide parameters for the fields you want to change. Unspecified parameters will retain their current values on the controller (unless the API requires all fields on PUT, which might be the case). This interacts with an undocumented private API endpoint. Response structure may vary.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • group_id (str) – The _id of the user group to modify.

  • name (Optional[str]) – New name for the user group. Defaults to None (no change). Must be unique within the site if provided.

  • qos_rate_max_down_kbps (Optional[int]) – New download bandwidth limit in Kbps. Use -1 for unlimited. Defaults to None (no change).

  • qos_rate_max_up_kbps (Optional[int]) – New upload bandwidth limit in Kbps. Use -1 for unlimited. Defaults to None (no change).

Returns:

Raw API response as a list of dictionaries, typically

containing the updated user group object. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., invalid group_id, name conflict, network issue).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider using a dataclass like UnifiUserGroup to represent the returned object for better type safety and clarity in future development. Behaviour when no optional arguments are provided is untested (might be a no-op or error).

delete_user_group(site_name, group_id)[source]

Delete a user group using the REST endpoint DELETE /rest/usergroup/{group_id}.

This interacts with an undocumented private API endpoint. Response structure may vary. You cannot delete the default ‘Automatic’ group. Attempting to delete a group that is currently assigned to clients might fail or have unintended consequences.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • group_id (str) – The _id of the user group to delete.

Returns:

Raw API response as a list of dictionaries, typically

an empty list on success. Structure may vary.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., group not found, deletion forbidden, network issue).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider using a dataclass like UnifiOperationResult or similar to represent the outcome, rather than relying on the raw list structure.

get_site_stats_5minutes(site_name, start_ms=None, end_ms=None, attributes=None)[source]

Fetch 5-minute interval site statistics.

Uses the undocumented endpoint /api/s/{site_name}/stat/report/5minutes.site. Defaults to fetching data for the past 12 hours if start/end times are not specified. Response structure may vary between controller versions. Requires statistics retention to be enabled on the controller for the desired period.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds). Defaults to 12 hours before end_ms.

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds). Defaults to the current time.

  • attributes (Optional[List[str]]) – Optional list of specific attributes to retrieve. If None, defaults are used (similar to PHP client): [‘bytes’, ‘wan-tx_bytes’, ‘wan-rx_bytes’, ‘wlan_bytes’, ‘num_sta’, ‘lan-num_sta’, ‘wlan-num_sta’, ‘time’]. ‘time’ is always included if attributes are specified.

Returns:

Raw API response data as a list of dictionaries, where each

dictionary represents a 5-minute statistics interval. Keys correspond to the requested attributes. The time field is a Unix timestamp in milliseconds. Byte counts are typically cumulative within the interval.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider creating a UnifiSiteStats5Min dataclass to model the response objects.

get_site_stats_hourly(site_name, start_ms=None, end_ms=None, attributes=None)[source]

Fetch hourly interval site statistics.

Uses the undocumented endpoint /api/s/{site_name}/stat/report/hourly.site. Defaults to fetching data for the past 7 days if start/end times are not specified. Response structure may vary between controller versions. Requires statistics retention to be enabled on the controller for the desired period.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds). Defaults to 7 days before end_ms.

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds). Defaults to the current time.

  • attributes (Optional[List[str]]) – Optional list of specific attributes to retrieve. If None, defaults are used (similar to PHP client): [‘bytes’, ‘wan-tx_bytes’, ‘wan-rx_bytes’, ‘wlan_bytes’, ‘num_sta’, ‘lan-num_sta’, ‘wlan-num_sta’, ‘time’]. ‘time’ is always included if attributes are specified.

Returns:

Raw API response data as a list of dictionaries, where each

dictionary represents an hourly statistics interval. Keys correspond to the requested attributes. The time field is a Unix timestamp in milliseconds. Byte counts are typically cumulative within the interval.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider creating a UnifiSiteStatsHourly dataclass to model the response objects.

get_site_stats_daily(site_name, start_ms=None, end_ms=None, attributes=None)[source]

Fetch daily interval site statistics.

Uses the undocumented endpoint /api/s/{site_name}/stat/report/daily.site. Defaults to fetching data for the past 52 weeks if start/end times are not specified. Response structure may vary between controller versions. Requires statistics retention to be enabled on the controller for the desired period.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds). Defaults to 52 weeks before end_ms.

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds). Defaults to the start of the current hour.

  • attributes (Optional[List[str]]) – Optional list of specific attributes to retrieve. If None, defaults are used (similar to PHP client): [‘bytes’, ‘wan-tx_bytes’, ‘wan-rx_bytes’, ‘wlan_bytes’, ‘num_sta’, ‘lan-num_sta’, ‘wlan-num_sta’, ‘time’]. ‘time’ is always included if attributes are specified.

Returns:

Raw API response data as a list of dictionaries, where each

dictionary represents a daily statistics interval. Keys correspond to the requested attributes. The time field is a Unix timestamp in milliseconds. Byte counts are typically cumulative within the interval.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider creating a UnifiSiteStatsDaily dataclass to model the response objects. Default end_ms is the start of the current hour, not current time.

get_site_stats_monthly(site_name, start_ms=None, end_ms=None, attributes=None)[source]

Fetch monthly interval site statistics.

Uses the undocumented endpoint /api/s/{site_name}/stat/report/monthly.site. Defaults to fetching data for the past 52 weeks if start/end times are not specified. Response structure may vary between controller versions. Requires statistics retention to be enabled on the controller for the desired period.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds). Defaults to 52 weeks before end_ms.

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds). Defaults to the start of the current hour.

  • attributes (Optional[List[str]]) – Optional list of specific attributes to retrieve. If None, defaults are used (similar to PHP client): [‘bytes’, ‘wan-tx_bytes’, ‘wan-rx_bytes’, ‘wlan_bytes’, ‘num_sta’, ‘lan-num_sta’, ‘wlan-num_sta’, ‘time’]. ‘time’ is always included if attributes are specified.

Returns:

Raw API response data as a list of dictionaries, where each

dictionary represents a monthly statistics interval. Keys correspond to the requested attributes. The time field is a Unix timestamp in milliseconds. Byte counts are typically cumulative within the interval.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider creating a UnifiSiteStatsMonthly dataclass to model the response objects. Default end_ms is the start of the current hour, not current time. The default time range (52 weeks) might overlap with the daily stats default.

get_aps_stats_5minutes(site_name, start_ms=None, end_ms=None, mac=None, attributes=None)[source]

Fetch 5-minute stats for one or all access points.

Uses the undocumented endpoint /api/s/{site_name}/stat/report/5minutes.ap. Defaults to fetching data for the past 12 hours if start/end times are not specified. Response structure may vary between controller versions. Requires statistics retention to be enabled on the controller for the desired period.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds). Defaults to 12 hours before end_ms.

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds). Defaults to the current time.

  • mac (Optional[str]) – Optional AP MAC address to filter results by. If None, fetches stats for all APs on the site.

  • attributes (Optional[List[str]]) – Optional list of specific attributes to retrieve. If None, defaults to [‘bytes’, ‘num_sta’, ‘time’]. ‘time’ is always included if attributes are specified.

Returns:

Raw API response data as a list of dictionaries, where each

dictionary represents a 5-minute AP statistics interval. Keys include the requested attributes and usually mac. The time field is a Unix timestamp in milliseconds. Byte/client counts are typically cumulative within the interval.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider creating a UnifiApStats5Min dataclass to model the response objects.

get_aps_stats_hourly(site_name, start_ms=None, end_ms=None, mac=None, attributes=None)[source]

Fetch hourly stats for one or all access points.

Uses the undocumented endpoint /api/s/{site_name}/stat/report/hourly.ap. Defaults to fetching data for the past 7 days if start/end times are not specified. Response structure may vary between controller versions. Requires statistics retention to be enabled on the controller for the desired period.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds). Defaults to 7 days before end_ms.

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds). Defaults to the current time.

  • mac (Optional[str]) – Optional AP MAC address to filter results by. If None, fetches stats for all APs on the site.

  • attributes (Optional[List[str]]) – Optional list of specific attributes to retrieve. If None, defaults to [‘bytes’, ‘num_sta’, ‘time’]. ‘time’ is always included if attributes are specified.

Returns:

Raw API response data as a list of dictionaries, where each

dictionary represents an hourly AP statistics interval. Keys include the requested attributes and usually mac. The time field is a Unix timestamp in milliseconds. Byte/client counts are typically cumulative within the interval.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider creating a UnifiApStatsHourly dataclass to model the response objects.

get_aps_stats_daily(site_name, start_ms=None, end_ms=None, mac=None, attributes=None)[source]

Fetch daily stats for one or all access points.

Uses the undocumented endpoint /api/s/{site_name}/stat/report/daily.ap. Defaults to fetching data for the past 52 weeks if start/end times are not specified. Response structure may vary between controller versions. Requires statistics retention to be enabled on the controller for the desired period.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds). Defaults to 52 weeks before end_ms.

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds). Defaults to the start of the current hour.

  • mac (Optional[str]) – Optional AP MAC address to filter results by. If None, fetches stats for all APs on the site.

  • attributes (Optional[List[str]]) – Optional list of specific attributes to retrieve. If None, defaults to [‘bytes’, ‘num_sta’, ‘time’]. ‘time’ is always included if attributes are specified.

Returns:

Raw API response data as a list of dictionaries, where each

dictionary represents a daily AP statistics interval. Keys include the requested attributes and usually mac. The time field is a Unix timestamp in milliseconds. Byte/client counts are typically cumulative within the interval.

Return type:

List[Dict[str, Any]]

Raises:
  • UnifiAPIError – If the API request fails (e.g., network issue, 4xx/5xx error).

  • UnifiAuthenticationError – If authentication or re-authentication fails.

  • UnifiDataError – If the API response cannot be parsed as valid JSON or lacks the expected ‘data’ field.

Note

Consider creating a UnifiApStatsDaily dataclass to model the response objects. Default end_ms is the start of the current hour. The PHP library comment indicated default time range was 7 days, but the code used 52 weeks; this implementation follows the 52-week default for daily AP stats, matching site daily stats.

get_client_stats_daily(site_name, mac=None, start_ms=None, end_ms=None, attributes=None)[source]

Fetch daily stats for a specific client device (or potentially all if mac is None). Defaults to the past 7 days if start/end are not specified (matching PHP lib). Requires enabling “Clients Historical Data” in controller settings.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (Optional[str]) – Optional client MAC address.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds).

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds).

  • attributes (Optional[List[str]]) – Optional list of specific attributes. Defaults: [‘rx_bytes’, ‘tx_bytes’, ‘time’].

Returns:

A list of daily client stat objects.

Return type:

Raw API response

get_client_stats_monthly(site_name, mac=None, start_ms=None, end_ms=None, attributes=None)[source]

Fetch monthly stats for a specific client device (or potentially all if mac is None). Defaults to the past 13 weeks if start/end are not specified. Requires enabling “Clients Historical Data” in controller settings.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (Optional[str]) – Optional client MAC address.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds).

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds).

  • attributes (Optional[List[str]]) – Optional list of specific attributes. Defaults: [‘rx_bytes’, ‘tx_bytes’, ‘time’].

Returns:

A list of monthly client stat objects.

Return type:

Raw API response

get_gateway_stats_5minutes(site_name, start_ms=None, end_ms=None, attributes=None)[source]

Fetch 5-minute interval gateway statistics. Requires a UniFi gateway device on the site. Defaults to the past 12 hours if start/end are not specified.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds).

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds).

  • attributes (Optional[List[str]]) – Optional list of specific attributes. Defaults: [‘time’, ‘mem’, ‘cpu’, ‘loadavg_5’].

Returns:

A list of 5-minute gateway stat objects.

Return type:

Raw API response

get_gateway_stats_hourly(site_name, start_ms=None, end_ms=None, attributes=None)[source]

Fetch hourly interval gateway statistics. Requires a UniFi gateway device on the site. Defaults to the past 7 days if start/end are not specified.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds).

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds).

  • attributes (Optional[List[str]]) – Optional list of specific attributes. Defaults: [‘time’, ‘mem’, ‘cpu’, ‘loadavg_5’].

Returns:

A list of hourly gateway stat objects.

Return type:

Raw API response

get_gateway_stats_daily(site_name, start_ms=None, end_ms=None, attributes=None)[source]

Fetch daily interval gateway statistics. Requires a UniFi gateway device on the site. Defaults to the past 52 weeks if start/end are not specified.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds).

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds).

  • attributes (Optional[List[str]]) – Optional list of specific attributes. Defaults: [‘time’, ‘mem’, ‘cpu’, ‘loadavg_5’].

Returns:

A list of daily gateway stat objects.

Return type:

Raw API response

get_gateway_stats_monthly(site_name, start_ms=None, end_ms=None, attributes=None)[source]

Fetch monthly interval gateway statistics. Requires a UniFi gateway device on the site. Defaults to the past 52 weeks if start/end are not specified.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds).

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds).

  • attributes (Optional[List[str]]) – Optional list of specific attributes. Defaults: [‘time’, ‘mem’, ‘cpu’, ‘loadavg_5’].

Returns:

A list of monthly gateway stat objects.

Return type:

Raw API response

get_speedtest_results(site_name, start_ms=None, end_ms=None)[source]

Fetch speed test results. Requires a UniFi gateway device on the site. Defaults to the past 24 hours if start/end are not specified.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds).

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds).

Returns:

A list of speed test result objects.

Return type:

Raw API response

get_ips_events(site_name, start_ms=None, end_ms=None, limit=10000)[source]

Fetch IPS/IDS threat events. Requires a UniFi gateway device with IPS/IDS enabled. Defaults to the past 24 hours if start/end are not specified.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_ms (Optional[int]) – Optional start time (Unix timestamp in milliseconds).

  • end_ms (Optional[int]) – Optional end time (Unix timestamp in milliseconds).

  • limit (int) – Maximum number of events to return (default 10000).

Returns:

A list of IPS event objects.

Return type:

Raw API response

get_client_sessions(site_name, start_s=None, end_s=None, mac=None, client_type='all')[source]

Fetch client login sessions. Defaults to the past 7 days if start/end are not specified.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_s (Optional[int]) – Optional start time (Unix timestamp in seconds).

  • end_s (Optional[int]) – Optional end time (Unix timestamp in seconds).

  • mac (Optional[str]) – Optional client MAC address to filter by.

  • client_type (str) – Type of client (‘all’, ‘guest’, ‘user’). Default ‘all’.

Returns:

A list of session objects.

Return type:

Raw API response

get_client_sessions_latest(site_name, mac, limit=5)[source]

Fetch the latest ‘n’ login sessions for a specific client device.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Client MAC address (required).

  • limit (int) – Maximum number of sessions to retrieve (default 5).

Returns:

A list of the latest session objects for the client.

Return type:

Raw API response

get_authorizations(site_name, start_s=None, end_s=None)[source]

Fetch client authorizations (e.g., guest portal logins). Defaults to the past 7 days if start/end are not specified.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • start_s (Optional[int]) – Optional start time (Unix timestamp in seconds).

  • end_s (Optional[int]) – Optional end time (Unix timestamp in seconds).

Returns:

A list of authorization objects.

Return type:

Raw API response

get_all_clients_history(site_name, history_hours=8760)[source]

Fetch client devices that connected within a given timeframe (all users). Note: Return stats per client are all-time totals, not just for the timeframe.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • history_hours (int) – Hours to look back for client connections (default 8760).

Returns:

A list of client objects connected within the timeframe.

Return type:

Raw API response

get_guests(site_name, within_hours=8760)[source]

Fetch guest devices with valid access within a given timeframe.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • within_hours (int) – Timeframe in hours to list guests with valid access (default 8760).

Returns:

A list of guest client objects.

Return type:

Raw API response

get_active_clients_v2(site_name, include_traffic_usage=True, include_unifi_devices=True)[source]

Fetch active client devices using the V2 API.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • include_traffic_usage (bool) – Whether to include traffic usage data.

  • include_unifi_devices (bool) – Whether to include UniFi devices in the response.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response from the V2 endpoint.

get_offline_clients_v2(site_name, only_non_blocked=True, include_unifi_devices=True, within_hours=0)[source]

Fetch historical (offline) client devices using the V2 API.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • only_non_blocked (bool) – If True, only include non-blocked clients.

  • include_unifi_devices (bool) – Whether to include UniFi devices.

  • within_hours (int) – Only include devices offline within this many hours (0 = no limit).

Return type:

List[Dict[str, Any]]

Returns:

Raw API response from the V2 endpoint.

get_dashboard_metrics(site_name, use_5min_intervals=False)[source]

Fetch dashboard metrics.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • use_5min_intervals (bool) – If True, request 5-minute interval data (requires controller v5.5+). Defaults to hourly intervals.

Returns:

A list containing dashboard metric objects.

Return type:

Raw API response

get_sysinfo(site_name)[source]

Fetch system information for the site.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list containing system info objects.

Return type:

Raw API response

get_controller_status()[source]

Check the basic status of the controller. Does not require login for non-UniFi OS controllers. For UniFi OS, login might be required depending on configuration.

Return type:

Dict[str, Any]

Returns:

Raw status dictionary from the /status endpoint.

Raises:

UnifiAPIError – If the status endpoint cannot be reached or returns an error.

get_self(site_name)[source]

Fetch information about the currently authenticated user/session.

Parameters:

site_name (str) – The short name (ID) of the site (required for path context).

Returns:

A list containing the self/session info object.

Return type:

Raw API response

get_site_settings(site_name)[source]

Fetch all site settings.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list containing various site setting objects/sections.

Return type:

Raw API response

get_port_forward_stats(site_name)[source]

Fetch port forwarding statistics (e.g., packet/byte counts for rules).

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of port forward stat objects.

Return type:

Raw API response

get_dpi_stats(site_name)[source]

Fetch overall Deep Packet Inspection (DPI) statistics for the site.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of DPI stat objects.

Return type:

Raw API response

get_dpi_stats_filtered(site_name, by='by_cat', category_ids=None)[source]

Fetch DPI statistics, optionally filtered by application or category.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • by (str) – Grouping type: ‘by_cat’ (default) or ‘by_app’.

  • category_ids (Optional[List[int]]) – If by=’by_app’, list of numeric category IDs to filter applications by.

Returns:

A list of filtered DPI stat objects.

Return type:

Raw API response

count_alarms(site_name, archived=None)[source]

Count alarms.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • archived (Optional[bool]) – Filter by archived status: None (all), False (active), True (archived only).

Returns:

Usually a list containing a dictionary like [{‘count’: N}].

Return type:

Raw API response

get_fingerprint_devices_v2(site_name, fingerprint_source=0)[source]

Fetch fingerprints for client devices using the V2 API.

Parameters:
  • site_name (str) – The short name (ID) of the site (used for API context).

  • fingerprint_source (int) – The ID of the fingerprint source (default 0).

Return type:

List[Dict[str, Any]]

Returns:

Raw API response from the V2 endpoint.

get_controller_full_status()[source]

Fetch the full status object from the controller’s /status endpoint. Handles potential differences in login requirements.

Return type:

Dict[str, Any]

Returns:

Raw status dictionary from the /status endpoint.

Raises:
  • UnifiAPIError – If the status endpoint cannot be reached or returns an error.

  • UnifiDataError – If the response cannot be parsed as JSON.

get_device_name_mappings()[source]

Fetch device name/model mappings, typically from bundles.json. Does not usually require login.

Returns:

List of device mapping objects.

Return type:

Raw API response

Raises:
  • UnifiAPIError – If the endpoint cannot be reached or returns an error.

  • UnifiDataError – If the response cannot be parsed as JSON.

get_vouchers(site_name, create_time_s=None)[source]

Fetch hotspot voucher information.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • create_time_s (Optional[int]) – Optional Unix timestamp (seconds) to filter vouchers by creation time.

Returns:

A list of voucher objects.

Return type:

Raw API response

get_payments(site_name, within_hours=None)[source]

Fetch hotspot payment information.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • within_hours (Optional[int]) – Optional number of hours to look back for payments.

Returns:

A list of payment objects.

Return type:

Raw API response

get_current_channels(site_name)[source]

Fetch currently allowed channels for the site (based on country code, etc.).

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of channel information objects.

Return type:

Raw API response

get_country_codes(site_name)[source]

Fetch available country codes (ISO 3166-1 numeric).

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of country code objects.

Return type:

Raw API response

get_port_forwarding_rules(site_name)[source]

Fetch port forwarding rule configurations.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of port forwarding rule objects.

Return type:

Raw API response

get_voip_extensions(site_name)[source]

Fetch configured VoIP extensions.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of VoIP extension objects.

Return type:

Raw API response

get_all_known_clients(site_name)[source]

Fetch all known client devices (including offline) for the site.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of all known client objects.

Return type:

Raw API response

get_device_tags(site_name)[source]

Fetch device tags configured for the site (REST endpoint). Requires controller v5.5+.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of device tag objects.

Return type:

Raw API response

get_auto_backups(site_name)[source]

Fetch list of available automatic controller backups.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of backup file objects.

Return type:

Raw API response

get_site_admins(site_name)[source]

Fetch administrators with access to the specified site.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of admin objects for the site.

Return type:

Raw API response

get_all_admins(site_name)[source]

Fetch all administrator accounts on the controller. Requires appropriate permissions.

Parameters:

site_name (str) – The short name (ID) of a site for API context (path construction).

Returns:

A list of all admin objects.

Return type:

Raw API response

get_wlan_groups(site_name)[source]

Fetch WLAN groups for the site.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of WLAN group objects.

Return type:

Raw API response

get_hotspot_operators(site_name)[source]

Fetch hotspot operators for the site (REST endpoint).

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of hotspot operator objects.

Return type:

Raw API response

get_radius_profiles(site_name)[source]

Fetch RADIUS profiles for the site (REST endpoint). Requires controller v5.5.19+.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of RADIUS profile objects.

Return type:

Raw API response

get_radius_accounts(site_name)[source]

Fetch RADIUS user accounts for the site (REST endpoint). Requires controller v5.5.19+.

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of RADIUS account objects.

Return type:

Raw API response

get_firewall_groups(site_name, group_id=None)[source]

Fetch firewall groups for the site (REST endpoint).

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • group_id (Optional[str]) – Optional _id of a specific group to fetch.

Returns:

A list containing firewall group objects.

If group_id is provided, the list contains only that group.

Return type:

Raw API response

get_firewall_rules(site_name)[source]

Fetch firewall rules for the site (REST endpoint).

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list of firewall rule objects.

Return type:

Raw API response

get_static_routes(site_name, route_id=None)[source]

Fetch static routing configurations for the site (REST endpoint).

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • route_id (Optional[str]) – Optional _id of a specific static route to fetch.

Returns:

A list containing static route objects.

If route_id is provided, the list contains only that route.

Return type:

Raw API response

get_dynamic_dns_config(site_name)[source]

Fetch dynamic DNS configurations for the site (REST endpoint).

Parameters:

site_name (str) – The short name (ID) of the site.

Returns:

A list containing dynamic DNS configuration objects.

Return type:

Raw API response

adopt_device(site_name, macs)[source]

Adopt one or more devices to the current site using the /cmd/devmgr endpoint.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • macs (Union[str, List[str]]) – A single device MAC address string or a list of MAC addresses.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response, typically an empty list on success.

adopt_device_advanced(site_name, mac, device_ip, ssh_username, ssh_password, inform_url, ssh_port=22, ssh_key_verify=True)[source]

Adopt a device using custom SSH credentials and inform URL.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Device MAC address.

  • device_ip (str) – IP address of the device for SSH connection.

  • ssh_username (str) – SSH username for the device.

  • ssh_password (str) – SSH password for the device.

  • inform_url (str) – URL the device should use to inform the controller.

  • ssh_port (int) – SSH port (default 22).

  • ssh_key_verify (bool) – Whether to verify the device’s SSH key (default True).

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

migrate_device(site_name, macs, inform_url)[source]

Initiate migration for one or more devices to a new inform URL.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • macs (Union[str, List[str]]) – A single device MAC address string or a list of MAC addresses.

  • inform_url (str) – The new inform URL for the devices.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

cancel_migrate_device(site_name, macs)[source]

Cancel an ongoing migration for one or more devices.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • macs (Union[str, List[str]]) – A single device MAC address string or a list of MAC addresses.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

restart_device(site_name, macs, reboot_type='soft')[source]

Reboot one or more devices.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • macs (Union[str, List[str]]) – A single device MAC address string or a list of MAC addresses.

  • reboot_type (str) – ‘soft’ (default) requests a device restart. ‘hard’ requests a PoE power cycle (for capable switch ports).

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

Raises:

ValueError – If reboot_type is invalid.

force_provision_device(site_name, macs)[source]

Force provision one or more devices.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • macs (Union[str, List[str]]) – A single device MAC address string or a list of MAC addresses.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

reboot_cloudkey(site_name)[source]

Reboot the UniFi Controller (effective only on Cloud Key / UniFi OS devices).

Parameters:

site_name (str) – The short name (ID) of the site (needed for context).

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

disable_device(site_name, device_id, disable=True)[source]

Disable or enable a device using the REST endpoint. A disabled device is excluded from dashboard counts, LED/WLANs are off. Appears most effective for APs.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • device_id (str) – The _id of the device.

  • disable (bool) – True to disable the device, False to enable (default True).

Return type:

List[Dict[str, Any]]

Returns:

Raw API response, often the updated device object.

set_device_led_override(site_name, device_id, mode)[source]

Override the LED mode for a specific device using the REST endpoint.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • device_id (str) – The _id of the device.

  • mode (str) – LED mode - ‘on’, ‘off’, or ‘default’ (site setting).

Return type:

List[Dict[str, Any]]

Returns:

Raw API response, often the updated device object.

Raises:

ValueError – If mode is invalid.

locate_device(site_name, mac, enable=True)[source]

Enable or disable the flashing locate LED on a device.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – Device MAC address.

  • enable (bool) – True to start flashing, False to stop (default True).

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

set_device_radio_settings(site_name, device_id, radio, channel, ht, tx_power_mode, tx_power)[source]

Update radio settings for a specific device (likely AP) using the /upd/ endpoint. Note: May be deprecated or behave differently on newer controllers.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • device_id (str) – The _id of the device.

  • radio (str) – The radio band to modify (‘ng’, ‘na’).

  • channel (int) – Radio channel.

  • ht (int) – Channel width (HT/VHT value like 20, 40, 80).

  • tx_power_mode (str) – Transmit power mode (‘low’, ‘medium’, ‘high’, ‘auto’).

  • tx_power (int) – Specific transmit power level (integer dBm).

Return type:

List[Dict[str, Any]]

Returns:

Raw API response, potentially the updated device object.

set_device_wlan_group(site_name, device_id, radio_type, group_id)[source]

Assign a device’s radio to a specific WLAN group using the /upd/ endpoint.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • device_id (str) – The _id of the device (typically an AP).

  • radio_type (str) – Radio band (‘ng’ for 2.4GHz, ‘na’ for 5GHz).

  • group_id (str) – The _id of the WLAN group to assign.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response, potentially the updated device object.

Raises:

ValueError – If radio_type is invalid.

set_device_name(site_name, device_id, name)[source]

Rename a device using the /upd/device/ endpoint.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • device_id (str) – The _id of the device.

  • name (str) – The new name for the device.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response, potentially the updated device object.

move_device_to_site(current_site, mac, target_site_id)[source]

Move a device to a different site using the /cmd/sitemgr endpoint.

Parameters:
  • current_site (str) – The short name (ID) of the site the device is currently in.

  • mac (str) – MAC address of the device to move.

  • target_site_id (str) – The _id (string, not name) of the destination site.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

delete_device(site_name, mac)[source]

Delete/remove a device from the specified site using the /cmd/sitemgr endpoint. This typically forgets the device.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • mac (str) – MAC address of the device to delete.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

power_cycle_switch_port(site_name, switch_mac, port_index)[source]

Power-cycle a PoE port on a UniFi switch.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • switch_mac (str) – MAC address of the switch.

  • port_index (int) – The index (number) of the port to cycle.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

start_spectrum_scan(site_name, ap_mac)[source]

Trigger an RF spectrum scan on a specific access point.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • ap_mac (str) – MAC address of the access point.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response.

get_spectrum_scan_state(site_name, ap_mac)[source]

Check the state and results of an RF spectrum scan on an access point.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • ap_mac (str) – MAC address of the access point.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response containing scan state and potentially results.

set_device_settings_base(site_name, device_id, settings_payload)[source]

Update arbitrary device settings using the REST endpoint. Use with caution: payload must match the structure expected by the API for the specific device and settings being changed.

Parameters:
  • site_name (str) – The short name (ID) of the site.

  • device_id (str) – The _id of the device.

  • settings_payload (Dict[str, Any]) – A dictionary containing the settings to update. Structure should match parts of the device object from get_unifi_site_device.

Return type:

List[Dict[str, Any]]

Returns:

Raw API response, potentially the updated device object.

Usage Examples

Connecting to a Controller

from unifi_controller_api import UnifiController

controller = UnifiController(
    host="https://unifi.example.com",
    username="admin",
    password="password"
)

Getting Devices at a Site

# Get all devices at the default site
devices = controller.get_unifi_site_device("default")

# Get a specific device by MAC address
device = controller.get_device_by_mac("default", "00:11:22:33:44:55")

# Print device names
for device in devices:
    print(f"Device: {device.name} ({device.model})")

Getting Clients

# Get all clients at the default site
clients = controller.get_unifi_site_client("default")

# Print client information
for client in clients:
    print(f"Client: {client.name} ({client.ip})")