netbird


Namenetbird JSON
Version 1.0.1 PyPI version JSON
download
home_pageNone
SummaryPython client for the NetBird API
upload_time2025-07-28 09:42:44
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseNone
keywords api client mesh netbird networking vpn
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # NetBird Python Client

[![PyPI version](https://badge.fury.io/py/netbird.svg)](https://badge.fury.io/py/netbird)
[![Python Support](https://img.shields.io/pypi/pyversions/netbird.svg)](https://pypi.org/project/netbird/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Python client library for the [NetBird](https://netbird.io) API. Provides complete access to all NetBird API resources with a simple, intuitive interface.

This client follows the same upstream schemas as the official NetBird REST APIs, ensuring full compatibility and consistency with the NetBird ecosystem.

## Features

- ✅ **Complete API Coverage** - All 11 NetBird API resources supported
- ✅ **Upstream Schema Compliance** - Follows official NetBird REST API schemas exactly
- ✅ **Dictionary Responses** - Clean dictionary responses for easy data access
- ✅ **Type Safety** - Pydantic models for input validation, dictionaries for responses
- ✅ **Modern Python** - Built for Python 3.8+ with async support ready
- ✅ **Comprehensive Error Handling** - Detailed exception classes for different error types
- ✅ **High Test Coverage** - 97.56% unit test coverage, 83.29% integration coverage
- ✅ **Extensive Documentation** - Complete API reference and examples
- ✅ **PyPI Ready** - Easy installation and distribution

## Supported Resources

| Resource | Description | Endpoints |
|----------|-------------|-----------|
| **Accounts** | Account management and settings | List, Update, Delete |
| **Users** | User lifecycle management | CRUD + Invite, Current user |
| **Tokens** | API token management | CRUD operations |
| **Peers** | Network peer management | CRUD + Accessible peers |
| **Setup Keys** | Peer setup key management | CRUD operations |
| **Groups** | Peer group management | CRUD operations |
| **Networks** | Network and resource management | CRUD + Resources/Routers |
| **Policies** | Access control policies | CRUD operations |
| **Routes** | Network routing configuration | CRUD operations |
| **DNS** | DNS settings and nameservers | Nameserver groups + Settings |
| **Events** | Audit and traffic events | Audit logs, Network traffic |

## Installation

```bash
pip install netbird
```

## Quick Start

```python
from netbird import APIClient

# Initialize the client
client = APIClient(
    host="api.netbird.io",
    api_token="your-api-token-here"
)

# List all peers
peers = client.peers.list()
print(f"Found {len(peers)} peers")

# Get current user
user = client.users.get_current()
print(f"Logged in as: {user['name']}")

# Create a new group
from netbird.models import GroupCreate
group_data = GroupCreate(
    name="Development Team",
    peers=["peer-1", "peer-2"]
)
group = client.groups.create(group_data)
print(f"Created group: {group['name']}")
```

## Authentication

NetBird uses token-based authentication. You can use either a personal access token or a service user token:

### Personal Access Token (Recommended)
```python
client = APIClient(
    host="api.netbird.io",
    api_token="your-personal-access-token"
)
```

### Service User Token
```python
client = APIClient(
    host="api.netbird.io",
    api_token="your-service-user-token"
)
```

### Self-Hosted NetBird
```python
client = APIClient(
    host="netbird.yourcompany.com:33073",
    api_token="your-token",
    use_ssl=True  # or False for HTTP
)
```

## Examples

### User Management
```python
from netbird.models import UserCreate, UserRole

# Create a new user
user_data = UserCreate(
    email="john@example.com",
    name="John Doe",
    role=UserRole.USER,
    auto_groups=["group-developers"]
)
user = client.users.create(user_data)
print(f"Created user: {user['name']} ({user['email']})")

# Update user role
from netbird.models import UserUpdate
update_data = UserUpdate(role=UserRole.ADMIN)
updated_user = client.users.update(user['id'], update_data)
print(f"Updated user role to: {updated_user['role']}")
```

### Network Management
```python
from netbird.models import NetworkCreate, PolicyCreate, PolicyRule

# Create a network
network_data = NetworkCreate(
    name="Production Network",
    description="Main production environment"
)
network = client.networks.create(network_data)
print(f"Created network: {network['name']}")

# Create access policy
rule = PolicyRule(
    name="Allow SSH",
    action="accept",
    protocol="tcp", 
    ports=["22"],
    sources=["group-admins"],
    destinations=["group-servers"]
)
policy_data = PolicyCreate(
    name="Admin SSH Access",
    rules=[rule]
)
policy = client.policies.create(policy_data)
print(f"Created policy: {policy['name']}")
```

### Setup Key Management
```python
from netbird.models import SetupKeyCreate

# Create a reusable setup key
key_data = SetupKeyCreate(
    name="Development Environment",
    type="reusable",
    expires_in=86400,  # 24 hours
    usage_limit=10,
    auto_groups=["group-dev"]
)
setup_key = client.setup_keys.create(key_data)
print(f"Setup key: {setup_key['key']}")
print(f"Key valid: {setup_key['valid']}")
```

### Event Monitoring
```python
# Get audit events
audit_events = client.events.get_audit_events()
for event in audit_events[-10:]:  # Last 10 events
    print(f"{event['timestamp']}: {event['activity']}")
    if event.get('initiator_name'):
        print(f"  Initiated by: {event['initiator_name']}")

# Get network traffic events (cloud-only)
traffic_events = client.events.get_network_traffic_events(
    protocol="tcp",
    page_size=100
)
for traffic in traffic_events[:5]:
    print(f"Traffic: {traffic['source_ip']} -> {traffic['destination_ip']}")
```

## Error Handling

The client provides specific exception types for different error conditions:

```python
from netbird.exceptions import (
    NetBirdAPIError,
    NetBirdAuthenticationError,
    NetBirdNotFoundError,
    NetBirdRateLimitError,
    NetBirdServerError,
    NetBirdValidationError,
)

try:
    user = client.users.get("invalid-user-id")
except NetBirdNotFoundError:
    print("User not found")
except NetBirdAuthenticationError:
    print("Invalid API token")
except NetBirdRateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except NetBirdAPIError as e:
    print(f"API error: {e.message}")
```

## Configuration Options

```python
client = APIClient(
    host="api.netbird.io",
    api_token="your-token",
    use_ssl=True,           # Use HTTPS (default: True)
    timeout=30.0,           # Request timeout in seconds (default: 30)
    base_path="/api"        # API base path (default: "/api")
)
```

## Development

### Setting up Development Environment

```bash
# Clone the repository
git clone https://github.com/netbirdio/netbird-python-client.git
cd netbird-python-client

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

# Run tests
pytest

# Run type checking
mypy src/

# Format code
black src/ tests/
isort src/ tests/

# Run linting
flake8 src/ tests/
```

### Running Tests

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=src/netbird --cov-report=html

# Run specific test categories
pytest -m unit          # Unit tests only
pytest -m integration   # Integration tests only
```

## Response Format

The NetBird Python client provides clean and intuitive API responses:

- **Input validation**: Uses Pydantic models for type safety and validation
- **API responses**: Returns standard Python dictionaries for easy access
- **Familiar patterns**: Simple dictionary-based responses

```python
# 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'])          # Access like a dictionary
print(user['email'])         # Easy dictionary access
print(user.get('role'))      # Safe access with .get()
```

## Interactive Demo

Explore the client with our **Jupyter notebook demo**:

```bash
# Install Jupyter if you haven't already
pip install jupyter

# Start the demo notebook
jupyter notebook netbird_demo.ipynb
```

The demo notebook shows real usage examples for all API resources.

## Documentation

- **[Jupyter Demo](netbird_demo.ipynb)** - Interactive demonstration of all features
- **[Integration Tests](tests/integration/)** - Real API usage examples
- **[Unit Tests](tests/unit/)** - Complete test coverage examples
- **[NetBird Documentation](https://docs.netbird.io/)** - Official NetBird docs

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

### Quick Contribution Guide

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for new functionality
5. Run the test suite (`pytest`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to your branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support

- **GitHub Issues**: [Report bugs or request features](https://github.com/drtinkerer/netbird-python-client/issues)
- **NetBird Community**: [Join the discussion](https://github.com/netbirdio/netbird/discussions)
- **Documentation**: [API Documentation](https://docs.netbird.io/api)

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for a detailed history of changes.

---

Made with ❤️ by [Bhushan Rane](https://github.com/drtinkerer)
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "netbird",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "api, client, mesh, netbird, networking, vpn",
    "author": null,
    "author_email": "Bhushan Rane <eulersidentity2718@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/f2/ca/f6e48e2ab5205faaa93971f649cd4cdaf1323280c1162d700967eff7dc86/netbird-1.0.1.tar.gz",
    "platform": null,
    "description": "# NetBird Python Client\n\n[![PyPI version](https://badge.fury.io/py/netbird.svg)](https://badge.fury.io/py/netbird)\n[![Python Support](https://img.shields.io/pypi/pyversions/netbird.svg)](https://pypi.org/project/netbird/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nPython client library for the [NetBird](https://netbird.io) API. Provides complete access to all NetBird API resources with a simple, intuitive interface.\n\nThis client follows the same upstream schemas as the official NetBird REST APIs, ensuring full compatibility and consistency with the NetBird ecosystem.\n\n## Features\n\n- \u2705 **Complete API Coverage** - All 11 NetBird API resources supported\n- \u2705 **Upstream Schema Compliance** - Follows official NetBird REST API schemas exactly\n- \u2705 **Dictionary Responses** - Clean dictionary responses for easy data access\n- \u2705 **Type Safety** - Pydantic models for input validation, dictionaries for responses\n- \u2705 **Modern Python** - Built for Python 3.8+ with async support ready\n- \u2705 **Comprehensive Error Handling** - Detailed exception classes for different error types\n- \u2705 **High Test Coverage** - 97.56% unit test coverage, 83.29% integration coverage\n- \u2705 **Extensive Documentation** - Complete API reference and examples\n- \u2705 **PyPI Ready** - Easy installation and distribution\n\n## Supported Resources\n\n| Resource | Description | Endpoints |\n|----------|-------------|-----------|\n| **Accounts** | Account management and settings | List, Update, Delete |\n| **Users** | User lifecycle management | CRUD + Invite, Current user |\n| **Tokens** | API token management | CRUD operations |\n| **Peers** | Network peer management | CRUD + Accessible peers |\n| **Setup Keys** | Peer setup key management | CRUD operations |\n| **Groups** | Peer group management | CRUD operations |\n| **Networks** | Network and resource management | CRUD + Resources/Routers |\n| **Policies** | Access control policies | CRUD operations |\n| **Routes** | Network routing configuration | CRUD operations |\n| **DNS** | DNS settings and nameservers | Nameserver groups + Settings |\n| **Events** | Audit and traffic events | Audit logs, Network traffic |\n\n## Installation\n\n```bash\npip install netbird\n```\n\n## Quick Start\n\n```python\nfrom netbird import APIClient\n\n# Initialize the client\nclient = APIClient(\n    host=\"api.netbird.io\",\n    api_token=\"your-api-token-here\"\n)\n\n# List all peers\npeers = client.peers.list()\nprint(f\"Found {len(peers)} peers\")\n\n# Get current user\nuser = client.users.get_current()\nprint(f\"Logged in as: {user['name']}\")\n\n# Create a new group\nfrom netbird.models import GroupCreate\ngroup_data = GroupCreate(\n    name=\"Development Team\",\n    peers=[\"peer-1\", \"peer-2\"]\n)\ngroup = client.groups.create(group_data)\nprint(f\"Created group: {group['name']}\")\n```\n\n## Authentication\n\nNetBird uses token-based authentication. You can use either a personal access token or a service user token:\n\n### Personal Access Token (Recommended)\n```python\nclient = APIClient(\n    host=\"api.netbird.io\",\n    api_token=\"your-personal-access-token\"\n)\n```\n\n### Service User Token\n```python\nclient = APIClient(\n    host=\"api.netbird.io\",\n    api_token=\"your-service-user-token\"\n)\n```\n\n### Self-Hosted NetBird\n```python\nclient = APIClient(\n    host=\"netbird.yourcompany.com:33073\",\n    api_token=\"your-token\",\n    use_ssl=True  # or False for HTTP\n)\n```\n\n## Examples\n\n### User Management\n```python\nfrom netbird.models import UserCreate, UserRole\n\n# Create a new user\nuser_data = UserCreate(\n    email=\"john@example.com\",\n    name=\"John Doe\",\n    role=UserRole.USER,\n    auto_groups=[\"group-developers\"]\n)\nuser = client.users.create(user_data)\nprint(f\"Created user: {user['name']} ({user['email']})\")\n\n# Update user role\nfrom netbird.models import UserUpdate\nupdate_data = UserUpdate(role=UserRole.ADMIN)\nupdated_user = client.users.update(user['id'], update_data)\nprint(f\"Updated user role to: {updated_user['role']}\")\n```\n\n### Network Management\n```python\nfrom netbird.models import NetworkCreate, PolicyCreate, PolicyRule\n\n# Create a network\nnetwork_data = NetworkCreate(\n    name=\"Production Network\",\n    description=\"Main production environment\"\n)\nnetwork = client.networks.create(network_data)\nprint(f\"Created network: {network['name']}\")\n\n# Create access policy\nrule = PolicyRule(\n    name=\"Allow SSH\",\n    action=\"accept\",\n    protocol=\"tcp\", \n    ports=[\"22\"],\n    sources=[\"group-admins\"],\n    destinations=[\"group-servers\"]\n)\npolicy_data = PolicyCreate(\n    name=\"Admin SSH Access\",\n    rules=[rule]\n)\npolicy = client.policies.create(policy_data)\nprint(f\"Created policy: {policy['name']}\")\n```\n\n### Setup Key Management\n```python\nfrom netbird.models import SetupKeyCreate\n\n# Create a reusable setup key\nkey_data = SetupKeyCreate(\n    name=\"Development Environment\",\n    type=\"reusable\",\n    expires_in=86400,  # 24 hours\n    usage_limit=10,\n    auto_groups=[\"group-dev\"]\n)\nsetup_key = client.setup_keys.create(key_data)\nprint(f\"Setup key: {setup_key['key']}\")\nprint(f\"Key valid: {setup_key['valid']}\")\n```\n\n### Event Monitoring\n```python\n# Get audit events\naudit_events = client.events.get_audit_events()\nfor event in audit_events[-10:]:  # Last 10 events\n    print(f\"{event['timestamp']}: {event['activity']}\")\n    if event.get('initiator_name'):\n        print(f\"  Initiated by: {event['initiator_name']}\")\n\n# Get network traffic events (cloud-only)\ntraffic_events = client.events.get_network_traffic_events(\n    protocol=\"tcp\",\n    page_size=100\n)\nfor traffic in traffic_events[:5]:\n    print(f\"Traffic: {traffic['source_ip']} -> {traffic['destination_ip']}\")\n```\n\n## Error Handling\n\nThe client provides specific exception types for different error conditions:\n\n```python\nfrom netbird.exceptions import (\n    NetBirdAPIError,\n    NetBirdAuthenticationError,\n    NetBirdNotFoundError,\n    NetBirdRateLimitError,\n    NetBirdServerError,\n    NetBirdValidationError,\n)\n\ntry:\n    user = client.users.get(\"invalid-user-id\")\nexcept NetBirdNotFoundError:\n    print(\"User not found\")\nexcept NetBirdAuthenticationError:\n    print(\"Invalid API token\")\nexcept NetBirdRateLimitError as e:\n    print(f\"Rate limited. Retry after {e.retry_after} seconds\")\nexcept NetBirdAPIError as e:\n    print(f\"API error: {e.message}\")\n```\n\n## Configuration Options\n\n```python\nclient = APIClient(\n    host=\"api.netbird.io\",\n    api_token=\"your-token\",\n    use_ssl=True,           # Use HTTPS (default: True)\n    timeout=30.0,           # Request timeout in seconds (default: 30)\n    base_path=\"/api\"        # API base path (default: \"/api\")\n)\n```\n\n## Development\n\n### Setting up Development Environment\n\n```bash\n# Clone the repository\ngit clone https://github.com/netbirdio/netbird-python-client.git\ncd netbird-python-client\n\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run type checking\nmypy src/\n\n# Format code\nblack src/ tests/\nisort src/ tests/\n\n# Run linting\nflake8 src/ tests/\n```\n\n### Running Tests\n\n```bash\n# Run all tests\npytest\n\n# Run with coverage\npytest --cov=src/netbird --cov-report=html\n\n# Run specific test categories\npytest -m unit          # Unit tests only\npytest -m integration   # Integration tests only\n```\n\n## Response Format\n\nThe NetBird Python client provides clean and intuitive API responses:\n\n- **Input validation**: Uses Pydantic models for type safety and validation\n- **API responses**: Returns standard Python dictionaries for easy access\n- **Familiar patterns**: Simple dictionary-based responses\n\n```python\n# Input: Type-safe Pydantic models\nuser_data = UserCreate(email=\"john@example.com\", name=\"John Doe\")\n\n# Output: Standard Python dictionaries\nuser = client.users.create(user_data)\nprint(user['name'])          # Access like a dictionary\nprint(user['email'])         # Easy dictionary access\nprint(user.get('role'))      # Safe access with .get()\n```\n\n## Interactive Demo\n\nExplore the client with our **Jupyter notebook demo**:\n\n```bash\n# Install Jupyter if you haven't already\npip install jupyter\n\n# Start the demo notebook\njupyter notebook netbird_demo.ipynb\n```\n\nThe demo notebook shows real usage examples for all API resources.\n\n## Documentation\n\n- **[Jupyter Demo](netbird_demo.ipynb)** - Interactive demonstration of all features\n- **[Integration Tests](tests/integration/)** - Real API usage examples\n- **[Unit Tests](tests/unit/)** - Complete test coverage examples\n- **[NetBird Documentation](https://docs.netbird.io/)** - Official NetBird docs\n\n## Contributing\n\nWe welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.\n\n### Quick Contribution Guide\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes\n4. Add tests for new functionality\n5. Run the test suite (`pytest`)\n6. Commit your changes (`git commit -m 'Add amazing feature'`)\n7. Push to your branch (`git push origin feature/amazing-feature`)\n8. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Support\n\n- **GitHub Issues**: [Report bugs or request features](https://github.com/drtinkerer/netbird-python-client/issues)\n- **NetBird Community**: [Join the discussion](https://github.com/netbirdio/netbird/discussions)\n- **Documentation**: [API Documentation](https://docs.netbird.io/api)\n\n## Changelog\n\nSee [CHANGELOG.md](CHANGELOG.md) for a detailed history of changes.\n\n---\n\nMade with \u2764\ufe0f by [Bhushan Rane](https://github.com/drtinkerer)",
    "bugtrack_url": null,
    "license": null,
    "summary": "Python client for the NetBird API",
    "version": "1.0.1",
    "project_urls": {
        "Changelog": "https://github.com/drtinkerer/netbird-python-client/blob/main/CHANGELOG.md",
        "Documentation": "https://github.com/drtinkerer/netbird-python-client",
        "Homepage": "https://github.com/drtinkerer/netbird-python-client",
        "Issues": "https://github.com/drtinkerer/netbird-python-client/issues",
        "Repository": "https://github.com/drtinkerer/netbird-python-client"
    },
    "split_keywords": [
        "api",
        " client",
        " mesh",
        " netbird",
        " networking",
        " vpn"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "feb7de5a9c73f21a379ad4d89db5c2b9b0e03d6af63b54afbb259679d9b68070",
                "md5": "3080f5413e8f450361d06b8d3d1d6344",
                "sha256": "b15c3ab41739c7ff37705a3e7b593e80c041cbed8a89d5d9a804445634561f64"
            },
            "downloads": -1,
            "filename": "netbird-1.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3080f5413e8f450361d06b8d3d1d6344",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 33678,
            "upload_time": "2025-07-28T09:42:43",
            "upload_time_iso_8601": "2025-07-28T09:42:43.033165Z",
            "url": "https://files.pythonhosted.org/packages/fe/b7/de5a9c73f21a379ad4d89db5c2b9b0e03d6af63b54afbb259679d9b68070/netbird-1.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f2caf6e48e2ab5205faaa93971f649cd4cdaf1323280c1162d700967eff7dc86",
                "md5": "b3b632af63b2767d858693ecb0a5717f",
                "sha256": "43bf55428763a663000a13506762faf99aef02ce3a15f1bb552ab39fe6c8a77b"
            },
            "downloads": -1,
            "filename": "netbird-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "b3b632af63b2767d858693ecb0a5717f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 83368,
            "upload_time": "2025-07-28T09:42:44",
            "upload_time_iso_8601": "2025-07-28T09:42:44.547366Z",
            "url": "https://files.pythonhosted.org/packages/f2/ca/f6e48e2ab5205faaa93971f649cd4cdaf1323280c1162d700967eff7dc86/netbird-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-28 09:42:44",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "drtinkerer",
    "github_project": "netbird-python-client",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "netbird"
}
        
Elapsed time: 1.08196s