Skip to content

Creating a Pynautobot Instance

To start using pynautobot, instantiate an Api object, passing in the proper URL and a valid Token. The code sample below assumes that the token has been stored as an environment variable, and uses the builtin os module to retrieve it.

Note

To display dictionaries or other objects in examples, the pprint package is used. To install it run pip install pprint.

>>> import os
>>>
>>> from pprint import pprint
>>>
>>> from pynautobot import api
>>>
>>> url = "https://next.demo.nautobot.com"
>>>
>>> # Retrieve token from system environment variable
>>> # token = os.environ["NAUTOBOT_TOKEN"]
>>> token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
>>> nautobot = api(url=url, token=token)
>>> nautobot
<pynautobot.core.api.Api object at ...>

Tip

Creating a token in Nautobot.

Nautobot Info and Apps

The nautobot object returned above is the main entrypoint to interact with the Nautobot REST API. This object provides access to general information about the Nautobot system, and the core Apps and Plugins.

The core Apps are:

  • circuits
  • cloud
  • data_validation
  • dcim
  • extras
  • ipam
  • load_balancers
  • tenancy
  • users
  • virtualization
  • vpn
  • wireless
>>> nautobot = api(url=url, token=token)
>>>
>>> # View version of Nautobot
>>> nautobot.version
'2.0'
>>>
>>> # View various details about Nautobot
>>> pprint(nautobot.status())
{'celery-workers-running': 0,
 'django-version': '3.2.21',
 'installed-apps': {'constance': '2.9.1',
                    'constance.backends.database': None,
                    'corsheaders': None,
                    'db_file_storage': None,
                    'debug_toolbar': '4.1.0',
                    'django.contrib.admin': None,
                    'django.contrib.auth': None,
                    'django.contrib.contenttypes': None,
                    'django.contrib.humanize': None,
                    'django.contrib.messages': None,
                    'django.contrib.sessions': None,
                    'django.contrib.staticfiles': None,
                    'django_ajax_tables': None,
                    'django_celery_beat': '2.5.0..',
                    'django_celery_results': '2.4.0..',
                    'django_extensions': '3.2.3',
                    'django_filters': '23.1',
                    'django_jinja': '3.2.21.final.0',
                    'django_prometheus': '2.3.1',
                    'django_tables2': '2.6.0',
                    'drf_spectacular': '0.26.3',
                    'drf_spectacular_sidecar': '2023.9.1',
                    'example_plugin': '1.0.0',
                    'graphene_django': '2.16.0',
                    'health_check': None,
                    'health_check.storage': None,
                    'nautobot.circuits': None,
                    'nautobot.core': None,
                    'nautobot.dcim': None,
                    'nautobot.extras': None,
                    'nautobot.extras.tests.example_plugin_dependency': None,
                    'nautobot.ipam': None,
                    'nautobot.tenancy': None,
                    'nautobot.users': None,
                    'nautobot.virtualization': None,
                    'rest_framework': '3.14.0',
                    'social_django': '5.2.0',
                    'taggit': '4.0.0',
                    'timezone_field': '5.1'},
 'nautobot-version': '2.0.0',
 'plugins': {'example_plugin': '1.0.0'},
 'python-version': '3.8.18'}
>>> 
>>> # Show that the dcim app is available
>>> nautobot.dcim
<pynautobot.core.app.App object at ...>

The main purpose of App objects is to provide access to Models and their data.

Models

Pynautobot App objects will treat all unknown attributes as Endpoints. The Endpoint class is used to represent Models in Nautobot. For example, the Nautobot DCIM App contains Models, such as: Devices, Platforms, and Roles. The pynautobot dcim App does not provide attributes to represent these Models, however, Endpoint objects are created upon attribute access.

The code sample below shows that Models do not exist in the nautobot.dcim attribute dictionary, but the devices Model is still accessible from it.

>>> nautobot = api(url=url, token=token)
>>>
>>> # Show that the devices attribute does not exist on the dcim object
>>> pprint(nautobot.dcim.__dict__)
{'_choices': None,
 'api': <pynautobot.core.api.Api object at ...>,
 'model': <module 'pynautobot.models.dcim' from '/opt/ntc/nautobot/pynautobot/pynautobot/models/dcim.py'>,
 'name': 'dcim'}
>>> 
>>> # Show that the devices attribute is accessible and
>>> # is an Endpoint object corresponding to the Devices Model
>>> devices = nautobot.dcim.devices
>>> devices
<pynautobot.core.endpoint.Endpoint object at ...>
>>> devices.url
'https://next.demo.nautobot.com/api/dcim/devices'

Note

Since Models are evaluated lazily, using the builtin dir and help functions on the Apps will not provide any information regarding the available Models.

Some Models in Nautobot have names that contain more than a single word. In order to access these Models, the names should be joined with an underscore. The above example of Roles would use roles. Pynautobot will automatically convert the underscore into a hyphen for access to the Nautobot API endpoint.

>>> nautobot = api(url=url, token=token)
>>>
>>> # Show using an underscore to access Models with multi-word names.
>>> roles = nautobot.extras.roles
>>>
>>> # Show that the URL converts the underscore to a hyphen
>>> roles.url
'https://next.demo.nautobot.com/api/extras.roles'

Note

Attributes are not checked against the Nautobot API, so misspelled or non-existent Models will not raise an Exception until a CRUD operation is attempted on the returned object.

For example, calling nautobot.dcim.device (missing the trailing s) will return an Endpoint object. However, the URL assigned to the Endpoint will not be a valid Nautobot API endpoint, and performing any CRUD operations against that URL will result in an Exception being raised.

Rate Limiting

Nautobot 3.3 added optional rate limiting for the REST API. When it is set to enforce mode, a request that exceeds the token's budget is rejected with HTTP 429 and a Retry-After header giving the number of seconds to wait.

By default, retries is 0 and pynautobot does not retry: an HTTP 429 response raises a RequestError right away. Set retries when creating the Api object to retry automatically. On an HTTP 429 response, pynautobot waits the number of seconds given in Retry-After before trying again. If every retry fails, a RetriesExhaustedError is raised. It is a RequestError, so existing error handling keeps working.

Once the retries are used up, waiting longer in the same process is rarely the right answer. The error's rate_limit attribute describes the budget that was exceeded, so you can stop cleanly and report what limit the script ran into:

>>> import sys
>>> import pynautobot
>>>
>>> nautobot = pynautobot.api(url=url, token=token, retries=3)
>>> try:
...     devices = nautobot.dcim.devices.all()
... except pynautobot.RetriesExhaustedError as e:
...     limit = e.rate_limit
...     sys.exit(f"Used the Nautobot budget of {limit.quota} per {limit.window} seconds; reduce the request load or ask for a higher budget.")
...
Used the Nautobot budget of 1000 per 60 seconds; reduce the request load or ask for a higher budget.

When rate limiting is in report or enforce mode, Nautobot also reports the remaining budget on every response. pynautobot keeps the most recent values in the rate_limit property of the Api object returned by pynautobot.api() (the nautobot variable in these examples). It holds a RateLimit object, or None when connected to Nautobot versions before 3.3 or when rate limiting is turned off.

>>> nautobot = pynautobot.api(url=url, token=token)
>>> nautobot.dcim.devices.all()
>>> nautobot.rate_limit
RateLimit(policy='rest-complexity-cost', quota=1000, window=60, remaining=996, reset=60, cost=4, retry_after=None)
>>> nautobot.rate_limit.remaining
996

Note

Api.rate_limit is updated by a hook on the session pynautobot creates. If you replace the Api object's http_session with your own session, Api.rate_limit is no longer updated, but RequestError.rate_limit is still set on failed requests.