### Setup Development Environment Source: https://github.com/netbox-community/pynetbox/blob/master/CLAUDE.md Commands to initialize a virtual environment and install necessary dependencies. ```bash # Create and activate virtual environment python3 -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install dependencies pip install -r requirements.txt pip install -r requirements-dev.txt ``` -------------------------------- ### Install pyNetBox directly from source Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Install pyNetBox using the setup.py script after cloning the repository. ```bash python setup.py install ``` -------------------------------- ### Install Pynetbox Requirements Source: https://github.com/netbox-community/pynetbox/blob/master/README.md Install both requirements files for the project. ```bash pip install -r requirements.txt pip install -r requirements-dev.txt ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/netbox-community/pynetbox/blob/master/docs/development/getting-started.md Sets up a virtual environment and installs Pynetbox with development dependencies. Use on Windows: venv\Scripts\activate. ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -e ".[dev]" ``` -------------------------------- ### Install pyNetBox from source in development mode Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Install pyNetBox in editable mode after cloning the repository, suitable for development. ```bash pip install -e . ``` -------------------------------- ### Check Docker installation Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Verify that Docker is installed and running on your system before proceeding with Docker-based testing. ```bash docker --version ``` -------------------------------- ### Verify pyNetBox installation Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Import the pynetbox library and print its version to confirm successful installation. ```python import pynetbox print(pynetbox.version) ``` -------------------------------- ### Install development dependencies for pyNetBox Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Install pyNetBox in editable mode along with its development dependencies after cloning the repository and setting up a virtual environment. ```bash # Clone the repository git clone https://github.com/netbox-community/pynetbox.git cd pynetbox # Create and activate virtual environment python3 -m venv venv source venv/bin/activate # Install development dependencies pip install -r requirements.txt pip install -r requirements-dev.txt # Install in editable mode pip install -e . ``` -------------------------------- ### Install pyNetBox using pip Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Use this command to install the latest stable version of pyNetBox from the Python Package Index. ```bash pip install pynetbox ``` -------------------------------- ### Install Tenacity Dependency Source: https://github.com/netbox-community/pynetbox/blob/master/docs/branching.md Install the tenacity library to handle retries and waiting logic for branch status updates. ```bash pip install tenacity ``` -------------------------------- ### Upgrade pyNetBox to a specific version Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Command to install a particular version of pyNetBox. ```bash pip install pynetbox==7.6.0 ``` -------------------------------- ### Clone pyNetBox repository Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Clone the pyNetBox repository from GitHub to install from source or contribute to development. ```bash git clone https://github.com/netbox-community/pynetbox.git cd pynetbox ``` -------------------------------- ### Get Front Port Cable Paths Source: https://github.com/netbox-community/pynetbox/blob/master/docs/dcim.md Retrieves all possible cable paths through a front port. The front port object must be fetched prior to this operation. ```python # Get paths through a front port front_port = nb.dcim.front_ports.get(name='FrontPort1', device='patch-panel-1') paths = front_port.paths() # Each path contains origin, destination, and path segments for path_info in paths: print(f"Origin: {path_info['origin']}") print(f"Destination: {path_info['destination']}") print("Path segments:") for segment in path_info['path']: for obj in segment: print(f" - {obj}") ``` -------------------------------- ### Get a Specific Device Source: https://github.com/netbox-community/pynetbox/blob/master/docs/index.md Retrieves a single device by its name. Use this when you need to access a specific object. ```python # Get a specific device device = nb.dcim.devices.get(name='spine1') ``` -------------------------------- ### Upgrade pyNetBox to the latest version Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Command to upgrade your installed pyNetBox package to the most recent version available on PyPI. ```bash pip install --upgrade pynetbox ``` -------------------------------- ### Example of Valid and Invalid Filter Usage Source: https://github.com/netbox-community/pynetbox/blob/master/docs/advanced.md Demonstrates how PyNetBox with `strict_filters=True` handles valid and invalid filter parameters. Invalid filters raise a `ParameterValidationError`. ```python import pynetbox b = pynetbox.api( 'http://localhost:8000', token='your-token', strict_filters=True ) # Valid filter - works fine devices = nb.dcim.devices.filter(site='datacenter1') # Invalid filter - raises exception try: devices = nb.dcim.devices.filter(iste='datacenter1') # Typo: 'iste' instead of 'site' except pynetbox.core.query.ParameterValidationError as e: print(f"Error: {e}") # Error: 'iste' is not a valid filter parameter for dcim.devices ``` -------------------------------- ### Get NAPALM Device Facts Source: https://github.com/netbox-community/pynetbox/blob/master/docs/dcim.md Retrieve device facts using NAPALM integration. Ensure the device object is fetched first. ```python device = nb.dcim.devices.get(name='router1') # Get device facts facts = device.napalm.list(method='get_facts') print(facts) ``` -------------------------------- ### Get Rack Elevation as SVG Source: https://github.com/netbox-community/pynetbox/blob/master/docs/dcim.md Generates an SVG diagram representing the rack's elevation. The rack object needs to be fetched prior to this operation. ```python # Get elevation as SVG diagram svg_diagram = rack.elevation.list(render='svg') # Save SVG to file with open('rack-elevation.svg', 'w') as f: f.write(svg_diagram) ``` -------------------------------- ### Interact with NetBox Endpoints Source: https://github.com/netbox-community/pynetbox/blob/master/docs/api.md Use Endpoint instances to perform CRUD operations on NetBox data. The 'all()' method retrieves all items, 'get()' retrieves a specific item by ID, and 'create()' adds a new item. ```python # nb.dcim is an App instance # nb.dcim.devices is an Endpoint instance devices_endpoint = nb.dcim.devices # Endpoint provides CRUD methods all_devices = devices_endpoint.all() device = devices_endpoint.get(1) new_device = devices_endpoint.create(name='test', site=1, device_type=1, device_role=1) ``` -------------------------------- ### Get Rear Port Cable Paths Source: https://github.com/netbox-community/pynetbox/blob/master/docs/dcim.md Fetches all cable paths associated with a rear port. The rear port object must be retrieved before calling this method. ```python # Get paths through a rear port rear_port = nb.dcim.rear_ports.get(name='RearPort1', device='patch-panel-1') rear_paths = rear_port.paths() # Access the complete path from origin to destination if rear_paths: first_path = rear_paths[0] if first_path['origin']: print(f"Cable path starts at: {first_path['origin']}") if first_path['destination']: print(f"Cable path ends at: {first_path['destination']}") ``` -------------------------------- ### Build Documentation Source: https://github.com/netbox-community/pynetbox/blob/master/CLAUDE.md Commands to build and serve the project documentation locally or deploy to GitHub Pages. ```bash # Build and serve docs locally mkdocs serve # Deploy docs to GitHub Pages mkdocs gh-deploy ``` -------------------------------- ### Create and activate a virtual environment Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Recommended steps to create and activate a Python virtual environment for isolating pyNetBox dependencies. Activate on Linux/macOS or Windows. ```bash python3 -m venv venv source venv/bin/activate ``` ```bash venv\Scripts\activate ``` -------------------------------- ### Render Device and VM Configurations with Pynetbox Source: https://context7.com/netbox-community/pynetbox/llms.txt Devices and virtual machines support configuration rendering via config contexts and templates. Use the `render_config.create()` method to generate the configuration. ```python import pynetbox nb = pynetbox.api('http://localhost:8000', token='your-token') # Render device configuration device = nb.dcim.devices.get(name='switch1') config = device.render_config.create() print(config) # Render VM configuration vm = nb.virtualization.virtual_machines.get(name='web-vm-01') config = vm.render_config.create() print(config) ``` -------------------------------- ### Run tests Source: https://github.com/netbox-community/pynetbox/blob/master/docs/development/release-checklist.md Execute the test suite to ensure all components are functioning correctly before a release. ```bash pytest ``` -------------------------------- ### Get Single Object by ID or Name Source: https://context7.com/netbox-community/pynetbox/llms.txt Use the `get()` method to retrieve a single object, either by its unique ID or by a combination of unique fields like its name. The method returns `None` if no object is found or if multiple objects match a non-ID query. ```python import pynetbox b = pynetbox.api('http://localhost:8000', token='your-token') # Get by ID device = b.dcim.devices.get(1) print(f"Device: {device.name}, Serial: {device.serial}") # Get by name (must return exactly one result) device = b.dcim.devices.get(name='spine1') if device: print(f"Found: {device.name}") else: print("Device not found") ``` -------------------------------- ### Instantiate Pynetbox API Source: https://github.com/netbox-community/pynetbox/blob/master/README.md Import pynetbox and instantiate the API with the NetBox URL and an authentication token for writing data. ```python import pynetbox b = pynetbox.api( 'http://localhost:8000', token='d6f4e314a5b5fefd164995169f28ae32d987704f' ) ``` -------------------------------- ### POST /virtualization/virtual-machines/{id}/render-config/ Source: https://github.com/netbox-community/pynetbox/blob/master/docs/virtualization.md Renders the configuration for a specific virtual machine based on its assigned config contexts and templates. ```APIDOC ## POST /virtualization/virtual-machines/{id}/render-config/ ### Description This endpoint triggers the rendering of a virtual machine's configuration using the configured templates and context data. ### Method POST ### Endpoint /virtualization/virtual-machines/{id}/render-config/ ### Request Example ```python vm = nb.virtualization.virtual_machines.get(name='web-vm-01') config = vm.render_config.create() print(config) ``` ### Response #### Success Response (200) - **content** (string) - The rendered configuration text. ``` -------------------------------- ### Render Device Configuration Source: https://github.com/netbox-community/pynetbox/blob/master/docs/dcim.md Renders the device configuration using config contexts and templates. Requires fetching the device object first. ```python device = nb.dcim.devices.get(name='switch1') config = device.render_config.create() print(config) ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://github.com/netbox-community/pynetbox/blob/master/README.md Create and activate a Python virtual environment to isolate project dependencies. ```bash python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Get NAPALM Device Interfaces Source: https://github.com/netbox-community/pynetbox/blob/master/docs/dcim.md Retrieve network interface details from a device using NAPALM. This requires a device object to be previously obtained. ```python # Get interfaces interfaces = device.napalm.list(method='get_interfaces') ``` -------------------------------- ### Initialize Pynetbox API and Access Endpoints Source: https://github.com/netbox-community/pynetbox/blob/master/docs/endpoint.md Demonstrates how to initialize the Pynetbox API client and access an Endpoint for device management. Ensure you replace 'http://localhost:8000' and 'your-token' with your actual NetBox URL and API token. ```python import pynetbox nb = pynetbox.api('http://localhost:8000', token='your-token') # Accessing an attribute on an App returns an Endpoint devices = nb.dcim.devices # This is an Endpoint instance # Use Endpoint methods for CRUD operations all_devices = devices.all() device = devices.get(1) filtered = devices.filter(site='headquarters') new_device = devices.create(name='test', site=1, device_type=1, device_role=1) ``` -------------------------------- ### Get Rack Elevation Data Source: https://github.com/netbox-community/pynetbox/blob/master/docs/dcim.md Fetches rack elevation data, which can be rendered as a list of RU objects. The rack object must be retrieved first. ```python rack = nb.dcim.racks.get(name='RACK-01') # Get elevation as JSON (returns list of RU objects) elevation_data = rack.elevation.list() ``` -------------------------------- ### Manage Available IP Addresses Source: https://context7.com/netbox-community/pynetbox/llms.txt Explains how to list, allocate, and create IP addresses from available pools within prefixes and IP ranges using `available_ips`. ```python import pynetbox b = pynetbox.api('http://localhost:8000', token='your-token') # Get a prefix prefix = nb.ipam.prefixes.get(prefix='10.0.0.0/24') # List available IP addresses in the prefix available = prefix.available_ips.list() print(f"Available IPs: {available[:5]}") # [10.0.0.1/24, 10.0.0.2/24, 10.0.0.3/24, ...] # Allocate a single IP from the available pool new_ip = prefix.available_ips.create() print(f"Allocated: {new_ip.address}") # Allocate IP with specific attributes new_ip = prefix.available_ips.create({ 'dns_name': 'server01.example.com', 'description': 'Web Server', 'status': 'active', 'tags': ['production'] }) # Allocate multiple IPs at once new_ips = prefix.available_ips.create([{} for _ in range(5)]) for ip in new_ips: print(f"Allocated: {ip.address}") # Work with IP ranges ip_range = nb.ipam.ip_ranges.get(1) available_in_range = ip_range.available_ips.list() new_ip = ip_range.available_ips.create({ 'description': 'DHCP reservation', 'status': 'reserved' }) ``` -------------------------------- ### Create Child Prefixes Source: https://context7.com/netbox-community/pynetbox/llms.txt Demonstrates how to create child prefixes from a parent prefix using the `available_prefixes` property. ```python import pynetbox b = pynetbox.api('http://localhost:8000', token='your-token') ``` -------------------------------- ### Get NAPALM ARP Table Source: https://github.com/netbox-community/pynetbox/blob/master/docs/dcim.md Fetch the ARP table from a network device via NAPALM. The device object must be retrieved before calling this method. ```python # Get ARP table arp = device.napalm.list(method='get_arp_table') ``` -------------------------------- ### Initialize Pynetbox API Client Source: https://context7.com/netbox-community/pynetbox/llms.txt Basic initialization requires the NetBox URL and an API token. Optional parameters like 'threading' and 'strict_filters' can be set during initialization for performance and validation. ```python import pynetbox # Basic initialization with API token b = pynetbox.api( 'http://localhost:8000', token='d6f4e314a5b5fefd164995169f28ae32d987704f' ) ``` ```python # Initialize with threading for faster bulk queries b = pynetbox.api( 'http://localhost:8000', token='d6f4e314a5b5fefd164995169f28ae32d987704f', threading=True ) ``` ```python # Initialize with strict filter validation b = pynetbox.api( 'http://localhost:8000', token='d6f4e314a5b5fefd164995169f28ae32d987704f', strict_filters=True ) ``` -------------------------------- ### Initialize API Connection and Query Devices Source: https://github.com/netbox-community/pynetbox/blob/master/docs/index.md Initializes the PyNetBox API connection with a URL and token, then queries all devices and iterates through them. Use this to establish a connection and perform basic data retrieval. ```python import pynetbox # Initialize the API connection b = pynetbox.api( 'http://localhost:8000', token='d6f4e314a5b5fefd164995169f28ae32d987704f' ) # Query all devices devices = nb.dcim.devices.all() for device in devices: print(device.name) ``` -------------------------------- ### Create New Objects in NetBox Source: https://context7.com/netbox-community/pynetbox/llms.txt Shows how to create single and bulk objects in NetBox using the `create()` method. Supports creation using IDs or nested objects for related items. ```python import pynetbox b = pynetbox.api('http://localhost:8000', token='your-token') # Create a new site new_site = nb.dcim.sites.create( name='new-datacenter', slug='new-datacenter', status='planned', description='New datacenter facility' ) print(f"Created site: {new_site.name} (ID: {new_site.id})") # Create a device using IDs for related objects new_device = nb.dcim.devices.create( name='new-switch', device_type=1, site=1, role=5, status='staged' ) # Create with nested objects new_device = nb.dcim.devices.create( name='test-device', device_type={'id': 1}, site={'id': 1}, role={'id': 1} ) # Create IP address with assignment new_ip = nb.ipam.ip_addresses.create( address='10.0.0.100/24', status='active', dns_name='server01.example.com', assigned_object_type='dcim.interface', assigned_object_id=123, tags=['production', 'web-server'] ) # Bulk create multiple objects new_devices = nb.dcim.devices.create([ {'name': 'switch-1', 'device_type': 1, 'site': 1, 'role': 1}, {'name': 'switch-2', 'device_type': 1, 'site': 1, 'role': 1}, {'name': 'switch-3', 'device_type': 1, 'site': 1, 'role': 1} ]) for device in new_devices: print(f"Created: {device.name}") ``` -------------------------------- ### Virtual Circuits - Path Tracing Source: https://github.com/netbox-community/pynetbox/blob/master/docs/circuits.md Details how to perform cable path tracing for virtual circuits and their terminations using the `paths()` method, similar to standard circuit terminations. ```APIDOC ## Virtual Circuits - Path Tracing ### Description This section covers cable path tracing for Virtual Circuits and their associated terminations. The `paths()` method can be used to understand the physical connectivity underlying virtual circuits. ### Method `paths()` ### Endpoint N/A (This is a method on a pyNetBox object, not a direct REST endpoint) ### Parameters None for the `paths()` method itself. Parameters are used when retrieving the virtual circuit or termination objects (e.g., `cid`, `virtual_circuit_id`, `role`). ### Request Example ```python # Get a virtual circuit vcircuit = nb.circuits.virtual_circuits.get(cid='VPLS-001') print(f"Virtual Circuit: {vcircuit.cid}") print(f"Provider Network: {vcircuit.provider_network.name}") print(f"Type: {vcircuit.type.name}") # List all terminations for a virtual circuit terminations = nb.circuits.virtual_circuit_terminations.filter( virtual_circuit_id=vcircuit.id ) for term in terminations: print(f"Termination Role: {term.role}") # Get a virtual circuit termination vterm = nb.circuits.virtual_circuit_terminations.get( virtual_circuit_id=123, role='hub' ) # Get all cable paths through this termination paths = vterm.paths() # Analyze the connectivity for path_info in paths: print(f"Origin: {path_info['origin']}") print(f"Destination: {path_info['destination']}") print("Path segments:") for segment in path_info['path']: for obj in segment: print(f" - {obj}") # Example: Find all devices connected via a virtual circuit vcircuit = nb.circuits.virtual_circuits.get(cid='VPLS-001') terminations = nb.circuits.virtual_circuit_terminations.filter( virtual_circuit_id=vcircuit.id ) print(f"Virtual Circuit {vcircuit.cid} connectivity:") for term in terminations: paths = term.paths() if paths and paths[0]['destination']: print(f" {term.role}: {paths[0]['destination']}") ``` ### Response #### Success Response The `paths()` method, when called on a virtual circuit termination, returns a list of dictionaries. Each dictionary represents a complete cable path and contains: - `origin`: The starting endpoint of the path (Record object or None if unconnected). - `destination`: The ending endpoint of the path (Record object or None if unconnected). - `path`: A list of path segments, where each segment is a list of Record objects representing the components in that segment. #### Response Example ```json [ { "origin": {"id": 2, "url": "/api/circuits/virtual-terminations/2/", "name": "VC Term A"}, "destination": {"id": 7, "url": "/api/dcim/interfaces/7/", "name": "Interface Y"}, "path": [ [ {"id": 15, "url": "/api/dcim/cables/15/", "label": "VC Cable 1"} ] ] } ] ``` ``` -------------------------------- ### Create release branch Source: https://github.com/netbox-community/pynetbox/blob/master/docs/development/release-checklist.md Commands to initialize a new release branch from the master branch. ```bash git checkout master git pull git checkout -b release/vX.Y.Z ``` -------------------------------- ### Establish Basic API Connection Source: https://github.com/netbox-community/pynetbox/blob/master/docs/getting-started.md Import pynetbox and create an API connection to your NetBox instance using its URL and an authentication token. ```python import pynetbox b = pynetbox.api( 'http://localhost:8000', token='d6f4e314a5b5fefd164995169f28ae32d987704f' ) ``` -------------------------------- ### Run Integration Tests with Version Control Source: https://github.com/netbox-community/pynetbox/blob/master/CLAUDE.md Commands for running integration tests against specific NetBox versions or custom instances. ```bash # Test against specific NetBox versions (default: 4.4) pytest tests/integration --netbox-versions 4.4 # Skip cleanup to leave Docker containers running pytest --no-cleanup # Use existing NetBox instance (skip Docker) pytest -p no:docker --url-override http://localhost:8000 ``` -------------------------------- ### Manage IPAM VLANs with Pynetbox Source: https://context7.com/netbox-community/pynetbox/llms.txt The `available_vlans` property on VLAN groups allows viewing and creating available VLANs. You can list available VLAN IDs or create a new VLAN by assigning the next available ID or a specific VID within the available range. ```python import pynetbox nb = pynetbox.api('http://localhost:8000', token='your-token') # Get a VLAN group vlan_group = nb.ipam.vlan_groups.get(name='Production') # List available VLAN IDs available = vlan_group.available_vlans.list() print(f"Available VLAN IDs: {available[:10]}") # [10, 11, 12, 13, ...] # Create a VLAN from available IDs (assigns next available) new_vlan = vlan_group.available_vlans.create({ 'name': 'NewVLAN', 'status': 'active' }) print(f"Created VLAN: {new_vlan.name} (VID: {new_vlan.vid})") # Create VLAN with specific VID (must be in available range) new_vlan = vlan_group.available_vlans.create({ 'name': 'Servers', 'vid': 100, 'status': 'active', 'description': 'Server VLAN' }) ``` -------------------------------- ### Integrate with NAPALM using Pynetbox Source: https://context7.com/netbox-community/pynetbox/llms.txt Devices support NAPALM integration for retrieving live device data. Use the `device.napalm.list(method='method_name')` to call various NAPALM methods like `get_facts`, `get_interfaces`, etc. ```python import pynetbox nb = pynetbox.api('http://localhost:8000', token='your-token') device = nb.dcim.devices.get(name='router1') # Get device facts facts = device.napalm.list(method='get_facts') print(facts) # Get interfaces interfaces = device.napalm.list(method='get_interfaces') # Get ARP table arp = device.napalm.list(method='get_arp_table') # Get routing table routes = device.napalm.list(method='get_route_to') ``` -------------------------------- ### Render Virtual Machine Configuration Source: https://github.com/netbox-community/pynetbox/blob/master/docs/virtualization.md Uses the render_config property to generate a virtual machine's configuration based on existing contexts and templates. ```python vm = nb.virtualization.virtual_machines.get(name='web-vm-01') config = vm.render_config.create() print(config) ``` -------------------------------- ### Update Objects in NetBox Source: https://context7.com/netbox-community/pynetbox/llms.txt Demonstrates updating single objects using `save()` and batch updates using `update()`. Also shows how to preview changes before saving. ```python import pynetbox b = pynetbox.api('http://localhost:8000', token='your-token') # Method 1: Modify attributes and save device = nb.dcim.devices.get(name='test-device') device.serial = 'ABC123' device.asset_tag = 'ASSET001' device.status = 'active' device.save() print(f"Updated device serial: {device.serial}") # Method 2: Use update() with a dictionary device = nb.dcim.devices.get(1) device.update({ 'serial': 'XYZ789', 'asset_tag': 'ASSET002', 'comments': 'Updated via pynetbox' }) # Check what changes will be sent before saving device = nb.dcim.devices.get(name='switch1') device.serial = 'NEW-SERIAL' print(device.updates()) # {'serial': 'NEW-SERIAL'} # Bulk update multiple objects devices = list(nb.dcim.devices.filter(site='test-site')) for device in devices: device.status = 'active' b.dcim.devices.update(devices) # Update via RecordSet directly b.dcim.devices.filter(site_id=1).update(status='active') ``` -------------------------------- ### Test connectivity to NetBox instance Source: https://github.com/netbox-community/pynetbox/blob/master/docs/installation.md Instantiate the pynetbox API client and test connection by printing the NetBox version and status. ```python import pynetbox b = pynetbox.api( 'http://localhost:8000', token='your-api-token-here' ) # Check NetBox version print(nb.version) # Check API status print(nb.status()) ``` -------------------------------- ### Create Child Prefixes with Pynetbox Source: https://context7.com/netbox-community/pynetbox/llms.txt Use the `available_prefixes.create()` method on a parent prefix object to create child prefixes of a specified length. Multiple prefixes can be created in a single call. ```python import pynetbox nb = pynetbox.api('http://localhost:8000', token='your-token') # Get a parent prefix parent = nb.ipam.prefixes.get(prefix='10.0.0.0/16') # List available child prefixes available = parent.available_prefixes.list() print(f"Available prefixes: {available[:5]}") # [10.0.1.0/24, 10.0.2.0/23, 10.0.4.0/22, ...] # Create a child prefix with specific size new_prefix = parent.available_prefixes.create({ 'prefix_length': 24, 'status': 'active', 'description': 'Server subnet', 'site': 1 }) print(f"Created prefix: {new_prefix.prefix}") # Create multiple child prefixes new_prefixes = parent.available_prefixes.create([ {'prefix_length': 24, 'description': 'Subnet 1'}, {'prefix_length': 24, 'description': 'Subnet 2'}, {'prefix_length': 25, 'description': 'Small subnet'} ]) for prefix in new_prefixes: print(f"Created: {prefix.prefix}") ``` -------------------------------- ### Circuit Terminations - Cable Path Tracing Source: https://github.com/netbox-community/pynetbox/blob/master/docs/circuits.md Demonstrates how to trace cable paths through a circuit termination using the `paths()` method. This helps visualize the connectivity from origin to destination. ```APIDOC ## Circuit Terminations - Cable Path Tracing ### Description This section details how to use the `paths()` method on circuit termination objects to trace all cable paths traversing through them. It provides insights into the complete connectivity from the origin to the destination. ### Method `paths()` ### Endpoint N/A (This is a method on a pyNetBox object, not a direct REST endpoint) ### Parameters None for the `paths()` method itself. Parameters are used when retrieving the circuit termination object (e.g., `circuit_id`, `term_side`). ### Request Example ```python # Get a circuit termination circuit_term = nb.circuits.circuit_terminations.get(circuit_id=123, term_side='A') # Get all cable paths through this termination paths = circuit_term.paths() # Each path contains origin, destination, and path segments for path_info in paths: print(f"Origin: {path_info['origin']}") print(f"Destination: {path_info['destination']}") print("Path segments:") for segment in path_info['path']: for obj in segment: print(f" - {obj}") # Example: Find what a circuit connects to circuit = nb.circuits.circuits.get(cid='CIRCUIT-001') terminations = nb.circuits.circuit_terminations.filter(circuit_id=circuit.id) for term in terminations: print(f"\nTermination {term.term_side}:") paths = term.paths() if paths: for path in paths: if path['destination']: print(f" Connected to: {path['destination']}") else: print(" No destination (incomplete path)") else: print(" No cable paths") ``` ### Response #### Success Response The `paths()` method returns a list of dictionaries. Each dictionary represents a complete cable path and contains the following keys: - `origin`: The starting endpoint of the path (Record object or None if unconnected). - `destination`: The ending endpoint of the path (Record object or None if unconnected). - `path`: A list of path segments. Each segment is a list of Record objects representing the components in that segment (e.g., cables, terminations, interfaces). #### Response Example ```json [ { "origin": {"id": 1, "url": "/api/dcim/terminations/1/", "name": "Rack 1 - Unit 1"}, "destination": {"id": 5, "url": "/api/dcim/terminations/5/", "name": "Device A - Interface X"}, "path": [ [ {"id": 10, "url": "/api/dcim/cables/10/", "label": "Cable 1"} ] ] } ] ``` ``` -------------------------------- ### Create a New Device Source: https://github.com/netbox-community/pynetbox/blob/master/docs/index.md Creates a new device in NetBox. Requires specifying device type, site, and device role, typically by their IDs. ```python # Create a new device new_device = nb.dcim.devices.create( name='new-device', device_type=1, site=1, device_role=1 ) ``` -------------------------------- ### Trace Cable Paths for Virtual Circuit Terminations Source: https://github.com/netbox-community/pynetbox/blob/master/docs/circuits.md Analyzes connectivity for virtual circuit terminations using the paths() method. ```python # Get a virtual circuit termination vterm = nb.circuits.virtual_circuit_terminations.get( virtual_circuit_id=123, role='hub' ) # Get all cable paths through this termination paths = vterm.paths() # Analyze the connectivity for path_info in paths: print(f"Origin: {path_info['origin']}") print(f"Destination: {path_info['destination']}") print("Path segments:") for segment in path_info['path']: for obj in segment: print(f" - {obj}") # Example: Find all devices connected via a virtual circuit vcircuit = nb.circuits.virtual_circuits.get(cid='VPLS-001') terminations = nb.circuits.virtual_circuit_terminations.filter( virtual_circuit_id=vcircuit.id ) print(f"Virtual Circuit {vcircuit.cid} connectivity:") for term in terminations: paths = term.paths() if paths and paths[0]['destination']: print(f" {term.role}: {paths[0]['destination']}") ``` -------------------------------- ### List All Devices Source: https://github.com/netbox-community/pynetbox/blob/master/README.md To iterate over the results of all() multiple times, encapsulate the results in a list object. ```python >>> devices = list(nb.dcim.devices.all()) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/netbox-community/pynetbox/blob/master/docs/development/getting-started.md Executes the unit test suite for Pynetbox using pytest. ```bash pytest tests/unit ``` -------------------------------- ### Query All Objects with Pagination Source: https://context7.com/netbox-community/pynetbox/llms.txt Use the `all()` method to retrieve all objects from an endpoint. This method returns a generator that automatically handles pagination. ```python import pynetbox b = pynetbox.api('http://localhost:8000', token='your-token') # Get all devices (returns a generator) devices = b.dcim.devices.all() for device in devices: print(f"{device.name} - {device.device_type} at {device.site}") # Output: # spine1 - Cisco Nexus 9000 at datacenter-1 # leaf1 - Arista 7050 at datacenter-1 # leaf2 - Arista 7050 at datacenter-1 # Convert to list for multiple iterations devices = list(b.dcim.devices.all()) print(f"Total devices: {len(devices)}") # Get all IP addresses ip_addresses = list(b.ipam.ip_addresses.all()) for ip in ip_addresses: print(f"{ip.address} - {ip.status}") # With pagination control devices = b.dcim.devices.all(limit=100, offset=0) ``` -------------------------------- ### Enable Threading for API Queries Source: https://github.com/netbox-community/pynetbox/blob/master/README.md Enable multithreaded calls for .filter() and .all() queries by setting threading=True in the API object initialization. Ensure MAX_PAGE_SIZE in Netbox is not 0 or None. ```python nb = pynetbox.api( 'http://localhost:8000', threading=True, ) ``` -------------------------------- ### Trace Cable Connections with Pynetbox Source: https://context7.com/netbox-community/pynetbox/llms.txt DCIM objects like interfaces, console ports, and power ports support cable tracing via the `trace()` method. The results can be parsed to identify terminations, cables, and their connections. ```python import pynetbox nb = pynetbox.api('http://localhost:8000', token='your-token') # Trace a network interface interface = nb.dcim.interfaces.get(name='eth0', device='switch1') trace_result = interface.trace() # Parse the trace results (list of [terminations, cable, terminations]) for item in trace_result: if isinstance(item, list): for term in item: print(f" Termination: {term}") else: if item: print(f" Cable: {item.id} - {item.label}") else: print(" No cable") # Trace console port console = nb.dcim.console_ports.get(name='Console', device='router1') console_trace = console.trace() # Trace power connections power_port = nb.dcim.power_ports.get(name='PSU1', device='server1') power_trace = power_port.trace() # Get paths through front/rear ports front_port = nb.dcim.front_ports.get(name='FrontPort1', device='patch-panel-1') paths = front_port.paths() for path_info in paths: print(f"Origin: {path_info['origin']}") print(f"Destination: {path_info['destination']}") for segment in path_info['path']: for obj in segment: print(f" - {obj}") ``` -------------------------------- ### Run Tests with Coverage Reporting Source: https://github.com/netbox-community/pynetbox/blob/master/docs/development/getting-started.md Executes all tests and generates a coverage report for the pynetbox library. ```bash pytest --cov=pynetbox tests/ ``` -------------------------------- ### Configure API Connection Parameters Source: https://github.com/netbox-community/pynetbox/blob/master/docs/getting-started.md Configure the API connection with optional parameters like threading and strict filter validation. The URL and token are essential for establishing the connection. ```python nb = pynetbox.api( 'http://localhost:8000', token='your-token-here', threading=True, strict_filters=True ) ``` -------------------------------- ### Query All Devices Source: https://github.com/netbox-community/pynetbox/blob/master/README.md Query all objects in the 'devices' endpoint. The all() method returns a generator that can only be iterated over once. ```python >>> devices = nb.dcim.devices.all() >>> for device in devices: ... print(device.name) ... test1-leaf1 test1-leaf2 test1-leaf3 >>> ``` -------------------------------- ### Run Integration Tests Source: https://github.com/netbox-community/pynetbox/blob/master/docs/development/getting-started.md Executes the integration test suite for Pynetbox. Requires a running NetBox instance or uses pytest-docker. ```bash pytest tests/integration ``` -------------------------------- ### Enable Threading in PyNetBox API Initialization Source: https://github.com/netbox-community/pynetbox/blob/master/docs/advanced.md Initialize the PyNetBox API with `threading=True` to enable parallel fetching for `.all()` and `.filter()` queries. This significantly speeds up operations on large datasets. ```python import pynetbox b = pynetbox.api( 'http://localhost:8000', token='your-token', threading=True ) # Now all .all() and .filter() calls will use threading devices = nb.dcim.devices.all() # Fetches pages in parallel ``` -------------------------------- ### Delete Objects from NetBox Source: https://context7.com/netbox-community/pynetbox/llms.txt Illustrates how to delete single objects by retrieving them first, and how to perform bulk deletions using lists of objects or filters. ```python import pynetbox b = pynetbox.api('http://localhost:8000', token='your-token') # Delete a single object device = nb.dcim.devices.get(name='test-device') if device: device.delete() print("Device deleted") # Bulk delete via endpoint devices_to_delete = list(nb.dcim.devices.filter(status='decommissioned')) if devices_to_delete: nb.dcim.devices.delete(devices_to_delete) print(f"Deleted {len(devices_to_delete)} devices") # Delete by ID list b.dcim.devices.delete([1, 2, 3]) # Bulk delete via RecordSet b.dcim.devices.filter(site_id=1, status='offline').delete() ``` -------------------------------- ### Device Config Rendering Source: https://github.com/netbox-community/pynetbox/blob/master/docs/dcim.md Renders device configuration based on assigned config contexts and templates. ```APIDOC ## POST /dcim/devices/{id}/render-config ### Description Triggers the rendering of a device configuration. ### Method POST ### Response Example ```python # Returns the rendered configuration string "hostname router1\n!\ninterface ge-0/0/0\n..." ``` ``` -------------------------------- ### Retrieve Virtual Circuit Information Source: https://github.com/netbox-community/pynetbox/blob/master/docs/circuits.md Fetches virtual circuit details and lists associated terminations. ```python # Get a virtual circuit vcircuit = nb.circuits.virtual_circuits.get(cid='VPLS-001') print(f"Virtual Circuit: {vcircuit.cid}") print(f"Provider Network: {vcircuit.provider_network.name}") print(f"Type: {vcircuit.type.name}") # List all terminations for a virtual circuit terminations = nb.circuits.virtual_circuit_terminations.filter( virtual_circuit_id=vcircuit.id ) for term in terminations: print(f"Termination Role: {term.role}") ``` -------------------------------- ### Retrieve Objects with Filters and Access Attributes Source: https://context7.com/netbox-community/pynetbox/llms.txt Demonstrates how to retrieve objects using filters and access their nested attributes. Objects can also be converted to dictionaries or serialized. ```python location = nb.dcim.locations.get(site='site-1', name='Row 1') device = nb.dcim.devices.get(name='switch1') print(f"Device Type: {device.device_type.model}") print(f"Site: {device.site.name}") print(f"Primary IP: {device.primary_ip.address}") device_dict = dict(device) print(device_dict) device_data = device.serialize() ``` -------------------------------- ### Run Integration Tests with Specific NetBox Versions Source: https://github.com/netbox-community/pynetbox/blob/master/docs/development/getting-started.md Executes integration tests against specified NetBox versions using the --netbox-versions flag. ```bash pytest tests/integration --netbox-versions 4.2 4.3 4.4 ``` -------------------------------- ### Initialize pyNetBox API Connection Source: https://github.com/netbox-community/pynetbox/blob/master/docs/api.md Create an API connection to NetBox using the Api class. Requires the NetBox URL and an authentication token. Access NetBox applications and endpoints through the initialized Api object. ```python import pynetbox # Create API connection (Api class) b = pynetbox.api('http://localhost:8000', token='your-token') # Access an app (App class) b.dcim # Returns an App instance # Access an endpoint (Endpoint class) b.dcim.devices # Returns an Endpoint instance # Use endpoint methods devices = b.dcim.devices.all() ``` -------------------------------- ### Configure HTTP Timeouts with Adapters Source: https://github.com/netbox-community/pynetbox/blob/master/docs/advanced.md Use a custom HTTPAdapter to set a timeout for requests. Mount this adapter to the pynetbox session to apply the timeout globally. ```python from requests.adapters import HTTPAdapter class TimeoutHTTPAdapter(HTTPAdapter): def __init__(self, *args, **kwargs): self.timeout = kwargs.get("timeout", 5) super().__init__(*args, **kwargs) def send(self, request, **kwargs): kwargs['timeout'] = self.timeout return super().send(request, **kwargs) adapter = TimeoutHTTPAdapter() session = requests.Session() session.mount("http://", adapter) session.mount("https://", adapter) nb = pynetbox.api( 'http://localhost:8000', token='d6f4e314a5b5fefd164995169f28ae32d987704f' ) nb.http_session = session ``` -------------------------------- ### Provision API Tokens Source: https://context7.com/netbox-community/pynetbox/llms.txt Generate new API tokens programmatically by providing valid user credentials to the create_token method. ```python import pynetbox # Initialize without token nb = pynetbox.api('https://netbox-server') # Create token with credentials token = nb.create_token('admin', 'password') print(f"Token: {nb.token}") # '96d02e13e3f1fdcd8b4c089094c0191dcb045bef' # Token details print(dict(token)) # { # 'id': 2, # 'key': '96d02e13e3f1fdcd8b4c089094c0191dcb045bef', # 'write_enabled': True, # 'user': {'id': 1, 'username': 'admin', ...}, # ... # } ``` -------------------------------- ### Prefix Available Prefixes Source: https://github.com/netbox-community/pynetbox/blob/master/docs/ipam.md Methods to list and create available child prefixes within a parent prefix. ```APIDOC ## GET/POST /ipam/prefixes/{id}/available-prefixes ### Description View and create available child prefixes within a parent prefix. ### Request Example { "prefix_length": 24, "status": "active", "description": "Server subnet" } ### Response #### Success Response (200) - **list** (array) - List of available child prefixes - **create** (object) - Created prefix object ``` -------------------------------- ### Manage available IPs in a Prefix Source: https://github.com/netbox-community/pynetbox/blob/master/docs/ipam.md Use the available_ips property on a Prefix object to list or allocate IP addresses within that prefix. ```python prefix = nb.ipam.prefixes.get(prefix='10.0.0.0/24') # List available IP addresses available = prefix.available_ips.list() # [10.0.0.1/24, 10.0.0.2/24, 10.0.0.3/24, ...] # Create a single IP from available pool new_ip = prefix.available_ips.create() # Create multiple IPs new_ips = prefix.available_ips.create([{} for i in range(5)]) # Create IP with specific attributes new_ip = prefix.available_ips.create({ 'dns_name': 'server01.example.com', 'description': 'Web Server', 'status': 'active' }) ``` -------------------------------- ### Prefix Available IPs Source: https://github.com/netbox-community/pynetbox/blob/master/docs/ipam.md Methods to list and create available IP addresses within a specific prefix. ```APIDOC ## GET/POST /ipam/prefixes/{id}/available-ips ### Description View and create available IP addresses within a prefix. ### Request Example { "dns_name": "server01.example.com", "description": "Web Server", "status": "active" } ### Response #### Success Response (200) - **list** (array) - List of available IP addresses - **create** (object) - Created IP address object ``` -------------------------------- ### Execute Test Suite Source: https://github.com/netbox-community/pynetbox/blob/master/CLAUDE.md Various commands for running unit, integration, and specific tests using pytest. ```bash # Run all tests pytest # Run only unit tests (fast, no Docker required) pytest tests/unit # Run only integration tests (requires Docker) pytest tests/integration # Run specific test file pytest tests/test_api.py # Run specific test function pytest tests/test_api.py::ApiStatusTestCase::test_api_status # Run tests matching a pattern pytest -k "test_api" # Run with coverage pytest --cov=pynetbox tests/ ``` -------------------------------- ### Lint Codebase Source: https://github.com/netbox-community/pynetbox/blob/master/CLAUDE.md Commands to run the Ruff linter and apply automatic fixes. ```bash # Run Ruff linter ruff check pynetbox/ tests/ # Fix auto-fixable issues ruff check --fix pynetbox/ tests/ ``` -------------------------------- ### Compare Threaded vs. Non-Threaded Performance Source: https://github.com/netbox-community/pynetbox/blob/master/docs/advanced.md Measure the performance difference between standard and threaded API calls for fetching all devices. Ensure `threading=True` is set for the threaded comparison. ```python import pynetbox import time b = pynetbox.api('http://localhost:8000', token='your-token') # Without threading start = time.time() devices = list(nb.dcim.devices.all()) print(f"Without threading: {time.time() - start:.2f}s") # With threading b_threaded = pynetbox.api( 'http://localhost:8000', token='your-token', threading=True ) start = time.time() devices = list(nb_threaded.dcim.devices.all()) print(f"With threading: {time.time() - start:.2f}s") ``` -------------------------------- ### Upload Image Attachments Source: https://github.com/netbox-community/pynetbox/blob/master/docs/advanced.md Upload files by passing a file-like object to the create method. Pynetbox automatically switches to multipart/form-data encoding. ```python import pynetbox nb = pynetbox.api( 'http://localhost:8000', token='d6f4e314a5b5fefd164995169f28ae32d987704f' ) # Attach an image to a device with open('/path/to/image.png', 'rb') as f: attachment = nb.extras.image_attachments.create( object_type='dcim.device', object_id=1, image=f, name='rack-photo.png' ) ``` ```python import io import pynetbox nb = pynetbox.api( 'http://localhost:8000', token='d6f4e314a5b5fefd164995169f28ae32d987704f' ) # Create image from bytes image_data = b'...' # Your image bytes file_obj = io.BytesIO(image_data) file_obj.name = 'generated-image.png' # Optional: set filename attachment = nb.extras.image_attachments.create( object_type='dcim.device', object_id=1, image=file_obj ) ``` ```python with open('/path/to/image.png', 'rb') as f: attachment = nb.extras.image_attachments.create( object_type='dcim.device', object_id=1, image=('custom-name.png', f, 'image/png') ) ```