Skip to content

NetBox API Client Code Examples

This guide shows how to use the NetBox client to interact with NetBox APIs.

The wingpy NetBox client is designed for seamless interaction with NetBox's intent REST API. E.g. advanced device management, credential operations, and task polling.

Wingpy handles authentication, logging, concurrency and error management for you.

The Basics - Connect and Get Devices

Environment Variables

You can set the environment variables in your shell to avoid hardcoding sensitive information in your code. Check out the FAQ section on Environment Variables for more details.

Connect to NetBox
import wingpy

netbox = wingpy.NetBox(
    base_url="https://netbox.example.com", # (1)!
    token="...", # (2)!
    verify=False,
)
  1. Environment variable:

    WINGPY_NETBOX_BASE_URL
    
  2. Environment variable:

    WINGPY_NETBOX_TOKEN
    

Get all devices
# list[dict]
devices = netbox.get_all("/api/dcim/devices/")

for device in devices:
    print(device["name"])

Get device by ID
device_id = "<your-device-id>"

# httpx.Response
response = netbox.get(f"/api/dcim/devices/{id}/")

print(response.json())

IPAM Examples

NetBox supports managing IP addresses, VLANs, VRF etc. via the REST API

With these examples we assume that you have set the environment variables for authentication as shown above.

As with any other object in the NetBox database, all IP addresses and prefixes are dynamically allocated an internal ID. This can later be used to reference the IP address to query, modify or delete it.

Create a prefix and allocate IP addresses

To automatically allocate IP addresses in NetBox, we need an IP prefix first which can be created using the POST /api/ipam/prefixes/ API endpoint. (All NetBox API endpoints ends with a /). The request will return the created object in JSON format, including the automatically allocated ID.

After this has been created, we can ask NetBox to list the available address using the GET /api/ipam/prefixes/{id}/available-ips/ API endpoint. This uses a path parameter {id} which is mapped from the previously retrieved prefix ID. By default we will get a maximum of 50 addresses returned. If we want to allocate more or less than that we can add the query parameter limit to the request.

When executing multiple consecutive REST API requests we can benefit from using the wingpy NetBox client as a context manager to ensure proper cleanup of resources.

Create prefix and allocate IP addresses
import wingpy

# Parameters
prefix = "10.0.0.0/24"
address_count = 5

# context manager
with wingpy.NetBox() as netbox:
    # Create the prefix
    prefix_rsp = netbox.post(
        "/api/ipam/prefixes/",
        data={"prefix": prefix},
    )
    prefix_id = prefix_rsp.json()["id"]
    print(f"Prefix {prefix} was allocated ID {prefix_id}")

    # Get the next 5 available addresses
    available_ips = netbox.get(
        "/api/ipam/prefixes/{id}/available-ips/",
        path_params={
            "id": prefix_id,
        },
        params={
            "limit": address_count,
        },
    )

    # Loop through the available addresses and allocate them one by one
    for ip in available_ips.json():
        print(f"IP address {ip['address']} is available. Let's allocate it!")
        netbox.post(
            "/api/ipam/ip-addresses/",
            data={
                "address": ip["address"],
                "description": "Wingpy test address"
            },
        )

Working with paginated data

Almost all data in NetBox exists as entries in a database table. When you browse through the entries using the Web UI you can usually see one page with 100 items at a time. To see more entries you need to navigate to the next page or expand the number of entries per page.

The API works in the same way. So to make sure you see the complete result and not just a page, it is recommended to use the get_all method for enpoints that is capable of returning multiple entries.

get_all is supported with searches as well. NetBox provides a lot of filtering options as query parameters, for example iws (starts with) or ie (exact match).

So to find and delete all the addresses with the description Wingpy test address we can use the query parameter description__ie.

Search for IP addresses and delete them
import wingpy

# context manager
with wingpy.NetBox() as netbox:
    # Use NetBox's search filter query parameter
    addresses = netbox.get_all(
        "/api/ipam/ip-addresses/",
        params={
            "description_ie": "Wingpy test address",
        },
    )

    # get_all handles the pagination and returns a loopable Python list
    for address in addresses:
        print(f"Found address {address['address']}. Deleting now.")
        netbox.delete(
            "/api/ipam/ip-addresses/{id}/",
            path_params={
                "id": address["id"],
            },
        )