NetBox API Client Library
pynetbox is the official Python API client library for NetBox, a popular open-source IPAM and DCIM solution. It provides a convenient, object-oriented interface for interacting with the NetBox REST API, abstracting away the complexities of raw HTTP requests. The library is actively maintained with frequent releases, currently at version 7.6.1, ensuring compatibility with the latest NetBox versions (supporting NetBox 3.3+ and recent 4.x features like v2 API tokens).
Warnings
- breaking In pynetbox v7.6.0, the `ObjectChange` model was moved to the `core` module for NetBox 4.1.0+ compatibility. Code referencing `nb.extras.object_changes` must be updated to `nb.core.object_changes`.
- breaking pynetbox v7.4.0 dropped support for Python 3.8 and 3.9, aligning with NetBox 4.0's removal of support for these Python versions. Users on older Python versions must upgrade.
- gotcha NetBox's API, by default, silently returns *all* objects if an invalid filter is provided, which can lead to unexpected and incorrect results. `pynetbox` offers `strict_filters=True` in the API constructor to enable client-side validation and raise an exception for invalid filters.
- gotcha Between pynetbox v7.0.0 and v7.3.x, there was a bug (#597) that caused failures when attempting to insert complex custom fields (e.g., lists of dictionaries). The `update()` method would return successfully, but the fields would be set to `None` in NetBox. This was fixed in v7.4.0.
- gotcha pynetbox versions 6.7 and later require NetBox 3.3 or higher. Ensure your NetBox instance meets this minimum version to avoid compatibility issues.
- gotcha NetBox v4.5 introduced v2 API tokens, which `pynetbox` v7.6.0+ supports. While legacy tokens still work, using v2 tokens might require updating your token management strategy for enhanced security features.
Install
-
pip install pynetbox
Imports
- api
import pynetbox nb = pynetbox.api(...)
Quickstart
import os
import pynetbox
NETBOX_URL = os.environ.get('NETBOX_URL', 'http://localhost:8000')
NETBOX_TOKEN = os.environ.get('NETBOX_TOKEN', 'YOUR_API_TOKEN_HERE') # Required for write operations
try:
nb = pynetbox.api(NETBOX_URL, token=NETBOX_TOKEN)
# Test connection and fetch NetBox version
print(f"Connected to NetBox version: {nb.version}")
# Fetch the first 5 devices
devices = list(nb.dcim.devices.all()[:5])
if devices:
print("\nFirst 5 Devices:")
for device in devices:
print(f" - {device.name} (ID: {device.id})")
else:
print("\nNo devices found.")
except pynetbox.RequestError as e:
print(f"NetBox API Request Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")