UniFi-API-client

Art-of-WiFiMIT活跃维护

用 PHP 封装的 UniFi 控制器 API 客户端,让开发者能直接调用接口管理 Ubiquiti 网络设备,省去自己拼 cURL 请求的麻烦。

A PHP API client class to interact with Ubiquiti's UniFi Controller API

v2.4.0发布于 2026-10-17 12:26 UTC1,351star +2 / 7 天238fork同步于 2026-11-11 05:46 UTC

怎么上手

由 README 提炼,执行前请确认
composer require art-of-wifi/unifi-api-client
require_once 'vendor/autoload.php';
硬件要求按 README 说明

README 未说明;只需能运行 PHP 7.4+ 并启用 php-curl、php-json 的服务器或桌面,且能网络访问 UniFi Network Application(通常 TCP 8443,UniFi OS Server 为 11443,UniFi OS 控制台为 443)

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

用 PHP 类封装 UniFi 控制器 API,让工程师无需手写 cURL 就能管理网络设备

用 PHP 封装的 UniFi 控制器 API 客户端,让开发者能直接调用接口管理 Ubiquiti 网络设备,省去自己拼 cURL 请求的麻烦。

核心能力

  • 提供 list_alarms 等大量 UniFi 端点方法封装
  • 支持 API Key、用户名密码、Site Manager 代理三种认证
  • 内置 custom_api_request 可调用任意 API 端点
  • 抛出命名异常便于精确 try/catch 处理
  • 无外部依赖,仅用 PHP cURL 与 JSON 扩展

容易踩的坑

用户名密码认证必须用本地管理员账号,不能用 UniFi Cloud 账号且不能开启 MFA/2FA;Network Application 11.x 上部分统计与事件方法返回空数组或抛异常,需改用 stat_series、list_aggregated_dashboard 等新方法;Site Manager 代理模式要求控制台固件 >= 5.0.3 且在线连接 UI.com,并会额外增加约 800ms 延迟

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v2.4.0
  1. v2.4.0API client class v2.4.0最新正式版2026-10-17 · 2026-10-17 12:26 UTC

    UniFi API client 2.4.0

    Support for the Network Application 11.x statistics engine, with no changes to existing behaviour.

    Background

    Network Application 11.0 (UniFi OS 6.0 or newer; no longer available for the self-hosted Network Server) moved all time-series statistics to a new engine and removed several legacy endpoints. Statistics history is not migrated: the new store starts at the moment of the 11.x upgrade. On 10.x and older nothing changes.

    New methods

    • get_stats_source() – returns LEGACY (10.x, the stat/report/* endpoints are populated) or MODERN (11.x, use stat_series()). Controllers older than 10.x do not have the endpoint and throw a JsonDecodeException; treat that as LEGACY.
    • list_stat_schemas() – the 28 schemas of the new engine with their keys, value fields and nested groups.
    • stat_series() – time series from the new engine: schema, period (HOUR/DAY 5-minute buckets, WEEK hourly, MONTH 8-hour), end timestamp, optional start timestamp (11.0.89+, mutually exclusive with period), filter in the official API grammar, projection (values(...), nested(...)) and noGaps. Arguments are validated client-side with InvalidArgumentException.
    • list_aggregated_dashboard() – the data behind the Network Application dashboard, the replacement for list_dashboard(). Works on 10.x as well.
    • STAT_SERIES_PERIODS constant.

    Behaviour on Network Application 11.x (documented, methods unchanged)

    • Always return an empty array: stat_5minutes_site() … stat_monthly_gateway() (all 16 interval report methods) and stat_speedtest_results(). Use stat_series().
    • Throw a ControllerErrorException because the endpoint was removed: list_dashboard() (use list_aggregated_dashboard()), list_events() (use get_system_log('all')), stat_ips_events() (use get_system_log('threat-alert')), list_alarms() and count_alarms() (use get_system_log('critical')), check_controller_update() (stat_sysinfo() still reports update_available), and the triggers class of get_system_log().
    • Unaffected: sessions, guests, authorizations, vouchers, devices, clients, health, system log and all configuration endpoints.

    Documentation

    • API reference: new "Statistics" section with the schema list, a mapping from the legacy report methods to the new schemas, usage examples, and notes on every affected method.
    • get_system_log(): all and critical classes and category filtering documented.
    • README: Network Application 11.x section; supported versions now include Network 11.x (11.0.89 confirmed) and UniFi OS 6.x (6.0.13 confirmed).
    • New example examples/stat_series.php showing source detection and switching.

    Compatibility

    PHP 7.4 or newer, unchanged. Verified on PHP 7.4.33 against Network Application 11.0.83 and 11.0.89 (direct and through the Site Manager connector) and 10.6.106.

  2. v2.3.1API client class v2.3.12026-10-06 · 2026-10-06 09:30 UTC
    查看更新说明

    Fixed

    • Site Manager proxy mode: some UniFi OS Servers compress their replies, and the Site Manager connector passes them through without a Content-Encoding header. The client now decompresses these replies itself, which fixes JsonDecodeException: Control character error, possibly incorrectly encoded on such consoles. Direct connections (username/password and API key) are unchanged.
  3. v2.3.0API client class v2.3.02026-10-02 · 2026-10-02 09:11 UTC
    查看更新说明

    The release notes are a bit more more elaborate this time due to the important changes/improvements to the Exception handling logic :wink:

    Typed exceptions for controller errors and argument validation

    This release replaces the last remaining plain \Exception and SPL \InvalidArgumentException throws with typed exceptions, so every error raised by the client can be caught through a single interface and controller error codes can be inspected directly.

    New

    • ControllerErrorException is thrown when the controller accepts a request but returns an error in its response body. This covers the classic API (meta.rc = 'error'), v2 API endpoints (errorCode) and UniFi OS endpoints (code). It extends UnifiApiException and exposes:
      • getApiErrorCode() returns the controller's error code, e.g. api.err.UnknownDevice
      • getResponse() returns the full decoded response object
    • UnifiApiExceptionInterface is a marker interface implemented by every exception the client throws. Catch it to handle all client errors uniformly.
    • UniFi_API\Exceptions\InvalidArgumentException extends PHP's \InvalidArgumentException and implements the interface. It is thrown by set_api_key(), enable_site_manager_proxy(), connect_via_site_manager() and create_dns_record(). Existing catch (\InvalidArgumentException $e) blocks continue to work.
    • getHttpResponseCode() is now available on the UnifiApiException base class. It returns the HTTP status code for cURL and login errors and 0 otherwise.

    Improved

    • Around 200 @throws Exception DocBlocks now read @throws UnifiApiException, which improves IDE and static analysis support.
    • The UniFi OS console methods and fetch_results() now document the specific exceptions they can raise.
    • README.md and API_REFERENCE.md gained a full table of all exceptions and when each is thrown.
    • The list_alarms.php, api_key_auth.php and site_manager_proxy_stats.php examples show the new catch patterns.

    Behaviour change

    Controller-side errors were previously thrown as a plain \Exception. They are now a ControllerErrorException, which is a subclass of both UnifiApiException and \Exception.

    • Code that catches \Exception or \Throwable is not affected.
    • Code that catches UnifiApiException first and relies on controller errors falling through to a later catch (\Exception $e) block will now see them in the UnifiApiException block.
    • Exception messages are unchanged.

    See the Upgrading from previous versions and Exception handling sections of the README for details.

    Testing

    Verified against a classic controller (10.x on port 8443) and a UniFi OS console (UDM-PRO) reached through the Site Manager proxy.

  4. v2.2.1API client class v2.2.12026-07-27 · 2026-07-27 09:37 UTC
    查看更新说明
    • implemented a fix for truncation of Access Point related stats we observed in recent 10.x controller versions. The API output was truncated to only return stats for 10 access points. See the docblocks for example of stat_monthly_aps(), for details.
    • applied minor tweaks and updates to the README.md
  5. v2.2.0API client class v2.2.02026-03-22 · 2026-03-22 13:49 UTC
    查看更新说明
    • Add Site Manager proxy support (major new feature!) 💪

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    UniFi Controller API client class

    License Packagist Version Downloads PHP Version

    A PHP class that provides access to Ubiquiti's UniFi Network Application API.

    This class is used by our API Browser tool, which can be found here.

    The package can be installed manually or by using composer/packagist for easy inclusion in your projects. See the installation instructions below for more details.

    Contents

    Why use this API client?

    • Easy to use: clear docs, comprehensive method coverage, and helpful examples.
    • Broad coverage: exposes many UniFi endpoints not (yet) available in the official APIs.
    • Composer-friendly: installable via Composer and works with modern PHP projects.
    • Lightweight and dependency-free: no external libraries required; uses cURL.
    • Secure: communicates over TLS and supports optional SSL certificate validation.
    • Flexible and extensible: includes custom_api_request() for calling any API endpoint.
    • Robust error handling: throws named Exceptions for precise try/catch handling.
    • Actively maintained: regular updates and compatibility with recent UniFi versions.

    Supported Versions

    SoftwareVersions
    UniFi Network Application/controller5.x, 6.x, 7.x, 8.x, 9.x, 10.x, 11.x (11.0.89 is confirmed)
    UniFi OS3.x, 4.x, 5.x, 6.x (6.0.13 is confirmed)

    Network Application 11.x

    Network Application 11.0 (UniFi OS 6.0+ only, no longer available for the self-hosted Network Server) moved all time-series statistics to a new statistics engine and dropped several legacy endpoints. Existing methods keep working as before on 10.x and older, but on 11.x:

    • the interval report methods (stat_5minutes_site() … stat_monthly_gateway(), stat_speedtest_results()) always return an empty array; use the new stat_series() method instead, with list_stat_schemas() for the available schemas and get_stats_source() to detect which engine a controller uses (LEGACY or MODERN)
    • list_dashboard(), list_events(), stat_ips_events(), list_alarms(), count_alarms() and check_controller_update() throw a ControllerErrorException because the endpoints were removed; use list_aggregated_dashboard() and get_system_log() (classes all, threat-alert, critical) instead
    • sessions, guests, authorizations, vouchers, devices, clients, health and all configuration endpoints are unaffected

    The new methods are documented in the API Reference. Statistics history is not migrated by the controller: the new store starts at the moment of the 11.x upgrade.

    Requirements

    • a server or desktop with:
      • PHP 7.4.0 or higher (use version 1.1.83 for PHP 7.3.x and lower)
      • PHP cURL (php-curl) module enabled
      • PHP JSON (php-json) module enabled (always available on PHP 8.0 and later, but it can be disabled at compile time on PHP 7.4)
      • network connectivity to the UniFi Network Application, either:
        • direct, between this server/desktop and the host and port where the UniFi Network Application is running (usually TCP port 8443, port 11443 for UniFi OS Server, or port 443 for UniFi OS consoles), or
        • through the Site Manager proxy at unifi.ui.com, which only requires outbound HTTPS (TCP port 443) from this server/desktop to the internet; the console itself must be online and connected to UI.com (see Option 3: Site Manager Proxy below)
    • authentication — you need one of the following:

    UniFi OS Support

    Starting from version 1.1.47, this API client also supports UniFi OS-based controllers. These applications/devices/services have been verified to work:

    • UniFi OS Server, announcement here
    • UniFi Dream Router (UDR)
    • UniFi Dream Machine (UDM)
    • UniFi Dream Machine Pro (UDM PRO)
    • UniFi Cloud Key Gen2 (UCK G2), firmware version 2.0.24 or higher
    • UniFi Cloud Key Gen2 Plus (UCK G2 Plus), firmware version 2.0.24 or higher
    • UniFi Express (UX)
    • UniFi Dream Wall (UDW)
    • UniFi Cloud Gateway Ultra (UCG-Ultra)
    • UniFi CloudKey Enterprise (CK-Enterprise)
    • UniFi Enterprise Fortress Gateway (EFG)
    • Official UniFi Hosting, details here
    • HostiFi UniFi Cloud Hosting, details here

    The API Client automatically detects UniFi OS consoles/servers and adjusts URLs and several functions/methods accordingly.

    UniFi OS-based consoles require you to connect using port 443, whereas port 8443 is used for the self-hosted/software-based controllers. When connecting to UniFi OS Server, you are required to use port 11443.

    Remote API access to UniFi OS-based gateways

    When connecting to a UniFi OS-based gateway through the WAN interface, you need to create a specific firewall rule to allow this. See this blog post on the Art of WiFi website for detailed instructions when using the "Classic" firewall:
    https://artofwifi.net/blog/how-to-access-the-unifi-controller-by-wan-ip-or-hostname-on-a-udm-pro

    See this blog post when using the Zone-Based firewall (ZBF):
    https://artofwifi.net/blog/how-to-access-the-unifi-controller-by-wan-ip-or-hostname-on-a-udm-pro-using-zbf

    Upgrading from previous versions

    When upgrading to 2.3.0 or later, please note:

    • errors returned by the controller (e.g. api.err.NoSiteContext) are now thrown as UniFi_API\Exceptions\ControllerErrorException instead of a plain \Exception. Code that catches \Exception keeps working, but code that catches UnifiApiException first and relies on controller errors falling through to a later catch (\Exception $e) block will now see them in the UnifiApiException block
    • set_api_key(), enable_site_manager_proxy(), connect_via_site_manager() and create_dns_record() now throw UniFi_API\Exceptions\InvalidArgumentException, which extends PHP's \InvalidArgumentException, so existing catch (\InvalidArgumentException $e) blocks continue to work
    • see the Exception handling section for details

    When upgrading from a version before 2.0.0, please:

    • change your code to use the new Exceptions that are thrown by the API Client class
    • test the client with your code for any breaking changes
    • make sure you are using Composer to install the API Client because the code is no longer held within a single file
    • see the note here regarding the single file version (1.x.x) of the API client

    Installation

    The preferred installation method is through Composer. Follow these installation instructions if you don't have Composer installed already.

    Once Composer is installed, execute this command from the shell in your project directory:

    composer require art-of-wifi/unifi-api-client
    

    Or manually add the package to your composer.json file:

    {
        "require": {
            "art-of-wifi/unifi-api-client": "^2.0"
        }
    }
    

    Finally, be sure to include the composer autoloader in your code if your framework doesn't already do this for you:

    /**
     * load the class using the composer autoloader
     */
    require_once 'vendor/autoload.php';
    

    Authentication

    The API client supports three authentication methods. Choose the one that fits your setup.

    Option 1: API Key (recommended for UniFi OS)

    API key authentication is stateless — no login/logout flow is needed. This is the simplest way to get started with UniFi OS-based controllers.

    require_once 'vendor/autoload.php';
    
    $unifi_connection = new UniFi_API\Client('', '', 'https://unifi:443', 'default');
    $unifi_connection->set_api_key('your-api-key-here');
    $results = $unifi_connection->list_alarms(); // no login() needed
    

    How to generate an API key:

    1. Open your UniFi OS console in a browser
    2. Navigate to Integrations in the sidebar menu
    3. Click Create New API Key
    4. Copy the generated key — it will not be shown again

    The API key inherits the permissions from the admin user that created it.

    Key points:

    • API keys are only available on UniFi OS-based consoles (UDM, UDR, UCG, UX, UDW, UCG-Ultra, UniFi OS Server, etc.)
    • No login() or logout() calls are needed (calling them is harmless and will be ignored)
    • The client automatically configures itself for UniFi OS when an API key is set

    Option 2: Username/Password

    The traditional authentication method that works with both self-hosted controllers and UniFi OS consoles.

    require_once 'vendor/autoload.php';
    
    $unifi_connection = new UniFi_API\Client(
        $controller_user,
        $controller_password,
        $controller_url,
        $site_id
    );
    
    $login   = $unifi_connection->login();
    $results = $unifi_connection->list_alarms();
    

    Requirements for username/password authentication:

    Option 3: Site Manager Proxy

    If your console is managed through unifi.ui.com and you don't have a direct network path to it, you can route API requests through the Ubiquiti Site Manager cloud proxy. This uses the Site Manager API connector to reach the console via UI.com's cloud infrastructure.

    require_once 'vendor/autoload.php';
    
    $client = UniFi_API\Client::connect_via_site_manager(
        '245A4CA234150000000005F23204000000000638FE970000000061156371:48913759', // console ID
        'your-site-manager-api-key',                                              // Site Manager API key
        'default'                                                                  // site (optional)
    );
    
    // No login() needed — proxy mode is stateless
    $stats = $client->stat_daily_site();
    

    Finding the console ID: The console ID (host ID) is visible in the URL when managing a console via unifi.ui.com:

    https://unifi.ui.com/consoles/{console_id}/network/default/dashboard
    

    Site Manager API key: Generate a Site Manager API key at https://unifi.ui.com under your account settings. This is not the same as a local controller API key generated in the UniFi OS console.

    Requirements:

    • Console firmware version must be >= 5.0.3
    • Console must be online and connected to UI.com
    • For non-organization API keys: limited to the API key owner's consoles only
    • For organization API keys: can access any console within the organization

    You can also enable/disable proxy mode on an existing client instance:

    $client = new UniFi_API\Client('', '', 'https://127.0.0.1', 'default');
    $client->enable_site_manager_proxy($console_id, $site_manager_api_key);
    
    // ... make API calls through the proxy ...
    
    $client->disable_site_manager_proxy();
    // Client must be re-configured (login, set_api_key, etc.) before making direct calls
    

    SSL verification: In proxy mode, all requests go to api.ui.com which has a valid public CA certificate. SSL peer and host verification is automatically enforced.

    Performance note: Proxied requests add ~800ms of latency compared to direct access due to the cloud hop. Use direct access when available. The proxy is best suited for remote/headless deployments where a direct network path does not exist.

    Rate limits: The Site Manager API enforces rate limits (10,000 requests/minute for v1 stable). When exceeded, the API returns HTTP 429 with a Retry-After header.

    When to use which method?

    ScenarioMethod
    Controller is part of a UniFi FabricAPI key (required)
    UniFi OS console (UDM, UDR, UCG, etc.)API key (recommended) or username/password
    UniFi OS ServerAPI key (recommended) or username/password
    Self-hosted Network Application (non-UniFi OS Server)Username/password (API keys are not supported)
    Remote console via UI.com (no direct network path)Site Manager proxy

    Important: When your controller is a member of a UniFi Fabric, username/password authentication is not available. You must use API key authentication. UniFi Fabric uses centralized identity management which does not support local login sessions through the API.

    Migrating from username/password to API keys

    If you have existing code using username/password authentication and want to switch to API keys, the changes are minimal:

    Before (username/password):

    $unifi_connection = new UniFi_API\Client($user, $password, $url, $site_id);
    $unifi_connection->login();
    $results = $unifi_connection->list_alarms();
    $unifi_connection->logout();
    

    After (API key):

    $unifi_connection = new UniFi_API\Client('', '', $url, $site_id);
    $unifi_connection->set_api_key($api_key);
    $results = $unifi_connection->list_alarms();
    

    What changes:

    1. Pass empty strings for the $user and $password constructor parameters
    2. Call set_api_key() instead of login()
    3. Remove logout() calls (or leave them — they will be silently ignored)
    4. In your exception handling, LoginFailedException and LoginRequiredException will no longer occur; you can keep or remove those catch blocks as you prefer
    IMPORTANT NOTES:
    1. In the above example, $site_id is the short site "name" (usually 8 characters long) that is visible in the URL when managing the site in the UniFi Network Controller. For example, with this URL:

      https://<controller IP address or FQDN>:8443/manage/site/jl3z2shm/dashboard

      jl3z2shm is the short site "name" and the value to assign to $site_id.

    2. The 6th optional parameter that is passed to the constructor in the above example (true), enables validation of the controller's SSL certificate, which is otherwise disabled by default. It is highly recommended to enable this feature in production environments where you have a valid SSL cert installed on the UniFi Controller that is associated with the FQDN in the controller_url parameter. This option was added with API client version 1.1.16.

    3. Using an administrator account ($controller_user in the above example) with read-only permissions can limit visibility on certain collection/object properties. See this issue and this issue for an example where the WPA2 password isn't visible for read-only administrator accounts.

    Code Examples:

    More code examples are available in the examples/ directory.

    Exception handling

    The API Client class throws Exceptions for various error conditions instead of using PHP's trigger_error() function. This allows for more granular error handling in your application code.

    All Exceptions thrown by the API Client class implement the UniFi_API\Exceptions\UnifiApiExceptionInterface interface, and all but one extend the UniFi_API\Exceptions\UnifiApiException base class. Catch the interface (or the base class) when you want to handle all client errors uniformly.

    The following Exceptions can be thrown:

    ExceptionThrown when
    ControllerErrorExceptionthe controller returns an error in its response, e.g. api.err.Invalid; see getApiErrorCode()/getResponse()
    ConsoleOfflineExceptionthe console is offline when using the Site Manager proxy (HTTP 408)
    CurlExtensionNotLoadedExceptionthe PHP cURL extension is not loaded
    CurlGeneralErrorExceptioncURL reports an error; see getHttpResponseCode()/getCurlGetinfoResults()
    CurlTimeoutExceptionthe cURL request timed out
    EmailInvalidExceptionan invalid email address is passed to a method
    InvalidArgumentExceptionan invalid argument is passed to a method (extends PHP's \InvalidArgumentException, not UnifiApiException)
    InvalidBaseUrlExceptionthe base URL passed to the constructor is invalid
    InvalidCurlMethodExceptionan unsupported HTTP method is passed to set_curl_method()
    InvalidSiteNameExceptionthe site name is invalid
    JsonDecodeExceptionthe controller response could not be decoded as JSON
    LoginFailedExceptionlogin failed; see getHttpResponseCode()
    LoginRequiredExceptiona method that requires login is called before login()
    MacAddressEmptyExceptionan empty MAC address is passed to a method
    MacAddressInvalidExceptionan invalid MAC address is passed to a method
    MethodDeprecatedExceptiona deprecated method is called
    NotAUnifiOsConsoleExceptiona UniFi OS-only method is called against a classic controller

    Here is an example of how to catch each of the Exceptions individually:

    <?php
    /**
     * PHP API usage example with Exception handling
     */
    use UniFi_API\Exceptions\ConsoleOfflineException;
    use UniFi_API\Exceptions\ControllerErrorException;
    use UniFi_API\Exceptions\CurlExtensionNotLoadedException;
    use UniFi_API\Exceptions\CurlGeneralErrorException;
    use UniFi_API\Exceptions\CurlTimeoutException;
    use UniFi_API\Exceptions\InvalidBaseUrlException;
    use UniFi_API\Exceptions\InvalidSiteNameException;
    use UniFi_API\Exceptions\JsonDecodeException;
    use UniFi_API\Exceptions\LoginFailedException;
    use UniFi_API\Exceptions\LoginRequiredException;
    use UniFi_API\Exceptions\UnifiApiExceptionInterface;
    
    /**
     * load the class using the composer autoloader
     */
    require_once 'vendor/autoload.php';
    
    /**
     * include the config file (place your credentials etc. there if not already present)
     */
    require_once 'config.php';
    
    /**
     * initialize the UniFi API connection class, log in to the controller and request the alarms collection
     * (this example assumes you have already assigned the correct values to the variables in config.php)
     */
    try {
        $unifi_connection = new UniFi_API\Client($controller_user, $controller_password, $controller_url, $site_id, $controller_version, true);
        $login            = $unifi_connection->login();
        $results          = $unifi_connection->list_alarms(); // returns a PHP array containing alarm objects
    } catch (CurlExtensionNotLoadedException $e) {
        echo 'CurlExtensionNotLoadedException: ' . $e->getMessage(). PHP_EOL;
    } catch (InvalidBaseUrlException $e) {
        echo 'InvalidBaseUrlException: ' . $e->getMessage(). PHP_EOL;
    } catch (InvalidSiteNameException $e) {
        echo 'InvalidSiteNameException: ' . $e->getMessage(). PHP_EOL;
    } catch (JsonDecodeException $e) {
        echo 'JsonDecodeException: ' . $e->getMessage(). PHP_EOL;
    } catch (LoginRequiredException $e) {
        echo 'LoginRequiredException: ' . $e->getMessage(). PHP_EOL;
    } catch (ConsoleOfflineException $e) {
        echo 'ConsoleOfflineException: ' . $e->getMessage(). PHP_EOL;
    } catch (CurlGeneralErrorException $e) {
        echo 'CurlGeneralErrorException: ' . $e->getMessage(). PHP_EOL;
    } catch (CurlTimeoutException $e) {
        echo 'CurlTimeoutException: ' . $e->getMessage(). PHP_EOL;
    } catch (LoginFailedException $e) {
        echo 'LoginFailedException: ' . $e->getMessage(). PHP_EOL;
    } catch (ControllerErrorException $e) {
        echo 'ControllerErrorException: ' . $e->getMessage() . ' (' . $e->getApiErrorCode() . ')' . PHP_EOL;
    } catch (UnifiApiExceptionInterface $e) {
        /** catch any other Exceptions thrown by the API client */
        echo 'UniFi API client Exception: ' . $e->getMessage(). PHP_EOL;
    } catch (Exception $e) {
        /** catch any other Exceptions that might be thrown */
        echo 'General Exception: ' . $e->getMessage(). PHP_EOL;
    }
    

    The PHP DocBlocks for most public methods contain @throws UnifiApiException, which covers the Exceptions that the internal request helper can raise (LoginRequiredException, ControllerErrorException, JsonDecodeException, the cURL Exceptions and LoginFailedException). It is recommended to catch specific Exceptions where your application needs to respond differently to them.

    The list_alarms.php example in the examples/ directory is a good starting point to see how you can implement Exception handling.

    Functions/methods supported

    The API Client class currently supports a large and growing number of functions/methods to access the UniFi Controller API. Please refer to the comments/PHP DocBlocks in the source code for more details on each of the functions/methods, their purpose, and their respective parameters.

    If you are using an advanced IDE such as PHPStorm or VS Code, you can use its code completion and other features to explore the available functions/methods thanks to the extensive PHP DocBlocks throughout the code.

    For a quick overview of the available functions/methods, you can also check the API Reference here:
    API Reference

    Need help or have suggestions?

    There is still work to be done to add functionality and further improve the usability of this API Client class, so all suggestions/comments are welcome. Please use the GitHub Issues section or the Ubiquiti Community forums (https://community.ui.com/questions/PHP-client-class-to-access-the-UniFi-controller-API-updates-and-discussion-part-2/a793904e-6023-4a7f-bcae-340db2a03fc1) to share your suggestions and questions.

    IMPORTANT NOTE:

    When encountering issues with the UniFi API using other libraries, cURL or Postman, please do not open an Issue. Such issues will be closed immediately. Please use the Discussions section instead.

    Looking for version 1.x.x?

    With versions 1.x.x of the API client, the entire client was contained within a single file which can be useful in specific cases. This has changed with version 2.0.0 where the code is now split across multiple files and inclusion in your project is managed using composer.

    If you are looking for the version 1.x.x code, you can tell composer to install that version by using the following syntax in your composer.json file:

    {
        "require": {
            "art-of-wifi/unifi-api-client": "^1.1"
        }
    }
    

    Alternatively, you can download the latest 1.x.x code from the releases page.

    Whenever necessary, we will make sure to update the version_1 branch with the latest 1.x.x code.

    Credits

    This API Client class is based on the initial work by the following developers:

    and the API as published by Ubiquiti:

    Contributors

    A big thanks to all the contributors who have helped with this project!

    Contributors

    If you would like to contribute to this project, please open an issue and include your suggestions or code there or else create a pull request.

    About Art of WiFi

    Art of WiFi develops software and tools that enhance the capabilities of UniFi networks. From captive portals and reporting solutions to device search utilities, our goal is to make UniFi deployments more powerful and easier to manage.

    If you're looking for a specific solution or just want to see what else we offer, feel free to explore our website:

    Important Disclaimer

    Many of the functions in this API client class are not officially supported by Ubiquiti and as such, may not be supported in future versions of the UniFi Controller API.