Skip to content

Nautobot API Client Code Examples

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

The wingpy Nautobot client is designed for seamless interaction with Nautobot'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 Nautobot
import wingpy

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

    WINGPY_NAUTOBOT_BASE_URL
    
  2. Environment variable:

    WINGPY_NAUTOBOT_TOKEN
    

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

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

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

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

print(response.json())

IPAM Examples

Nautobot 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 Nautobot 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 Nautobot, we need an IP prefix first which can be created using the POST /api/ipam/prefixes/ API endpoint. (All Nautobot 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 Nautobot 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 Nautobot 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.Nautobot() as nautobot:
    # Create the prefix
    prefix_rsp = nautobot.post(
        "/api/ipam/prefixes/",
        data={
            "prefix": prefix,
            "status": "Active",
        },
    )

    prefix_id = prefix_rsp.json()["id"]
    print(f"Prefix {prefix} was allocated ID {prefix_id}")

    # Get the next 5 available addresses
    available_ips = nautobot.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!")
        rsp = nautobot.post(
            "/api/ipam/ip-addresses/",
            data={
                "address": ip["address"],
                "description": "Wingpy test address",
                "namespace": "Global",
                "status": "Active",
            },
        )

Working with paginated data

Almost all data in Nautobot 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. Nautobot 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.Nautobot() as nautobot:
    # Use Nautobot's search filter query parameter
    addresses = nautobot.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.")
        nautobot.delete(
            "/api/ipam/ip-addresses/{id}/",
            path_params={
                "id": address["id"],
            },
        )