art-of-wifi/unifi-api-client

repository·main·Indexed 23 days ago

https://github.com/art-of-wifi/unifi-api-client

A PHP client class for the Ubiquiti UniFi Network Application API. It supports traditional software controllers, UniFi OS-based consoles (UDM, UDR, UX, etc.), and routing requests through the Ubiquiti Site Manager cloud proxy. The library provides multiple authentication methods, including API keys, username/password, and Site Manager API keys, and is compatible with UniFi Network Application versions 5.x through 10.x and UniFi OS versions 3.x through 5.x.

Tokens
19.7K
Snippets
11
Records
119
Agent score
78%

What's inside unifi-api-client

  1. Choose the correct authentication method

    main

    Use this table to determine the best authentication strategy for your environment:

    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
  2. Authenticate using Username and Password

    main

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

    Requirements:

    • Use a local admin account with local access permissions.
    • Do not use UniFi Cloud accounts.
    • Do not enable MFA/2FA on the account used with this client.
    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();
  3. Migrate from username/password to API keys

    main

    To switch from traditional authentication to API keys, follow these steps:

    1. Pass empty strings for the $user and $password constructor parameters.
    2. Call set_api_key() instead of login().
    3. Remove logout() calls (they will be silently ignored).
    4. You can remove LoginFailedException and LoginRequiredException catch blocks, as they will no longer be thrown.
    // 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();
  4. Set up and run API client examples

    main

    To use the provided examples as a starting point for your own code, follow these steps:

    1. Copy files: Copy an example file from the examples/ directory to your working directory.
    2. Configure credentials: Copy config.template.php to config.php in your working directory. Update config.php with your controller's IP/hostname, port, and credentials.
    3. Adjust paths: Update the require_once() statement in your example file to point to the correct path of either the Composer autoloader (vendor/autoload.php) or the client class itself (src/Client.php).
    4. Execute: Run the script via the PHP CLI.
    $ php list_site_health.php
  5. System requirements for the UniFi API client

    main

    To use this client, your environment must meet the following requirements:

    PHP Requirements

    • PHP Version: 7.4.0 or higher. (Note: If you are using PHP 7.3.x or lower, you must use version 1.1.83 of the client).
    • Modules:
      • php-curl must be enabled.
      • php-json must be enabled.

    Network Connectivity

    You must have direct network connectivity to the UniFi Network Application host and port. Common ports include:

    • 8443: Standard self-hosted/software-based controllers.
    • 11443: UniFi OS Server.
    • 443: UniFi OS consoles (e.g., UDM, UDR, UX).

    Authentication Requirements

    You must provide one of the following:

    1. Username/Password: An admin account with local access permissions. Do not use UniFi Cloud accounts and do not enable MFA/2FA for these accounts.
    2. API Key: Generated in your UniFi OS console or UniFi OS Server.
    3. Site Manager API Key: For routing requests through the Ubiquiti cloud proxy.
  6. Install version 1.x.x via Composer

    main

    If your project requires the legacy single-file version of the API client (v1.x.x), you can specify it in your composer.json file. Note that version 2.0.0 and above are split across multiple files and managed via Composer as the standard.

    {
        "require": {
            "art-of-wifi/unifi-api-client": "^1.1"
        }
    }
  7. Authenticate via Site Manager Proxy

    main

    If your console is managed via unifi.ui.com and you lack a direct network path, you can route requests through the Ubiquiti Site Manager cloud proxy. This mode is stateless and does not require login().

    Requirements:

    • Console firmware version must be >= 5.0.3.
    • Console must be online and connected to UI.com.
    • Console ID: Found in the URL when managing via unifi.ui.com (e.g., https://unifi.ui.com/consoles/{console_id}/...).
    • Site Manager API key: Generated at unifi.ui.com under account settings (distinct from local controller API keys).

    Performance & Limits:

    • Adds ~800ms latency due to the cloud hop.
    • Rate limit: 10,000 requests/minute. Exceeding this returns HTTP 429.
    • SSL verification is automatically enforced for api.ui.com.
    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();
  8. Authenticate using an API Key (recommended for UniFi OS)

    main

    API key authentication is stateless and does not require a login() or logout() flow. This is the simplest method for UniFi OS-based consoles (UDM, UDR, UCG, UX, UDW, etc.). The client automatically configures itself for UniFi OS when an API key is set.

    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 key immediately.

    Note: API keys inherit permissions from the admin user that created them. If your controller is part of a UniFi Fabric, you must use API key authentication; username/password is not supported in that scenario.

    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
  9. Install the UniFi API client via Composer

    main

    The preferred method for installing the unifi-api-client is using Composer. This ensures all dependencies are managed and the autoloader is correctly configured.

    Using the CLI

    Run the following command in your project directory:

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

    Manual configuration

    Alternatively, add the package directly to your composer.json file:

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

    Loading the class

    After installation, ensure you include the Composer autoloader in your PHP script to make the API client class available:

    /**
     * load the class using the composer autoloader
     */
    require_once 'vendor/autoload.php';
  10. Configure authentication for examples

    main

    The examples support two authentication methods via the config.php file:

    • API key authentication: Recommended for UniFi OS-based controllers and required for controllers in a UniFi Fabric. Set the $controllerapikey variable in config.php.
    • Username/password authentication: Used by most other examples. Set the $controlleruser and $controllerpassword variables in config.php.
  11. Set up the site provisioning example

    main

    To use the site provisioning example, you must initialize the configuration files by copying the provided templates. Run the following commands in your terminal from the examples/site_provisioning_example/ directory:

    1. Copy the settings template to create your site settings file: cp settings.template.php settings.php
    2. Copy the configuration template to create your main configuration file: cp config.template.php config.php
  12. Handle authentication and request execution in Client

    main

    The Client class manages the lifecycle of UniFi Controller API requests using cURL. It handles several critical authentication and routing tasks:

    • Automatic Re-authentication: If a request returns an HTTP 401 (Unauthorized) due to an expired cookie or token, the client attempts to re-login once and retry the original request automatically.
    • UniFi OS Routing: The client detects if it is interacting with a UniFi OS controller (indicated by a TOKEN in the cookie) and automatically prefixes paths with /proxy/network when necessary.
    • CSRF Protection: For UniFi OS controllers, the client automatically extracts the csrfToken from the JWT cookie and injects the x-csrf-token header into non-GET requests.
    • Site Manager Proxy Support: When using the Site Manager proxy, the client routes requests through the appropriate connector base URL and uses the X-API-KEY header instead of session cookies.
    • Payload Handling: If a payload is provided, the client automatically converts it to JSON and switches the HTTP method from GET or DELETE to POST to ensure compatibility.