### Install and Start Jupyter Notebook Demo Source: https://github.com/drtinkerer/netbird-python-client/blob/main/README.md Instructions to install Jupyter and launch the interactive NetBird client demo notebook. This notebook showcases real-world API resource usage. ```bash # Install Jupyter if you haven't already pip install jupyter # Start the demo notebook jupyter notebook netbird_demo.ipynb ``` -------------------------------- ### Initialize NetBird API Client Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/index.md This is the initial setup required for all examples. Ensure you replace 'your-api-token' with your actual NetBird API token. ```python from netbird import APIClient client = APIClient( host="api.netbird.io", api_token="your-api-token" ) ``` -------------------------------- ### Setup Keys Resource Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/index.md Manage setup keys for peer onboarding. ```APIDOC ## Setup Keys ### Description Peer setup key management. ### Methods - `list()` - `get(key_id)` - `create(key_data)` - `update(key_id, key_data)` - `delete(key_id)` ``` -------------------------------- ### Manage Users and Invites Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Examples for interacting with user and invite resources. Includes getting the current user, creating a service user, and approving a pending user. ```python # Get current user me = client.users.get_current() print(f"Role: {me['role']}") # Create a service user from netbird.models import UserCreate user = client.users.create(UserCreate( email="bot@company.com", name="Bot", is_service_user=True )) # Approve a pending user client.users.approve("user-id") ``` -------------------------------- ### Get a Specific Setup Key Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Retrieve details for a single setup key using its unique identifier. This allows checking key properties like its validity. ```python >>> key = client.setup_keys.get("key-123") >>> print(f"Key: {key['name']} - Valid: {key['valid']}") ``` -------------------------------- ### List All Setup Keys Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Retrieve a list of all available setup keys. This is useful for auditing or managing existing keys. ```python >>> keys = client.setup_keys.list() >>> for key in keys: ... print(f"Key: {key['name']} (Type: {key['type']})") ``` -------------------------------- ### Manage Setup Keys Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/network-management.md Demonstrates listing and creating setup keys, including reusable and one-off types. Requires `SetupKeyCreate` model. ```python from netbird.models import SetupKeyCreate # List setup keys keys = client.setup_keys.list() for key in keys: status = "valid" if key.get('valid') else "invalid" print(f"{key['name']}: {status}, used {key.get('used_times', 0)} times") # Create a reusable key key = client.setup_keys.create(SetupKeyCreate( name="Auto-enrollment", type="reusable", expires_in=86400, # 24 hours usage_limit=100, auto_groups=["default-group"], )) print(f"Key: {key['key']}") # Create a one-off key one_off = client.setup_keys.create(SetupKeyCreate( name="Single Use", type="one-off", expires_in=3600, # 1 hour )) ``` -------------------------------- ### Setup Self-Hosted Instance Source: https://context7.com/drtinkerer/netbird-python-client/llms.txt Perform a one-time setup for a fresh self-hosted NetBird instance, including creating the initial admin user. ```python # One-time setup for a fresh self-hosted instance result = client.instance.setup( email="admin@corp.example.com", password="Str0ngP@ss!", name="Admin User", ) ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/contributing.md Clone your forked repository and install development dependencies including documentation tools. ```bash git clone https://github.com/YOUR-USERNAME/netbird-python-client.git cd netbird-python-client pip install -e ".[dev,docs]" ``` -------------------------------- ### Clone Repository and Setup Environment Source: https://github.com/drtinkerer/netbird-python-client/blob/main/CONTRIBUTING.md Clone the repository and set up a Python virtual environment for development. ```bash git clone https://github.com/your-username/netbird-python-client.git cd netbird-python-client ``` ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate ``` ```bash pip install -e ".[dev]" ``` ```bash pre-commit install ``` ```bash pytest --version mypy --version black --version ``` -------------------------------- ### Setup Keys Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/network-management.md Manages setup keys for device enrollment, including listing, creating reusable or one-off keys, and setting expiration and usage limits. ```APIDOC ## Setup Keys ### Description Manages setup keys for device enrollment, including listing, creating reusable or one-off keys, and setting expiration and usage limits. ### Method ```python from netbird.models import SetupKeyCreate # List setup keys keys = client.setup_keys.list() for key in keys: status = "valid" if key.get('valid') else "invalid" print(f"{key['name']}: {status}, used {key.get('used_times', 0)} times") # Create a reusable key key = client.setup_keys.create(SetupKeyCreate( name="Auto-enrollment", type="reusable", expires_in=86400, # 24 hours usage_limit=100, auto_groups=["default-group"], )) print(f"Key: {key['key']}") # Create a one-off key one_off = client.setup_keys.create(SetupKeyCreate( name="Single Use", type="one-off", expires_in=3600, # 1 hour )) ``` ``` -------------------------------- ### SetupKeys Resource Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Manage NetBird setup keys using the Python client. Supports listing, creating, retrieving, updating, and deleting setup keys. ```APIDOC ## SetupKeys Resource Manages NetBird setup keys. ### Methods - `list()`: List all setup keys. - `create(key_data)`: Create a new setup key with specified data. - `get(key_id)`: Retrieve a specific setup key by its ID. - `update(key_id, key_data)`: Update an existing setup key. - `delete(key_id)`: Delete a specific setup key. ### Example Usage ```python # List all setup keys setup_keys = client.setup_keys.list() # Create a new reusable setup key valid for 24 hours with a usage limit of 10 from netbird.models.setup_key import SetupKeyCreate key_creation_data = SetupKeyCreate(name="Development Key", type="reusable", expires_in=86400, usage_limit=10) new_key = client.setup_keys.create(key_creation_data) # Get a specific setup key specific_key = client.setup_keys.get("key-123") # Update a setup key (e.g., change its name) updated_key = client.setup_keys.update("key-123", {"name": "Updated Key Name"}) # Delete a setup key client.setup_keys.delete("key-123") ``` ``` -------------------------------- ### Install Graphviz and Diagrams Libraries Source: https://github.com/drtinkerer/netbird-python-client/blob/main/README.md Install the necessary libraries for generating diagrams. Graphviz is for high-quality publications, and Diagrams is for code documentation. ```bash # For Graphviz diagrams pip install graphviz # For Python Diagrams pip install diagrams # Mermaid requires no additional dependencies ``` -------------------------------- ### Generate Network Diagram Examples Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/client.md Examples demonstrating the generation of network topology diagrams in different formats. ```python mermaid_content = client.generate_diagram(format="mermaid") client.generate_diagram(format="graphviz", output_file="my_network") client.generate_diagram(format="diagrams") ``` -------------------------------- ### Install NetBird with Documentation Tools Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/installation.md Install NetBird with dependencies required for building and managing project documentation using Sphinx. ```bash pip install netbird[docs] ``` -------------------------------- ### Create Reusable Setup Key Source: https://github.com/drtinkerer/netbird-python-client/blob/main/README.md Generate a reusable setup key with a specified name, type, expiration time, usage limit, and auto-assigned groups. The output includes the key itself and its validity status. ```python from netbird.models import SetupKeyCreate # Create a reusable setup key key_data = SetupKeyCreate( name="Environment Setup", type="reusable", expires_in=86400, # 24 hours usage_limit=10, auto_groups=["default-group"] ) setup_key = client.setup_keys.create(key_data) print(f"Setup key: {setup_key['key']}") print(f"Key valid: {setup_key['valid']}") ``` -------------------------------- ### Setup Key Management Source: https://context7.com/drtinkerer/netbird-python-client/llms.txt Manage peer enrollment keys used for registering new peers. ```APIDOC ## setup_keys — Peer Enrollment Keys `client.setup_keys` manages enrollment keys used to register new peers in the network. ### Methods - `client.setup_keys.list()`: Lists all available setup keys. - `client.setup_keys.create(SetupKeyCreate)`: Creates a new setup key. `SetupKeyCreate` object specifies name, type, expiration, usage limit, auto groups, and ephemeral status. - `client.setup_keys.get(key_id)`: Retrieves a specific setup key by its ID. - `client.setup_keys.update(key_id, SetupKeyUpdate)`: Updates an existing setup key. `SetupKeyUpdate` object can set the `revoked` status. - `client.setup_keys.delete(key_id)`: Deletes a setup key. ### Usage Example ```python from netbird.models import SetupKeyCreate, SetupKeyUpdate # List all keys for key in client.setup_keys.list(): print(f"{key['name']} type={key['type']} valid={key['valid']}") # Create a reusable key valid for 24 h with a usage limit key = client.setup_keys.create(SetupKeyCreate( name="Office-Onboarding", type="reusable", expires_in=86400, usage_limit=50, auto_groups=["grp-office"], ephemeral=False, )) print(f"Key value: {key['key']}") # Get a specific key retrieved = client.setup_keys.get(key["id"]) # Revoke a key client.setup_keys.update(key["id"], SetupKeyUpdate(revoked=True)) # Delete a key client.setup_keys.delete(key["id"]) ``` ``` -------------------------------- ### Setup Instance Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Sets up the NetBird instance with an initial administrator user. Requires email, password, and display name. ```APIDOC ## setup(email, password, name) ### Description Setup the instance with initial admin user. ### Parameters #### Path Parameters - **email** (str) - Required - Email address for the admin user - **password** (str) - Required - Password for the admin user (minimum 8 characters) - **name** (str) - Required - Display name for the admin user ### Returns Setup confirmation dictionary ### Return Type Dict[str, Any] ``` -------------------------------- ### Claude Code CLI Setup for NetBird MCP Source: https://context7.com/drtinkerer/netbird-python-client/llms.txt Instructions for installing NetBird with MCP support and configuring the Claude Code CLI to connect to the NetBird API. Includes commands for adding the service, verifying connectivity, and running the MCP server manually. ```bash # Install with MCP support pip install "netbird[mcp]" # Claude Code CLI setup claude mcp add netbird \ -e NETBIRD_HOST=api.netbird.io \ -e NETBIRD_API_TOKEN=nbp_xxx \ -- netbird-mcp # Verify connectivity claude mcp list # netbird: ... ✓ Connected # Run server manually NETBIRD_HOST=api.netbird.io NETBIRD_API_TOKEN=nbp_xxx netbird-mcp ``` -------------------------------- ### Unit Test Example Source: https://github.com/drtinkerer/netbird-python-client/blob/main/CONTRIBUTING.md Example of a unit test for client initialization and error handling. Requires `pytest`. ```python import pytest from netbird import APIClient from netbird.exceptions import NetBirdAuthenticationError def test_client_initialization(): client = APIClient(host="example.com", api_token="test-token") assert client.host == "example.com" def test_invalid_token_raises_error(): with pytest.raises(NetBirdAuthenticationError): # Test authentication error handling pass ``` -------------------------------- ### Setup Key Management Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Methods for managing NetBird setup keys, including updating and deleting them. ```APIDOC ## update(key_id, key_data) ### Description Update a setup key. ### Parameters #### Path Parameters - **key_id** (str) - Required - Unique setup key identifier - **key_data** (SetupKeyUpdate) - Required - Setup key update data ### Returns Updated setup key dictionary ### Return type Dict[str, Any] ### Example ```pycon >>> key_data = SetupKeyUpdate(revoked=True) >>> key = client.setup_keys.update("key-123", key_data) ``` ``` ```APIDOC ## delete(key_id) ### Description Delete a setup key. ### Parameters #### Path Parameters - **key_id** (str) - Required - Unique setup key identifier ### Example ```pycon >>> client.setup_keys.delete("key-123") ``` ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/contributing.md Install pre-commit hooks to ensure code quality checks are run before committing. ```bash pre-commit install ``` -------------------------------- ### MCP Server — AI Assistant Integration Source: https://context7.com/drtinkerer/netbird-python-client/llms.txt Explains how to set up and use the built-in MCP server to expose NetBird tools to AI assistants like Claude Desktop and Claude Code. Includes installation, CLI setup, and verification steps. ```APIDOC ## MCP Server — AI Assistant Integration The built-in MCP server exposes 25 NetBird tools to AI assistants (Claude Desktop, Claude Code) via the Model Context Protocol. ```bash # Install with MCP support pip install "netbird[mcp]" # Claude Code CLI setup claude mcp add netbird \ -e NETBIRD_HOST=api.netbird.io \ -e NETBIRD_API_TOKEN=nbp_xxx \ -- netbird-mcp # Verify connectivity claude mcp list # netbird: ... ✓ Connected # Run server manually NETBIRD_HOST=api.netbird.io NETBIRD_API_TOKEN=nbp_xxx netbird-mcp ``` ```json // Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json { "mcpServers": { "netbird": { "command": "netbird-mcp", "env": { "NETBIRD_HOST": "api.netbird.io", "NETBIRD_API_TOKEN": "nbp_xxx" } } } } ``` ```python # The MCP server is implemented using FastMCP and reads credentials from env vars. # All 25 tools map directly to APIClient methods. # Example: the 'generate_network_diagram' tool calls client.generate_diagram(format="mermaid") import os from netbird import APIClient from netbird.mcp.server import mcp # FastMCP instance # To introspect available tools programmatically: # tool names: get_account, get_current_user, list_users, # list_peers, get_peer, update_peer, delete_peer, get_peer_accessible_peers, # list_groups, get_group, create_group, update_group, delete_group, # list_policies, create_policy, delete_policy, # list_networks, get_network, # list_setup_keys, create_setup_key, # list_nameservers, get_dns_settings, # list_posture_checks, get_audit_events, # generate_network_diagram ``` ``` -------------------------------- ### SetupKeyType Enumeration Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/models.md Enumeration for setup key types in NetBird. ```APIDOC ### SetupKeyType Enumeration Setup key type enumeration. Values: `reusable`, `one-off` #### REUSABLE `'reusable'` #### ONE_OFF `'one-off'` ``` -------------------------------- ### Create a New Setup Key Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Create a new NetBird setup key with specified properties like name, type, expiration, and usage limit. Requires a SetupKeyCreate object. ```python >>> key_data = SetupKeyCreate( ... name="Development Key", ... type="reusable", ... expires_in=86400, # 24 hours ... usage_limit=10 ... ) >>> key = client.setup_keys.create(key_data) ``` -------------------------------- ### Basic NetBird Client Installation Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/installation.md Install the core NetBird client and its required dependencies using pip. This is the standard method for most users. ```bash pip install netbird ``` -------------------------------- ### Update Setup Key Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Updates an existing setup key by its ID. Requires a SetupKeyUpdate object with the desired changes. ```python >>> key_data = SetupKeyUpdate(revoked=True) >>> key = client.setup_keys.update("key-123", key_data) ``` -------------------------------- ### List NetBird Setup Keys Source: https://github.com/drtinkerer/netbird-python-client/blob/main/netbird_demo.ipynb Retrieves and displays information about existing setup keys. It shows the validity status, usage count, and expiration details for each key. Handles potential API errors during the listing process. ```python try: setup_keys = client.setup_keys.list() print(f"🔑 Found {len(setup_keys)} setup keys:") print() for key in setup_keys: status = "✅ Valid" if key['valid'] and not key['revoked'] else "❌ Invalid" print(f" {status} {key['name']}") print(f" Type: {key['type']}") print(f" Used: {key['used_times']} times") print(f" Limit: {key.get('usage_limit') or 'Unlimited'}") print(f" Expires: {key.get('expires') or 'Never'}") print(f" Last Used: {key.get('last_used') or 'Never'}") if key.get('auto_groups'): print(f" Auto Groups: {len(key['auto_groups'])} groups") print() except NetBirdAPIError as e: print(f"❌ Error listing setup keys: {e}") ``` -------------------------------- ### Install Python Diagrams for Architectural Diagrams Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/installation.md Install the 'diagrams' Python package for creating architectural diagrams. ```bash pip install diagrams ``` -------------------------------- ### Install NetBird with Development Tools Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/installation.md Install NetBird along with a suite of development tools including linters, formatters, and testing frameworks. ```bash pip install netbird[dev] ``` -------------------------------- ### Delete Setup Key Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Deletes a setup key using its unique identifier. This action is irreversible. ```python >>> client.setup_keys.delete("key-123") ``` -------------------------------- ### Installation for Diagram Formats Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/user-guide/network-visualization.md Install necessary dependencies for generating diagrams. Mermaid requires no extra Python dependencies. Graphviz and Python Diagrams require specific pip installations and, for Graphviz, a system package. ```bash # Mermaid - no extra Python dependencies # Render with any Mermaid-compatible tool (GitHub, GitLab, mermaid.live) # Graphviz pip install graphviz brew install graphviz # macOS system package also required # Python Diagrams pip install diagrams ``` -------------------------------- ### Install Graphviz for Network Visualization Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/installation.md Install the Graphviz Python package to generate network topology diagrams in formats like PNG, SVG, and PDF. ```bash pip install graphviz ``` -------------------------------- ### Instance Resource Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/index.md Manage NetBird instance status and setup. ```APIDOC ## Instance ### Description Instance management. ### Methods - `get_status()` - `get_version()` - `setup(setup_data)` ``` -------------------------------- ### Development Installation of NetBird Client Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/installation.md Install the NetBird client in development mode from a Git repository. This is useful for contributing to the project or using the latest unreleased features. ```bash git clone https://github.com/drtinkerer/netbird-python-client.git cd netbird-python-client # Install in development mode with all dependencies pip install -e ".[dev,docs]" ``` -------------------------------- ### Manage Policies Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/network-management.md Examples for listing, creating, and disabling network policies. Requires `PolicyCreate`, `PolicyRule`, and `PolicyUpdate` models. ```python from netbird.models import PolicyCreate, PolicyRule, PolicyUpdate # List policies policies = client.policies.list() for policy in policies: enabled = "enabled" if policy.get('enabled') else "disabled" print(f"{policy['name']} ({enabled})") # Create a policy rule = PolicyRule( name="Allow SSH", action="accept", protocol="tcp", ports=["22"], sources=["source-group-id"], destinations=["dest-group-id"], bidirectional=False, ) policy = client.policies.create(PolicyCreate( name="SSH Access Policy", description="Allow SSH access from dev to prod", rules=[rule], enabled=True, )) # Disable a policy client.policies.update(policy['id'], PolicyUpdate(enabled=False)) ``` -------------------------------- ### Verify NetBird Installation Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/installation.md Verify the NetBird installation by importing the library and printing its version. Ensure the output matches the expected version. ```python import netbird print(netbird.__version__) # Should print "1.3.0" ``` -------------------------------- ### Python Docstring Example Source: https://github.com/drtinkerer/netbird-python-client/blob/main/CONTRIBUTING.md Illustrates the structure and content of docstrings for functions, including arguments, return values, raised exceptions, and usage examples. ```python def create_user(self, user_data: UserCreate) -> User: """Create a new user. Args: user_data: User creation data Returns: Created User object Raises: NetBirdValidationError: If user data is invalid NetBirdAPIError: If creation fails Example: >>> user_data = UserCreate(email="test@example.com", name="Test User") >>> user = client.users.create(user_data) """ ``` -------------------------------- ### Instance Status & Setup Source: https://context7.com/drtinkerer/netbird-python-client/llms.txt Introspects instance metadata and bootstraps a fresh self-hosted deployment. These endpoints do not require authentication. ```APIDOC ## Instance Status & Setup ### Description Introspects instance metadata and bootstraps a fresh self-hosted deployment. These endpoints do not require authentication. ### Methods - `get_status()`: Retrieves the operational status of the NetBird instance. - `get_version()`: Retrieves the software version information of the NetBird instance. - `setup(email, password, name)`: Performs the one-time setup for a fresh self-hosted instance. ### Usage Example ```python # Get operational status status = client.instance.get_status() print(status) # Get software version information version_info = client.instance.get_version() print(f"Server version: {version_info.get('version')}") # One-time setup for a fresh self-hosted instance result = client.instance.setup( email="admin@corp.example.com", password="Str0ngP@ss!", name="Admin User", ) ``` ``` -------------------------------- ### Install NetBird Python Client Source: https://context7.com/drtinkerer/netbird-python-client/llms.txt Install the NetBird Python client using pip. Optional extras for MCP server, documentation build, and development tools can be included. ```bash pip install netbird # Optional extras pip install "netbird[mcp]" # MCP server support pip install "netbird[docs]" # Sphinx documentation build pip install "netbird[dev]" # Development / testing tools ``` -------------------------------- ### Install NetBird with MCP Server Support Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/installation.md Install NetBird with optional dependencies for the Model Context Protocol (MCP) server, enabling integration with AI assistants. ```bash pip install "netbird[mcp]" ``` -------------------------------- ### Token Expiration Examples Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/user-guide/authentication.md Demonstrates creating tokens with different expiration periods. ```APIDOC ## Token Expiration Examples ### Description Demonstrates creating tokens with different expiration periods. ### Method ```python TokenCreate(name: str, expires_in: int) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (str) - Required - The name of the token. - **expires_in** (int) - Required - The number of days until the token expires (1-365). ### Request Example ```python from netbird.models import TokenCreate # Short-lived token for CI/CD ci_token = TokenCreate(name="ci-pipeline", expires_in=1) # 1 day # Long-lived token for service accounts service_token = TokenCreate(name="monitoring", expires_in=365) # 1 year ``` ### Response None ``` -------------------------------- ### Approve or Reject Users Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/user-management.md Lists pending users and provides examples for approving or rejecting them. ```python # List all users and find pending ones users = client.users.list() pending = [u for u in users if u.get('status') == 'invited'] for user in pending: print(f"Pending: {user['name']} ({user['email']})") # Approve the user client.users.approve(user['id']) print(f" Approved!") # Or reject a user # client.users.reject("user-id") ``` -------------------------------- ### SetupKeyUpdate Model Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/models.md Model for updating an existing setup key. Allows modification of revocation status and auto-assigned groups. ```APIDOC ## class netbird.models.setup_key.SetupKeyUpdate Model for updating a setup key. ### Parameters * **revoked** (bool | None) - Optional - Whether the key is revoked * **auto_groups** (List[netbird.models.common.ResourceId] | None) - Optional - Group IDs to auto-assign ``` -------------------------------- ### Pull Request Template Example Source: https://github.com/drtinkerer/netbird-python-client/blob/main/CONTRIBUTING.md A markdown template for creating pull requests, guiding contributors to provide necessary information about their changes, testing, and adherence to guidelines. ```markdown ## Description Brief description of the changes. ## Type of Change - [ ] Bug fix - [ ] New feature - [ ] Documentation update - [ ] Refactoring ## Testing - [ ] Unit tests added/updated - [ ] Integration tests added/updated - [ ] All tests pass ## Checklist - [ ] Code follows style guidelines - [ ] Self-review completed - [ ] Documentation updated - [ ] No breaking changes (or clearly documented) ``` -------------------------------- ### Create Network with Resources Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Demonstrates creating a new network and then listing its resources and routers. This example requires the `NetworkCreate` model from `netbird.models`. ```python # Create network with resources from netbird.models import NetworkCreate network = client.networks.create(NetworkCreate( name="Production", description="Production network" )) # Add resources and routers resources = client.networks.list_resources(network['id']) routers = client.networks.list_routers(network['id']) ``` -------------------------------- ### Install Missing Diagram Dependencies Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/installation.md Install missing dependencies for diagram generation, specifically Graphviz and diagrams. Also includes macOS-specific Graphviz installation via Homebrew. ```bash pip install graphviz diagrams On macOS, Graphviz also requires the system package: brew install graphviz ``` -------------------------------- ### Install NetBird Python Client Development Dependencies Source: https://github.com/drtinkerer/netbird-python-client/blob/main/README.md Install the NetBird Python client and its development dependencies using pip. The `-e` flag installs the package in editable mode. ```bash # Install development dependencies pip install -e ".[dev]" ``` -------------------------------- ### Client Initialization and Basic Usage Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/index.md Demonstrates how to initialize the APIClient and perform basic operations like listing peers and creating groups. ```APIDOC ## Client Initialization and Basic Usage ### Description Initialize the `APIClient` with your host and API token, then use resource methods to interact with the NetBird API. Models are used for input validation. ### Usage Pattern ```python from netbird import APIClient from netbird.models import GroupCreate from netbird.exceptions import NetBirdNotFoundError # 1. Initialize client client = APIClient(host="api.netbird.io", api_token="token") # 2. Use resource methods (returns dictionaries) peers = client.peers.list() # 3. Use models for input validation group_data = GroupCreate(name="Team", peers=["peer-1"]) group = client.groups.create(group_data) # 4. Handle errors try: client.peers.get("bad-id") except NetBirdNotFoundError: pass ``` ``` -------------------------------- ### Manage Peer Enrollment Keys with NetBird Client Source: https://context7.com/drtinkerer/netbird-python-client/llms.txt Demonstrates managing setup keys for peer enrollment, including listing, creating reusable keys with expiration and usage limits, retrieving, revoking, and deleting keys. ```python from netbird.models import SetupKeyCreate, SetupKeyUpdate # List all keys for key in client.setup_keys.list(): print(f"{key['name']} type={key['type']} valid={key['valid']}") ``` ```python # Create a reusable key valid for 24 h with a usage limit key = client.setup_keys.create(SetupKeyCreate( name="Office-Onboarding", type="reusable", expires_in=86400, usage_limit=50, auto_groups=["grp-office"], ephemeral=False, )) print(f"Key value: {key['key']}") ``` ```python # Get a specific key retrieved = client.setup_keys.get(key["id"]) ``` ```python # Revoke a key client.setup_keys.update(key["id"], SetupKeyUpdate(revoked=True)) ``` ```python # Delete a key client.setup_keys.delete(key["id"]) ``` -------------------------------- ### GET Request Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/client.md Make a GET request to a specified API path with optional query parameters. ```APIDOC ## GET Request ### Description Makes a GET request to the NetBird API. ### Method GET ### Parameters * **path** (str) - Required - API endpoint path * **params** (Dict[str, Any] | None) - Optional - Query parameters ### Returns Response data ### Return type Any ### Example ```python response = client.get("/some/path", params={"query": "value"}) ``` ``` -------------------------------- ### Build Documentation Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/contributing.md Build the HTML documentation locally using Sphinx. ```bash cd docs make html # Build HTML docs make livehtml # Live reload during development make linkcheck # Check for broken links ``` -------------------------------- ### Initialize and Use APIClient Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/index.md Demonstrates the basic usage pattern: initializing the APIClient with host and token, listing peers, creating a group using a Pydantic model, and handling potential Not Found errors. ```python from netbird import APIClient from netbird.models import GroupCreate # 1. Initialize client client = APIClient(host="api.netbird.io", api_token="token") # 2. Use resource methods (returns dictionaries) peers = client.peers.list() # 3. Use models for input validation group_data = GroupCreate(name="Team", peers=["peer-1"]) group = client.groups.create(group_data) # 4. Handle errors from netbird.exceptions import NetBirdNotFoundError try: client.peers.get("bad-id") except NetBirdNotFoundError: pass ``` -------------------------------- ### SetupKey Model Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/models.md Represents a NetBird setup key used for onboarding new peers. Includes properties for key identification, type, validity, usage, and associated groups. ```APIDOC ## class netbird.models.setup_key.SetupKey NetBird setup key model. ### Parameters * **id** (netbird.models.common.ResourceId) - Unique setup key identifier * **key** (str) - The actual setup key value * **name** (str) - Setup key name * **expires** (str | None) - Expiration timestamp * **type** ([netbird.models.common.SetupKeyType](#netbird.models.common.SetupKeyType)) - Key type * **valid** (bool) - Whether the key is valid * **revoked** (bool) - Whether the key is revoked * **used_times** (int) - Number of times the key has been used * **last_used** (str | None) - When the key was last used * **state** (str) - Key state * **auto_groups** (List[netbird.models.common.ResourceId] | None) - Auto-assigned group IDs * **updated_at** (str | None) - Last update timestamp * **usage_limit** (int | None) - Usage limit * **ephemeral** (bool) - Whether peers are ephemeral * **allow_extra_dns_labels** (bool | None) - Whether extra DNS labels are allowed ### Model Configuration * **model_config** = {'extra': 'allow', 'populate_by_name': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True} Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict]. ``` -------------------------------- ### Install Graphviz Dependencies Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/diagrams.md Installs the necessary Graphviz dependencies for generating diagrams. Use pip for Python and brew for macOS. ```bash # Install dependencies pip install graphviz brew install graphviz # macOS ``` -------------------------------- ### Integration Test Example Source: https://github.com/drtinkerer/netbird-python-client/blob/main/CONTRIBUTING.md Example of an integration test that requires environment variables for authentication and host. Uses `pytest` fixtures. ```python import os import pytest from netbird import APIClient @pytest.fixture def client(): api_token = os.getenv("NETBIRD_TEST_TOKEN") if not api_token: pytest.skip("NETBIRD_TEST_TOKEN not set") return APIClient(host="api.netbird.io", api_token=api_token) @pytest.mark.integration def test_list_users(client): users = client.users.list() assert isinstance(users, list) ``` -------------------------------- ### Inline vs. Fixture Data Example Source: https://github.com/drtinkerer/netbird-python-client/blob/main/tests/fixtures/README.md Illustrates the difference between using inline test data and loading data from fixture files. Inline data can become verbose with many fields. ```python def test_user(): user_data = { "id": "user-123", "email": "test@example.com", # ... 20 more lines of data } ``` ```python def test_user(): user_data = load_sample_data("user") ``` -------------------------------- ### NetBird MCP Server Initialization and Tool Introspection Source: https://context7.com/drtinkerer/netbird-python-client/llms.txt Demonstrates the basic setup for the MCP server using FastMCP, which reads credentials from environment variables. It also lists the available tools that map directly to APIClient methods. ```python # The MCP server is implemented using FastMCP and reads credentials from env vars. # All 25 tools map directly to APIClient methods. # Example: the 'generate_network_diagram' tool calls client.generate_diagram(format="mermaid") import os from netbird import APIClient from netbird.mcp.server import mcp # FastMCP instance # To introspect available tools programmatically: # tool names: get_account, get_current_user, list_users, # list_peers, get_peer, update_peer, delete_peer, get_peer_accessible_peers, # list_groups, get_group, create_group, update_group, delete_group, # list_policies, create_policy, delete_policy, # list_networks, get_network, # list_setup_keys, create_setup_key, # list_nameservers, get_dns_settings, # list_posture_checks, get_audit_events, # generate_network_diagram ``` -------------------------------- ### Add New YAML Configuration Example Source: https://github.com/drtinkerer/netbird-python-client/blob/main/tests/fixtures/README.md Demonstrates how to add a new YAML configuration file to the `mock_configs` directory. This is for defining new configuration settings. ```yaml # fixtures/mock_configs/new_config.yaml feature_flags: enable_new_feature: true debug_mode: false ``` -------------------------------- ### SetupKeyCreate Model Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/models.md Model for creating a new setup key. It includes fields for name, type, expiration, auto-assigned groups, usage limit, and ephemeral settings. ```APIDOC ## class netbird.models.setup_key.SetupKeyCreate Model for creating a setup key. ### Parameters * **name** (str) - Required - Setup key name * **type** ([netbird.models.common.SetupKeyType]) - Required - Key type (reusable or one-off) * **expires_in** (int) - Required - Expiration time in seconds * **auto_groups** (List[netbird.models.common.ResourceId] | None) - Optional - Group IDs to auto-assign * **usage_limit** (int | None) - Optional - Maximum number of uses * **ephemeral** (bool) - Optional - Whether peers using this key are ephemeral (defaults to False) * **allow_extra_dns_labels** (bool) - Optional - Allow extra DNS labels (defaults to False) ``` -------------------------------- ### Manage DNS Zones Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/network-management.md Provides examples for listing, creating DNS zones, and adding DNS records. Requires `DNSZoneCreate` and `DNSRecordCreate` models. ```python from netbird.models import DNSZoneCreate, DNSRecordCreate # List DNS zones zones = client.dns_zones.list() for zone in zones: print(f"Zone: {zone['name']}") # Create a DNS zone zone = client.dns_zones.create(DNSZoneCreate( name="internal.company.com", )) # Add a record to the zone record = client.dns_zones.create_record(zone['id'], DNSRecordCreate( name="app", type="A", value="10.0.0.1", )) ``` -------------------------------- ### Initialize API Client with Environment Variables Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/user-guide/authentication.md Load NetBird host and API token from environment variables for secure credential management. Ensure NETBIRD_HOST and NETBIRD_API_TOKEN are set. ```python import os from netbird import APIClient client = APIClient( host=os.environ["NETBIRD_HOST"], api_token=os.environ["NETBIRD_API_TOKEN"] ) ``` -------------------------------- ### Initialize CloudResources and EDRResources Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/superpowers/specs/2026-03-21-api-upgrade-design.md Demonstrates the initialization pattern for `CloudResources` and `EDRResources` classes, which utilize lazy loading for nested resources. The `APIClient` reference is passed down to child resources. ```python class CloudResources: def __init__(self, client: "APIClient") -> None: self.client = client self._edr: Optional["EDRResources"] = None @property def edr(self) -> "EDRResources": if self._edr is None: self._edr = EDRResources(self.client) return self._edr class EDRResources: def __init__(self, client: "APIClient") -> None: self.client = client ``` -------------------------------- ### UsersResource - Get Invite Info Method Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/superpowers/specs/2026-03-21-api-upgrade-design.md Adds a method to retrieve information about a user invite using its token via a GET request to `/users/invites/{token}`. ```python get_invite_info(token) ``` -------------------------------- ### Create Users Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/user-management.md Demonstrates creating regular, admin, and service users with specified roles and auto-groups. ```python from netbird.models import UserCreate # Create a regular user user = client.users.create(UserCreate( email="alice@company.com", name="Alice Smith", role="user", auto_groups=["default-group"] )) print(f"Created: {user['name']} ({user['id']})") # Create an admin user admin = client.users.create(UserCreate( email="admin@company.com", name="Admin User", role="admin", )) # Create a service user for automation bot = client.users.create(UserCreate( email="bot@company.com", name="CI/CD Bot", is_service_user=True, role="admin", )) ``` -------------------------------- ### Cloud Resources Management Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/index.md Examples for interacting with NetBird Cloud specific features, including usage statistics, reverse proxy services, and EDR integrations. These examples only work with NetBird Cloud. ```python # These only work with NetBird Cloud (api.netbird.io) # Get usage statistics usage = client.cloud.usage.get() print(f"Active peers: {usage.get('active_peers', 'N/A')}") # List reverse proxy services services = client.cloud.services.list() for svc in services: print(f"Service: {svc['name']}") # Check EDR integrations try: falcon = client.cloud.edr.falcon.get() print(f"Falcon: {falcon}") except Exception: print("Falcon not configured") ``` -------------------------------- ### EventsResource - Get Proxy Events Method Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/superpowers/specs/2026-03-21-api-upgrade-design.md Adds a method to retrieve proxy events using a GET request to `/events/proxy`. Supports various filters for pagination, sorting, searching, and specific event criteria. ```python get_proxy_events(**filters) ``` -------------------------------- ### Create MSP Tenant Subscription Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/superpowers/specs/2026-03-21-api-upgrade-design.md Creates a subscription for an MSP tenant. Requires the tenant ID and a price ID. ```python client.cloud.msp.create_subscription(id="tenant-id", price_id="price_123") ``` -------------------------------- ### Basic API Client Initialization Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/user-guide/authentication.md Initialize the API client with your host and Personal Access Token (PAT). ```APIDOC ## Basic API Client Initialization ### Description Initialize the API client with your host and Personal Access Token (PAT). ### Method ```python APIClient(host: str, api_token: str) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from netbird import APIClient client = APIClient( host="api.netbird.io", api_token="nbp_your_token_here" ) ``` ### Response None ``` -------------------------------- ### List and Create Posture Checks Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/network-management.md Demonstrates how to list existing posture checks and create new ones with specific requirements. ```python checks = client.posture_checks.list() for check in checks: print(f"{check['name']}: {check.get('description', '')}") ``` ```python check = client.posture_checks.create(PostureCheckCreate( name="Minimum OS Version", description="Require minimum OS version", checks={ "os_version_check": { "min_version": "10.0" } } )) ``` -------------------------------- ### Get IDP/SCIM Integration Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/superpowers/specs/2026-03-21-api-upgrade-design.md Retrieves a specific IDP/SCIM integration by its ID. ```python client.cloud.idp_scim.get(id="integration-id") ``` -------------------------------- ### List Connected Peers and Count Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Demonstrates listing all peers and then filtering to count only those that are currently connected. This requires the client to be initialized. ```python # List connected peers peers = client.peers.list() connected = [p for p in peers if p['connected']] print(f"{len(connected)}/{len(peers)} peers connected") ``` -------------------------------- ### Initialize API Client and Create User Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/index.md Initialize the API client with host and token. Use Pydantic models for type-safe input when creating resources like users. Responses are returned as standard Python dictionaries. ```python from netbird import APIClient from netbird.models import UserCreate client = APIClient(host="api.netbird.io", api_token="your-token") # Input: Type-safe Pydantic models user_data = UserCreate(email="john@example.com", name="John Doe") # Output: Standard Python dictionaries user = client.users.create(user_data) print(user['name']) # "John Doe" print(user.get('role')) # Safe access with .get() ``` -------------------------------- ### Get Event Streaming Integration Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/superpowers/specs/2026-03-21-api-upgrade-design.md Retrieves a specific event streaming integration by its ID. ```python client.cloud.event_streaming.get(id="integration-id") ``` -------------------------------- ### Get Current User Information Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/quickstart.md Fetch and display information about the currently logged-in user. ```python user = client.users.get_current() print(f"Logged in as: {user['name']} ({user['email']})") print(f"Role: {user['role']}") ``` -------------------------------- ### API Client Initialization with Environment Variables Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/user-guide/authentication.md Initialize the API client using environment variables for secure credential management. ```APIDOC ## API Client Initialization with Environment Variables ### Description Initialize the API client using environment variables for secure credential management. ### Method ```python APIClient(host: str, api_token: str) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import os from netbird import APIClient client = APIClient( host=os.environ["NETBIRD_HOST"], api_token=os.environ["NETBIRD_API_TOKEN"] ) ``` ### Response None ``` -------------------------------- ### Get Current User Details Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/user-management.md Fetches and prints details of the currently authenticated user. ```python me = client.users.get_current() print(f"Name: {me['name']}") print(f"Email: {me['email']}") print(f"Role: {me['role']}") print(f"Status: {me['status']}") ``` -------------------------------- ### Add New JSON Fixture Example Source: https://github.com/drtinkerer/netbird-python-client/blob/main/tests/fixtures/README.md Shows how to add a new JSON fixture file to the `api_responses` directory using a bash command. This is for creating new API response mocks. ```bash # Create new API response fixture echo '{"id": "route-123", "network": "10.0.0.0/24"}' > fixtures/api_responses/routes.json ``` -------------------------------- ### Configure APIClient Options Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/quickstart.md Initialize the APIClient with optional configuration parameters like timeout and base path. ```python client = APIClient( host="your-netbird-host.com", # Required: NetBird API host api_token="your-token", # Required: API access token timeout=30.0, # Optional: Request timeout (default: 30s) base_path="/api", # Optional: API base path (default: "/api") ) ``` -------------------------------- ### Get Instance Version Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Retrieves the version information for the NetBird instance. This endpoint does not require authentication. ```python client.instance.get_version() ``` -------------------------------- ### Create MSP Tenant Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/superpowers/specs/2026-03-21-api-upgrade-design.md Creates a new MSP tenant. Requires tenant name, domain, and optionally groups. ```python client.cloud.msp.create_tenant(data=MSPTenantCreate(name="Example Tenant", domain="example.com", groups=["group1"])) ``` -------------------------------- ### Initialize NetBird Client with Environment Variables Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/quickstart.md Initialize the APIClient using environment variables for host and API token. Ensure NETBIRD_HOST and NETBIRD_API_TOKEN are set. ```python import os client = APIClient( host=os.environ["NETBIRD_HOST"], api_token=os.environ["NETBIRD_API_TOKEN"] ) ``` -------------------------------- ### Get Instance Status Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Retrieves the current status of the NetBird instance. This endpoint does not require authentication. ```python client.instance.get_status() ``` -------------------------------- ### Get a Specific Route Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Fetch details of a specific network route using its unique identifier. ```python >>> route = client.routes.get("route-123") >>> print(f"Route: {route['network']}") ``` -------------------------------- ### Initialize API Client with Token Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/user-guide/authentication.md Instantiate the API client with your NetBird host and Personal Access Token. ```python from netbird import APIClient client = APIClient( host="api.netbird.io", api_token="nbp_your_token_here" ) ``` -------------------------------- ### Manage Groups Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/examples/network-management.md Provides examples for listing, creating, updating, and deleting groups. Requires `GroupCreate` and `GroupUpdate` models for creation and modification. ```python from netbird.models import GroupCreate, GroupUpdate # List all groups groups = client.groups.list() for group in groups: peers = group.get('peers', []) print(f"{group['name']}: {len(peers)} peers") # Create a group group = client.groups.create(GroupCreate( name="Backend Team", peers=["peer-id-1", "peer-id-2"] )) # Update a group client.groups.update(group['id'], GroupUpdate( name="Backend Engineers", peers=["peer-id-1", "peer-id-2", "peer-id-3"] )) # Delete a group client.groups.delete(group['id']) ``` -------------------------------- ### Get a Specific Policy Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/api/resources.md Retrieve details for a specific network policy using its unique identifier. ```python >>> policy = client.policies.get("policy-123") >>> print(f"Policy: {policy['name']}") ``` -------------------------------- ### Get IDP/SCIM Logs Source: https://github.com/drtinkerer/netbird-python-client/blob/main/docs/superpowers/specs/2026-03-21-api-upgrade-design.md Retrieves the logs for a specific IDP/SCIM integration. Requires the integration ID. ```python client.cloud.idp_scim.get_logs(id="integration-id") ```