NbApi

class nbforager.NbApi(host: str, token: str = '', scheme: str = 'https', port: int = 0, verify: bool = True, limit: int = 1000, url_length: int = 2047, threads: int = 1, interval: float = 0.0, timeout: int = 60, max_retries: int = 0, sleep: int = 10, strict: bool = False, extended_get: bool = True, loners: Dict[str, List[str]] | None = None, **kwargs)

NbApi, Python wrapper of Netbox REST API.

It is a set of connectors to Netbox endpoints. Connectors are nested by principle {application}.{model}.{method}, where:

  • application can be: circuits, dcim, ipam, etc.;

  • model can be: circuit_terminations, ip_addresses, etc.;

  • method can be: create, delete, get, update.

For example https://demo.netbox.dev/api/ipam/ip-addresses/ can be reached by NbApi.ipam.ip_addresses.get() method.

The parameters for the create, delete, update methods are identical in all models. The parameters for the get method are different for each model. Only NbApi.ipam.ip_addresses.get() is described in this documentation. Other models are implemented in a similar manner. Exact parameters can be found in Schema.

Initialize NbApi.

Parameters:
  • host (str) – Netbox host name.

  • token (str) – Netbox token.

  • scheme (str) – Access method: https or http. Default is https.

  • port (int) – TCP port. Default is 443 for scheme=`https`, 80 for scheme=`http`.

  • verify (bool) – Transport Layer Security. True - A TLS certificate is required, False - Requests will accept any TLS certificate. Default is True.

  • limit (int) – Split the query to multiple requests if the count of objects exceeds this value. Default is 1000.

  • url_length (int) – Split the query to multiple requests if the URL length exceeds maximum length due to a long list of GET parameters. Default is 2047.

  • threads (int) – Threads count. <=1 is loop mode, >=2 is threading mode. Default is 1.

  • interval (float) – Wait this time between the threading requests (seconds). Default is 0. Useful to optimize session spikes and achieve script stability in Docker with limited resources.

  • timeout (int) – Session timeout (seconds). Default is 60.

  • max_retries (int) – Retries the request multiple times if the Netbox API does not respond or responds with a timeout. Default is 0. This is useful for scheduled scripts in cron jobs, when the connection to Netbox server is not stable.

  • sleep (int) – Interval (seconds) before the next retry after session timeout reached. Default is 10.

  • strict (bool) – When querying objects by tag, if there are no tags present, the Netbox API response returns a status_code=400. True - HTTPError is raised when status_code=400. False - WARNING message is logged and an empty list is returned with status_code=200. Default is False.

  • extended_get (bool) – True - Extend filtering parameters in GET request, {parameter} can be used instead of {parameter}_id. Default is True.

  • loners (dict) – Set Filtering parameters in an OR manner.

Application/model connectors:

Variables:
app_models() List[Tuple[str, str]]

Get list of application model names.

Returns:

Application model names.

Return type:

List[Tuple[str, str]]

app_paths() List[str]

Get list of application/model paths.

Returns:

Application/model paths.

Return type:

List[str]

static apps() List[str]

Get list of application names.

Returns:

Applications.

Return type:

List[str]

connector_by_path(path: str) Connector

Get Connector instance by app/model path.

Parameters:

path – app/model path.

Returns:

Connector to the Netbox API endpoint.

Example:

NbApi().get_connector(“ipam/vrf”) -> VrfsC()

connectors() Generator[Connector, None, None]
Return generator of Connector instances ordered based on dependencies.

Connectors to models with the lowest count of dependencies will be first.

Returns:

Generator of Connector instances.

copy(**kwargs) NbApi

Create a duplicate of the object.

Parameters:

kwargs – Keyword arguments to replace in the original object.

Returns:

A copy of the current object.

create(**kwargs) Response

Create an object in Netbox using the app/model in the provided URL.

Parameters:

kwargs – Parameters for creating a new object.

The url and id parameters will be ignored.

Returns:

Session response.

  • <Response [201]> Object successfully created,

  • <Response [400]> Object already exists.

Return type:

Response

create_d(**kwargs) Dict[str, Any]

Create an object in Netbox using the app/model in the provided URL.

Parameters:

kwargs – Parameters for creating a new object.

The url and id parameters will be ignored.

Returns:

Data of newly created object.

Return type:

dict

delete(**kwargs) Response

Delete an object from Netbox using the ID in the provided URL.

Parameters:

kwargs – Parameters of the object to delete. Only the URL of the object is required.

Returns:

Session response.

  • <Response [204]> Object successfully deleted,

  • <Response [404]> Object not found.

Return type:

Response

get(**kwargs) List[Dict[str, Any]]

Request objects from Netbox using the app/model in the provided URL.

Parameters:

kwargs – Parameters of the object, only the URL is required.

Returns:

List of dictionaries containing Netbox objects.

Return type:

List[dict]

get_d(**kwargs) Dict[str, Any]

Request single object from Netbox using the app/model in the provided URL.

Parameters:

kwargs – Parameters of the object, only the URL with an ID is required.

Returns:

Dictionary containing Netbox object.

Return type:

dict

graphql(query: str) Response

Request data from Netbox GraphQL API.

Parameters:

query – GraphQL query string.

Returns:

Session response.

  • <Response [200]> - Request is successful or has syntax errors in the query.

Return type:

Response

property threads: int

Threads count.

update(**kwargs) Response

Update an object in Netbox using the app/model in the provided URL.

Parameters:
  • id (int) – Netbox object ID to update.

  • kwargs – Parameters to update an object in Netbox.

Returns:

Session response.

  • <Response [200]> Object successfully updated,

  • <Response [400]> Invalid data.

Return type:

Response

property url_api: str

Netbox URL to API endpoints.

version() str

Get Netbox version.

Returns:

Netbox version if version >= 3, otherwise an empty string.


Connector methods

class nbforager.api.connector.Connector(**kwargs)

Connector to Netbox entry point for different models.

For example, NbApi.ipam.ip_addresses.{method}, where {method} can be any of the described methods below.

create(**kwargs) Response

Create an object in Netbox.

Parameters:

kwargs – Parameters for creating a new object.

Returns:

Session response.

  • <Response [201]> Object successfully created,

  • <Response [400]> Object already exists.

Return type:

Response

create_d(**kwargs) Dict[str, Any]

Create an object in Netbox.

Parameters:

kwargs – Parameters for creating a new object.

Returns:

Data of newly created object.

Return type:

dict

delete(id: int) Response

Delete an object in Netbox.

Parameters:

id (int) – Object ID.

Returns:

Session response.

  • <Response [204]> Object successfully deleted,

  • <Response [404]> Object not found.

Return type:

Response

get(**kwargs) List[Dict[str, Any]]

Request data from Netbox using Schema ip_addresses.

The filtering parameters are identical to those in the web interface filter form. The value of each parameter can be either a single value or a list of multiple values.

Split the query to multiple requests if the URL length exceeds maximum length due to a long list of GET parameters.

Multithreading can be used to request a large amount of data rapidly, with intervals between threads (to optimize session spikes and achieve script stability in Docker with limited resources).

To determine the filtering parameters for various models, you can use:

Parameters:
  • or_{parameter} (list) – List of parameters that need to be requested in an OR manner, where {parameter} is the name of the Netbox REST API Schema ip_addresses.

  • kwargs – Netbox REST API Schema ip_addresses.

Returns:

List of dictionaries containing Netbox objects.

Return type:

List[dict]

get_count(**kwargs) int

Get the count of Netbox objects based on the provided filtering parameters.

Parameters:

kwargs – Filtering parameters.

Returns:

Count of Netbox objects based on the provided parameters.

Raises:

ValueError – If count for loners parameters is not supported.

graphql(fields: str, filters: str = '') List[Dict[str, Any]]

Request data from Netbox GraphQL API.

Parameters:
  • fields – Fields to include in the query, e.g. id name tenant { id name }.

  • filters – Parameters to filter Netbox objects, e.g. { status: STATUS_ACTIVE, name: {exact: "SITE1"}}.

Returns:

List of dictionaries containing GraphQL objects related to app/model.

Return type:

List[dict]

Raises:

HTTPError – Response status != 200 or contains ERROR messages.

update(**kwargs) Response

Update an object in Netbox.

Parameters:
  • id (int) – Netbox object ID to update.

  • kwargs – Parameters to update an object in Netbox.

Returns:

Session response.

  • <Response [200]> Object successfully updated,

  • <Response [400]> Invalid data.

Return type:

Response

update_d(**kwargs) Dict[str, Any]

Update an object in Netbox.

Parameters:
  • id (int) – Netbox object ID to update.

  • kwargs – Parameters to update an object in Netbox.

Returns:

Data of updated object.

Return type:

dict


Connector ipam.ip_addresses.get()

class nbforager.api.ip_addresses.IpAddressesC.get(self, **kwargs)

Request data from Netbox using Schema ip_addresses.

Only NbApi.ipam.ip_addresses.get() is described in this documentation. Other models are implemented in a similar manner. Exact parameters can be found in Schema.

NbApi parameters:

Parameters:

or_{parameter} (list) – List of parameters that need to be requested in an OR manner, where {parameter} is the name of the Netbox REST API Schema ip_addresses.

WEB UI Filter parameters:

Parameters:
  • q (str or List[str]) – IP address substring.

  • tag (str or List[str]) – Tag (slug).

Attributes:

Parameters:
  • parent (str or List[str]) – Parent Prefix. Addresses of this prefix.

  • family (int or List[int]) – Address family. IP version.

  • status (str or List[str]) – Status.

  • role (str or List[str]) – Role.

  • mask_length (int or List[int]) – Mask length.

  • assigned_to_interface (bool) – Assigned to an interface.

  • dns_name (str or List[str]) – DNS name.

VRF:

Parameters:
  • vrf (str or List[str]) – Assigned VRF name.

  • vrf_id (int or List[int]) – Assigned VRF object ID.

  • present_in_vrf (str or List[str]) – Present in VRF name.

  • present_in_vrf_id (int or List[int]) – Present in VRF object ID.

Tenant:

Parameters:
  • tenant_group (str or List[str]) – Tenant group name.

  • tenant_group_id (int or List[int]) – Tenant group object ID.

  • tenant (str or List[str]) – Tenant name.

  • tenant_id (int or List[int]) – Tenant object ID.

Device/VM:

Parameters:
  • device (str or List[str]) – Assigned Device name.

  • device_id (int or List[int]) – Assigned Device object ID.

  • virtual_machine (str or List[str]) – Assigned Virtual Machine name.

  • virtual_machine_id (int or List[int]) – Assigned Virtual Machine object ID.

Data Filter parameters:

Parameters:
  • id (int or List[int]) – Object ID.

  • address (str or List[str]) – IP address.

Text pattern:

Parameters:
  • description (str or List[str]) – Description exact value.

  • description_empty (bool) – Is empty.

  • description__ic (str or List[str]) – Case-insensitive contains.

  • description__ie (str or List[str]) – Case-insensitive exact.

  • description__iew (str or List[str]) – Case-insensitive ends with.

  • description__isw (str or List[str]) – Case-insensitive starts with.

  • description__n (str or List[str]) – Not case-sensitive.

  • description__nic (str or List[str]) – Not case-insensitive contains.

  • description__nie (str or List[str]) – Not case-insensitive exact.

  • description__niew (str or List[str]) – Not case-insensitive ends with.

  • description__nisw (str or List[str]) – Not case-insensitive starts with.

Date pattern:

Parameters:
  • created (str or List[str]) – Object created date.

  • created__empty (bool) – Is empty.

  • created__gt (str or List[str]) – Greater than.

  • created__gte (str or List[str]) – Greater than or equal.

  • created__lt (str or List[str]) – Less than.

  • created__lte (str or List[str]) – Less than or equal.

  • created__n (str or List[str]) – Not.


Extended filtering parameters

The mapped filtering parameters are identical to those in the web interface filter form and simplify the searching in Netbox. How it works? NbApi need be initialized with extended_get=True (default). When you are filtering by {parameter}, NbApi request all objects of the interested model, and then translate the interested {parameter} to {parameter}_id for the second request.

Note

In case the model has a large number of objects, searching by the mapped parameter could be slow.

NbApi

REST API

Parameter

Path

Parameter

Path

Key

circuit

any

circuit_id

circuits/circuits/

cid

provider

any

provider_id

circuits/providers/

name

provider_account

any

provider_account_id

circuits/provider-accounts/

name

device_type

any

device_type_id

dcim/device-types/

model

location

any

location_id

dcim/locations/

name

manufacturer

any

manufacturer_id

dcim/manufacturers/

name

platform

any

platform_id

dcim/platforms/

name

rack

any

rack_id

dcim/racks/

name

region

any

region_id

dcim/regions/

name

site

any

site_id

dcim/sites/

name

site_group

any

site_group_id

dcim/site-groups/

name

content_type

any

content_type_id

extras/content-types/

display

for_object_type

any

for_object_type_id

extras/content-types/

display

export_target

any

export_target_id

ipam/route-targets/

name

exporting_vrf

any

exporting_vrf_id

ipam/vrfs/

name

import_target

any

import_target_id

ipam/route-targets/

name

importing_vrf

any

importing_vrf_id

ipam/vrfs/

name

present_in_vrf

any

present_in_vrf_id

ipam/vrfs/

name

rir

any

rir_id

ipam/rirs/

name

vrf

any

vrf_id

ipam/vrfs/

name

tenant

any

tenant_id

tenancy/tenants/

name

tenant_group

any

tenant_group_id

tenancy/tenant-groups/

name

bridge

any

bridge_id

virtualization/interfaces/

name

group

dcim/sites/

group_id

dcim/site-groups/

name

group

ipam/vlans/

group_id

ipam/vlan-groups/

name

group

tenancy/tenants/

group_id

tenancy/tenant-groups/

name

group

virtualization/clusters/

group_id

virtualization/cluster-groups/

name

parent

dcim/locations/

parent_id

dcim/locations/

name

parent

dcim/regions/

parent_id

dcim/regions/

name

parent

dcim/site-groups/

parent_id

dcim/site-groups/

name

parent

tenancy/tenant-groups/

parent_id

tenancy/tenant-groups/

name

parent

virtualization/interfaces/

parent_id

virtualization/interfaces/

name

role

dcim/devices/

role_id

dcim/device-roles/

name

role

dcim/racks/

role_id

dcim/rack-roles/

name

role

ipam/

role_id

ipam/roles/

name

role

virtualization/virtual-machines/

role_id

dcim/device-roles/

name

type

circuits/circuits/

type_id

circuits/circuit-types/

name


Filtering parameters in an OR manner

Netbox REST API processes filtering parameters in different manners. They can be processed using OR, AND or loners, where loners means only one parameter can be processed (processing only the last in the list). Viewed through the lens of Netbox3, loners is useless and could be processed using an OR operator. If you meet the loners parameters, the Netbox API may return improperly filtered objects #14305. I have not checked all endpoints, so if you encounter this issue, please let me know so that I can fix it in NbApi. As a workaround, you can use or_{parameter} in filtering parameters or set custom loners to change NbApi default behavior.

Path

Parameter

any

q

ipam/aggregates

prefix

ipam/aggregates

within_include

extras/content-types

app_label, id, model

Example of how to change loners