Free tech learning for everyone, from basics to pro

Network AutomationNetworking SecurityIntermediate

Using the NetBox API with pynetbox: reading and updating your source of truth from Python

In short: NetBox is a popular source of truth for network inventory and IP addressing. The pynetbox library makes its REST API easy to use from Python: you can list devices by site or role, read interfaces and addresses, allocate the next free IP in a prefix, and update records. Scripts then use this data to generate configurations and verify devices.

Why use the API?

A source of truth is only useful if automation reads from it and, where appropriate, writes back to it. Instead of copying data from the NetBox web interface into spreadsheets, scripts query it directly.

Automation driven by NetBoxNetBoxdevices, IPs,VLANspynetboxAPI queriesPython scriptbuild dataJinja2render configPush or checkdevices
Figure 1. The source of truth holds intent; scripts turn it into configuration and checks.

Getting started

  1. Create an API token in NetBox under your user profile, with write access only if needed.
  2. Install the library: pip install pynetbox.
  3. Store the URL and token in environment variables.
import os
import pynetbox

nb = pynetbox.api(os.environ["NETBOX_URL"], token=os.environ["NETBOX_TOKEN"])

Reading data

# All access switches at one site
switches = nb.dcim.devices.filter(site="london-hq", role="access-switch")
for sw in switches:
    print(sw.name, sw.primary_ip, sw.device_type.model)

# Interfaces of one device
for intf in nb.dcim.interfaces.filter(device="lon-acc-01"):
    print(intf.name, intf.mode, intf.untagged_vlan)

# VLANs at a site
for vlan in nb.ipam.vlans.filter(site="london-hq"):
    print(vlan.vid, vlan.name)

Writing data

# Allocate the next free IP address in a prefix
prefix = nb.ipam.prefixes.get(prefix="10.20.30.0/24")
new_ip = prefix.available_ips.create({"description": "new printer"})
print("Allocated", new_ip.address)

# Update a device's status
dev = nb.dcim.devices.get(name="lon-acc-05")
dev.status = "active"
dev.save()

Generating configuration

Combine NetBox data with Jinja2 templates: fetch a device's interfaces and VLANs, build a dictionary and render the template. Store templates in Git so changes are reviewed.

Good practice

  • Use read-only tokens for scripts that only read.
  • Handle missing fields (for example a device with no primary IP) without crashing.
  • Use filters on the server side rather than downloading everything.
  • Log changes your scripts make, and use NetBox's change log for audit.
  • Check the API documentation at /api/docs/ on your NetBox instance; models change between versions.

Real-world example: no more duplicate IPs

A team assigned management IPs from a spreadsheet and regularly caused conflicts. A short script using pynetbox to allocate the next free address in the management prefix, record the device name in the description and render the configuration ended the duplicates.

Practice

How should you store the NetBox URL and token for scripts?
In environment variables or a secrets manager, not in the script.
How do you allocate the next free IP address in a prefix with pynetbox?
Get the prefix and call available_ips.create() on it.
Why use server-side filters in queries?
To fetch only the needed objects, which is faster and lighter than downloading everything.

Key takeaways

  • pynetbox gives Python easy access to the NetBox REST API.
  • Query devices, interfaces, IPs and VLANs with filters.
  • Create and update objects, including allocating free IPs.
  • Use the data with templates; secure tokens and handle missing fields.
Tracks your learning on this device only. See your progress on the learning paths.
Verified author✓ Valid
Issued to
Mohamed Fayas
Role
Founder of FM TecHub
Credentials
CCNABTEC HND Network EngineeringBEng (Hons) Computer Networking & Cloud Security
Issuer
FM TecHub · fmtechub.com

He writes practical, plain-English guides on networking, security and cloud.

More about the author →

Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.

Email updates: coming soon

New notes, tools and security news from FM TecHub by email, explained simply. Free. We're not collecting email addresses yet; see our privacy policy.

PortServiceStatus
SMTP/25Email updatesopening soon

Meanwhile, stay connected: