Skip to main content

UniFi Official API

PyPI version Python 3.11+ License: Apache 2.0 codecov

Async Python library for the official UniFi APIs:

  • UniFi Network API (v10.4.57+)
  • UniFi Protect API (v7.2.105+)
  • UniFi InnerSpace API (v1.3.23+)
  • UniFi Site Manager API (v1.0.0+)
  • UniFi Mobility API (v1.0.0+)
  • UniFi Carrier Fabric API (v1.0.0+)

Features

  • Async-first: Built with aiohttp for efficient non-blocking operations
  • Strict Typing: 100% typed, passing mypy --strict with Pydantic v2 models
  • Full Coverage: Comprehensive support for all 6 official UniFi API suites
  • Dual Connection Support: Works locally with direct device consoles or via api.ui.com cloud integrations
  • Home Assistant & Automation Ready: Designed for clean integration into automation environments

Requirements

Python 3.11 or higher is required.

  • Python 3.11, 3.12, or 3.13
  • UniFi API Key from developer.ui.com or generated locally on your console

Installation

pip install unifi-official-api

Quick Start

1. UniFi Network Client (Local / Cloud)

import asyncio
from unifi_official_api import LocalAuth, ConnectionType
from unifi_official_api.network import UniFiNetworkClient

async def main():
    async with UniFiNetworkClient(
        auth=LocalAuth(api_key="your-local-api-key", verify_ssl=False),
        base_url="https://192.168.1.1",
        connection_type=ConnectionType.LOCAL,
    ) as client:
        sites = await client.sites.get_all()
        devices = await client.devices.get_all(sites[0].id)
        for device in devices:
            print(f"Device: {device.name} ({device.mac})")

asyncio.run(main())

2. UniFi Protect Client (Cameras, Sirens, Chimes, Relays, POS)

import asyncio
from unifi_official_api import LocalAuth, ConnectionType
from unifi_official_api.protect import UniFiProtectClient

async def main():
    async with UniFiProtectClient(
        auth=LocalAuth(api_key="your-local-api-key", verify_ssl=False),
        base_url="https://192.168.1.1",
        connection_type=ConnectionType.LOCAL,
    ) as client:
        cameras = await client.cameras.get_all()
        for cam in cameras:
            print(f"Camera: {cam.display_name}")

asyncio.run(main())

3. UniFi InnerSpace Client (Floor Plans, AP/Switch Placements)

import asyncio
from unifi_official_api import LocalAuth, ConnectionType
from unifi_official_api.innerspace import UniFiInnerSpaceClient

async def main():
    async with UniFiInnerSpaceClient(
        auth=LocalAuth(api_key="your-local-api-key", verify_ssl=False),
        base_url="https://192.168.1.1",
        connection_type=ConnectionType.LOCAL,
    ) as client:
        plans = await client.floor_plans.get_all()
        aps = await client.access_points.get_all()
        print(f"Loaded {len(plans)} floor plans and {len(aps)} placed APs")

asyncio.run(main())

4. UniFi Site Manager Client (Cloud Multi-Site & Telemetry)

import asyncio
from unifi_official_api import ApiKeyAuth
from unifi_official_api.site_manager import UniFiSiteManagerClient

async def main():
    async with UniFiSiteManagerClient(
        auth=ApiKeyAuth(api_key="your-cloud-api-key")
    ) as client:
        hosts = await client.hosts.get_all()
        sites = await client.sites.get_all()
        metrics = await client.isp_metrics.get_metrics("latency", duration="24h")
        print(f"Monitored {len(hosts.data)} consoles across {len(sites.data)} sites")

asyncio.run(main())

5. UniFi Mobility Client (UMR Gateways & Fleets)

import asyncio
from unifi_official_api import ApiKeyAuth
from unifi_official_api.mobility import UniFiMobilityClient

async def main():
    async with UniFiMobilityClient(
        auth=ApiKeyAuth(api_key="your-cloud-api-key")
    ) as client:
        workspaces = await client.workspaces.get_all()
        ws_id = workspaces[0].workspace_id
        devices = await client.devices.get_all(ws_id)
        print(f"Found {len(devices)} mobility gateways")

asyncio.run(main())

6. UniFi Carrier Fabric Client (ISP Subscribers & Plans)

import asyncio
from unifi_official_api import ApiKeyAuth
from unifi_official_api.carrier_fabric import UniFiCarrierFabricClient

async def main():
    async with UniFiCarrierFabricClient(
        auth=ApiKeyAuth(api_key="your-cloud-api-key")
    ) as client:
        subscribers = await client.subscribers.get_all()
        plans = await client.service_plans.get_all()
        print(f"Loaded {len(subscribers.data)} subscribers and {len(plans)} service plans")

asyncio.run(main())

API Coverage Summary

Client / API Endpoints / Resources Covered
UniFiNetworkClient Sites, Devices, Clients, Networks, WiFi/SSIDs, Firewall & Zones, Vouchers, ACL Rules, Switching (LAGs, MC-LAG domains, Switch Stacks), Traffic Matching, Resources (WAN, VPN, RADIUS)
UniFiProtectClient Cameras (Streams, Snapshots, PTZ Presets & Patrols, Talkback), Sirens, Key Fobs, Relays, Speakers, Bridges, Link Stations, Alarm Hubs, Alarm Manager Webhooks, Arm Profiles, Local & Identity Users, POS Transaction Ingestion, Sensors, Lights, Chimes, NVR (read-only), LiveViews, Viewers, Real-time Device & Event WebSockets
UniFiInnerSpaceClient Full Project Data (Shapes, Walls, Attenuation), Floor Plans, Placed Access Points, Placed Switches, Unplaced Inventory, Blueprint Image Assets
UniFiSiteManagerClient Hosts/Consoles, Multi-site Aggregation, Cross-console Devices, ISP Performance Telemetry & Queries, SD-WAN Configs & Health Status, Cloud Connector Arbitrary Proxy
UniFiMobilityClient Workspaces, Workspace Admins, UMR Device Gateways & Location Coordinates, Connected Clients, Remote LAN/DHCP Configuration, Remote Wireless WiFi Configuration
UniFiCarrierFabricClient Subscribers Lifecycle (Create, Update, Suspend, Resume), Gateway Host Attach/Detach, Service Plan Assignment, Bandwidth QoS Service Plans

UniFiProtectClient sends only operations documented in the Protect OpenAPI spec pinned by PROTECT_SPEC_VERSION (7.3.70). A test checks every public Protect method against a vendored copy of that spec.

Error Handling

The library provides specific exceptions for different error types:

from unifi_official_api import (
    UniFiError,
    UniFiAuthenticationError,
    UniFiConnectionError,
    UniFiNotFoundError,
    UniFiRateLimitError,
    UniFiTimeoutError,
)

try:
    devices = await client.devices.get_all(host_id)
except UniFiAuthenticationError:
    print("Invalid API key")
except UniFiConnectionError:
    print("Failed to connect to API")
except UniFiRateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except UniFiNotFoundError:
    print("Resource not found")
except UniFiError as e:
    print(f"API error: {e.message}")

UniFiNotFoundError covers both an HTTP 404 and a successful response (status_code == 200) that holds no record. A record that fails validation raises UniFiResponseError with status_code == 200 and a message naming the failing fields only. Some listings skip such an item instead: a Protect endpoint with a last_result_complete attribute sets it to False, and the Network rule and route listings raise UniFiValidationError instead when called with strict=True. An HTTP error answer, including one to a snapshot or other binary download, raises UniFiAuthenticationError for 401 and 403, and UniFiResponseError or one of its subclasses (UniFiNotFoundError for 404, UniFiRateLimitError for 429) for any other 4xx or 5xx status; UniFiConnectionError and UniFiTimeoutError mean the console could not be reached. ValueError and TypeError are raised only for invalid arguments, before any request is made.

Protect listing completeness

Use the per-request result when a missing record can trigger removal:

result = await client.cameras.get_all_result()
if result.complete:
    reconcile_inventory(result.records)

records is a tuple in response order. skipped counts records that failed validation. shape_valid indicates that the response contained a bare or data-wrapped list. complete requires a valid list shape and zero skipped records, so a complete empty list is distinct from an unusable response. Transport and HTTP failures raise the usual exceptions.

Existing get_all() calls still return lists. Their legacy last_result_complete flag is shared by concurrent calls. Liveview and file listings continue to validate every record.

Shared request budgets

Protect and Mobility clients have independent request budgets by default. Clients on the same event loop that share a server quota can use one budget:

budget = UniFiProtectClient.create_request_budget()
first = UniFiProtectClient(auth, base_url=console_url, request_budget=budget)
second = UniFiProtectClient(auth, base_url=console_url, request_budget=budget)

The budget shares request-start pacing and short 429 cooldowns across those clients. It binds to one application, connection mode, origin and route prefix, including the console identity for remote Protect. The caller must group clients by credential scope. A budget is local to one event loop and process.

Configuration Options

Both clients accept the following configuration options:

from unifi_official_api import LocalAuth, ConnectionType
from unifi_official_api.network import UniFiNetworkClient

# Local connection
client = UniFiNetworkClient(
    auth=LocalAuth(
        api_key="your-local-api-key",
        verify_ssl=False,  # For self-signed certificates
    ),
    base_url="https://192.168.1.1",  # Your device IP
    connection_type=ConnectionType.LOCAL,
    timeout=30,  # Request timeout in seconds
    connect_timeout=10,  # Connection timeout in seconds
)

# Remote/Cloud connection
from unifi_official_api import ApiKeyAuth

client = UniFiNetworkClient(
    auth=ApiKeyAuth(api_key="your-cloud-api-key"),
    connection_type=ConnectionType.REMOTE,
    console_id="your-console-id",  # Required for REMOTE connections
    timeout=30,
    connect_timeout=10,
)

Local Protect Installation

For connecting directly to a local UniFi Protect installation:

from unifi_official_api import LocalAuth
from unifi_official_api.protect import UniFiProtectClient

client = UniFiProtectClient(
    auth=LocalAuth(
        api_key="local-api-key",
        verify_ssl=False,  # Disable SSL verification for self-signed certs
    ),
    base_url="https://192.168.1.1:7443",
)

Development

Read the domain glossary for resource terminology and the architecture decisions for the library's existing design contracts and trade-offs.

Setup

# Clone the repository
git clone https://github.com/tinkerologie/unifi-official-api.git
cd unifi-official-api

# Install development dependencies
pip install -e ".[dev]"

# Install pre-commit hooks (recommended)
pre-commit install

# Run tests
pytest

# Run linting
ruff check src tests

# Run type checking
mypy src

Pre-commit Hooks

This project uses pre-commit hooks to ensure code quality before commits. The hooks automatically run:

  • Ruff - Linting and formatting
  • Mypy - Static type checking
  • Bandit - Security vulnerability scanning
  • Markdownlint - Markdown file linting
  • Codespell - Spell checking
  • Pyupgrade - Python syntax modernization
  • File checks - YAML, TOML, JSON validation, trailing whitespace, etc.

To set up pre-commit hooks:

# Install pre-commit
pip install pre-commit

# Install the git hooks
pre-commit install

# (Optional) Run against all files
pre-commit run --all-files

Once installed, the hooks will automatically run on every commit. If any check fails, the commit will be blocked until you fix the issues.

Running Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=unifi_official_api --cov-report=html

# Run specific test file
pytest tests/network/test_client.py

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details. Earlier releases were MIT licensed; see NOTICE.

Disclaimer

This is an unofficial library. UniFi is a trademark of Ubiquiti Inc. This project is not affiliated with, endorsed by, or sponsored by Ubiquiti Inc.

Metadata

Release files for unifi-official-api 3.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for unifi-official-api 3.1.0
File Size Uploaded Provenance Actions
unifi_official_api-3.1.0.tar.gz 594.6 kB With provenance Details for unifi_official_api-3.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for unifi-official-api 3.1.0
File Interpreter ABI Platform Actions
unifi_official_api-3.1.0-py3-none-any.whl Python 3 none any Details for unifi_official_api-3.1.0-py3-none-any.whl

Total release size: 835.8 kB

Release files / unifi_official_api-3.1.0.tar.gz

Download URL unifi_official_api-3.1.0.tar.gz
Size 594.6 kB
Tags Source
SHA-256 checksum
How to use checksums
dacfeea59235998038b62ea8f91eae9ab5e3cf89a49fd8d9f779045e05227b03
BLAKE2b-256 checksum
How to use checksums
382457a6b955c9512a397e2d7876c4dc6c1f66c00a8efb3ba21f086502440322
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.

Transparency log

Release files / unifi_official_api-3.1.0-py3-none-any.whl

Download URL unifi_official_api-3.1.0-py3-none-any.whl
Size 241.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
45ceeb5b07ad0c36dc75c5e20c59210cc03ea7e44fa8e10cc4f2ec88d6e44ce5
BLAKE2b-256 checksum
How to use checksums
0254719bbbb2764f9ca7bac5590235f8118ff29c388e2d011692044af1cf6154
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.

Transparency log

Security for unifi-official-api 3.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for unifi_official_api-3.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page