Skip to content

Endpoint

pynautobot.core.endpoint

Provides classes and functions for interacting with the Nautobot API endpoints.

pynautobot.core.endpoint.DetailEndpoint

Enables read/write Operations on detail endpoints.

Endpoints like available-ips that are detail routes off traditional endpoints are handled with this class.

__init__(parent_obj, name, custom_return=None)

Initialize the DetailEndpoint object.

create(data=None, api_version=None)

The write operation for a detail endpoint.

Creates objects on a detail endpoint in Nautobot.

Parameters:

Name Type Description Default
data dict or list

A dictionary containing the key/value pairs of the items you're creating on the parent object. Defaults to an empty dict, which will create a single item with default values.

None
api_version str

Override default or globally set Nautobot REST API version for this single request.

None

Returns:

Type Description
Union[Dict, List[Dict]]

A dictionary or list of dictionaries representing the items created in Nautobot.

list(api_version=None, **kwargs)

The view operation for a detail endpoint.

Returns the response from Nautobot for a detail endpoint.

Parameters:

Name Type Description Default
api_version str

Override default or globally set Nautobot REST API version for this single request.

None
**kwargs dict

Key/value pairs that get converted into URL parameters when passed to the endpoint. E.g. .list(method='get_facts') would be converted to .../?method=get_facts.

{}

Returns:

Type Description
Union[Dict, List[Dict]]

A dictionary or list of dictionaries retrieved from Nautobot.

pynautobot.core.endpoint.Endpoint

Represent actions available on endpoints in the Nautobot API.

Takes name and app passed from App() and builds the correct URL to make queries to and the proper Response object to return results in.

Parameters:

Name Type Description Default
api object

Takes Api created at instantiation.

required
app object

Takes App.

required
name str

Name of endpoint passed to App().

required
model object

Custom model for given app.

None
Note

In order to call Nautobot endpoints with dashes in their names you should convert the dash to an underscore. (E.g. querying the ip-addresses endpoint is done with nb.ipam.ip_addresses.all().)

__init__(api, app, name, model=None)

Initialize the Endpoint object.

all(*args, **kwargs)

Queries the 'ListView' of a given endpoint.

Returns all objects from an endpoint.

Optional Args

api_version (str, optional): Override default or globally-set Nautobot REST API version for this single request. limit (int, optional): Overrides the max page size on paginated returns. This defines the number of records that will be returned with each query to the Netbox server. The queries will be made as you iterate through the result set. offset (int, optional): Overrides the offset on paginated returns.

Returns:

Type Description
list

List of :py:class:.Record objects.

Examples:

>>> nb.dcim.devices.all()
[test1-a3-oobsw2, test1-a3-oobsw3, test1-a3-oobsw4]

bulk_update(objects)

This method is called from the update() method if a bulk update is detected.

Allows for bulk updating of existing objects on an endpoint. Objects is a list which contain either JSON/dicts or Record derived objects, which contain the updates to apply. If JSON/dicts are used, then the id of the object must be included.

Parameters:

Name Type Description Default
objects list

A list of dicts or a list of Record.

required

choices(api_version=None)

Returns all choices from the endpoint.

The returned dict is also saved in the endpoint object (in _choices attribute) so that later calls will return the same data without recurring requests to Nautobot. When using .choices() in long-running applications, consider restarting them whenever Nautobot is upgraded, to prevent using stale choices data.

Parameters:

Name Type Description Default
api_version str

Override default or globally-set Nautobot REST API version for this single request.

None

Returns:

Type Description
dict

Dict containing the available choices.

Example (from Nautobot 2.8.x): >>> from pprint import pprint >>> pprint(nb.ipam.ip_addresses.choices()) {'role': [{'display_name': 'Loopback', 'value': 'loopback'}, {'display_name': 'Secondary', 'value': 'secondary'}, {'display_name': 'Anycast', 'value': 'anycast'}, {'display_name': 'VIP', 'value': 'vip'}, {'display_name': 'VRRP', 'value': 'vrrp'}, {'display_name': 'HSRP', 'value': 'hsrp'}, {'display_name': 'GLBP', 'value': 'glbp'}, {'display_name': 'CARP', 'value': 'carp'}], 'status': [{'display_name': 'Active', 'value': 'active'}, {'display_name': 'Reserved', 'value': 'reserved'}, {'display_name': 'Deprecated', 'value': 'deprecated'}, {'display_name': 'DHCP', 'value': 'dhcp'}]}

count(*args, api_version=None, **kwargs)

Returns the count of objects in a query.

Takes named arguments that match the usable filters on a given endpoint. If an argument is passed then it's used as a freeform search argument if the endpoint supports it. If no arguments are passed the count for all objects on an endpoint are returned.

Parameters:

Name Type Description Default
*args str

Freeform search string that's accepted on given endpoint.

()
**kwargs str

Any search argument the endpoint accepts can be added as a keyword arg.

{}
api_version str

Override default or globally-set Nautobot REST API version for this single request.

None

Returns:

Type Description
int

Integer with count of objects returned by query.

Examples:

To return a count of objects matching a named argument filter.

>>> nb.dcim.devices.count(site='tst1')
5827

To return a count of objects on an entire endpoint.

>>> nb.dcim.devices.count()
87382

create(*args, api_version=None, **kwargs)

Creates an object on an endpoint.

Allows for the creation of new objects on an endpoint. Named arguments are converted to JSON properties, and a single object is created. Nautobot's bulk creation capabilities can be used by passing a list of dictionaries as the first argument.

Note

Any positional arguments will supersede named ones.

Parameters:

Name Type Description Default
*args list

A list of dictionaries containing the properties of the objects to be created.

()
**kwargs str

Key/value strings representing properties on a JSON object.

{}
api_version str

Override default or globally-set Nautobot REST API version for this single request.

None

Returns:

Type Description
Union[Record, List[Record]]

A list or single :py:class:.Record object depending on whether a bulk creation was requested.

Examples:

Creating an object on the devices endpoint you can look up a device_role's name with:

>>> nautobot.dcim.devices.create(
...    name='test',
...    device_role=1,
... )

Use bulk creation by passing a list of dictionaries:

>>> nb.dcim.devices.create([
...     {
...         "name": "test1-core3",
...         "device_role": 3,
...         "site": 1,
...         "device_type": 1,
...         "status": 1
...     },
...     {
...         "name": "test1-core4",
...         "device_role": 3,
...         "site": 1,
...         "device_type": 1,
...         "status": 1
...     }
... ])

delete(objects)

Bulk deletes objects on an endpoint.

Allows for batch deletion of multiple objects from a single endpoint.

Parameters:

Name Type Description Default
objects list

A list of either IDs or Records to delete.

required

Returns:

Type Description
bool

True if bulk DELETE operation was successful.

Examples:

Deleting all devices:

>>> pynautobot.dcim.devices.delete(pynautobot.dcim.devices.all())

Use bulk deletion by passing a list of IDs:

>>> pynautobot.dcim.devices.delete([
...     "db8770c4-61e5-4999-8372-e7fa576a4f65",
...     "e9b5f2e0-4f20-41ad-9179-90a4987f743e"
... ])

Use bulk deletion to delete objects e.g. when filtering on a custom_field:

>>> pynautobot.dcim.devices.delete([
...     d for d in pynautobot.dcim.devices.all()
...     if d.custom_fields.get("field", False)
... ])

filter(*args, api_version=None, **kwargs)

Queries the 'ListView' of a given endpoint.

Takes named arguments that match the usable filters on a given endpoint. If an argument is passed then it's used as a freeform search argument if the endpoint supports it.

Parameters:

Name Type Description Default
*args str

Freeform search string that's accepted on given endpoint.

()
**kwargs str

Any search argument the endpoint accepts can be added as a keyword arg.

{}
api_version str

Override default or globally-set Nautobot REST API version for this single request.

None

Returns:

Type Description
list

A list of :py:class:.Record objects.

Examples:

To return a list of objects matching a named argument filter.

>>> nb.dcim.devices.filter(role='leaf-switch')
[test1-a3-tor1b, test1-a3-tor1c, test1-a3-tor1d, test1-a3-tor2a]

Using a freeform query along with a named argument.

>>> nb.dcim.devices.filter('a3', role='leaf-switch')
[test1-a3-tor1b, test1-a3-tor1c, test1-a3-tor1d, test1-a3-tor2a]

Chaining multiple named arguments.

>>> nb.dcim.devices.filter(role='leaf-switch', status=True)
[test1-leaf2]

Passing a list as a named argument adds multiple filters of the same value.

>>> nb.dcim.devices.filter(role=['leaf-switch', 'spine-switch'])
[test1-a3-spine1, test1-a3-spine2, test1-a3-leaf1]

get(*args, **kwargs)

Queries the DetailsView of a given endpoint.

Optional Args

key (int, optional): ID for the item to be retrieved. **kwargs (str, optional): Accepts the same keyword args as filter(). Any search argument the endpoint accepts can be added as a keyword arg. api_version (str, optional): Override default or globally-set Nautobot REST API version for this single request.

Returns:

Type Description
Union[Record, None]

A single :py:class:.Record object or None.

Raises:

Type Description
ValueError

If kwarg search returns more than one value.

Examples:

Referencing with a kwarg that only returns one value.

>>> nb.dcim.devices.get(name='test1-a3-tor1b')
test1-a3-tor1b

Referencing with an id.

>>> nb.dcim.devices.get(1)
test1-edge1

update(id, data=None)

Update a single resource with a dictionary or bulk update a list of objects.

Allows for bulk updating of existing objects on an endpoint. Objects is a list which contain either JSON/dicts or Record derived objects, which contain the updates to apply. If JSON/dicts are used, then the id of the object must be included.

Parameters:

Name Type Description Default
id (string, list)

Identifier of the object being updated OR list of JSON/dicts or Record objects containing updates to apply.

required
data dict

Key/value pairs to update the record object with, ignored in the case of a list to id.

None

Returns:

Type Description
Union[bool, List[Record]]

A list of :py:class:.Record objects or a boolean depending on whether a bulk update was requested.

Examples:

Accepts the id of the object that needs to be updated as well as a dictionary of k/v pairs used to update an object.

>>> ret = nb.dcim.devices.update(id="0238a4e3-66f2-455a-831f-5f177215de0f", data={
...     "name": "test",
...     "serial": "1234",
...     "location": "9b1f53c7-89fa-4fb2-a89a-b97364fef50c",
... })
>>> ret
True

Use bulk update by passing a list of dicts:

>>> devices = nb.dcim.devices.update([
...    {'id': "db8770c4-61e5-4999-8372-e7fa576a4f65", 'name': 'test'},
...    {'id': "e9b5f2e0-4f20-41ad-9179-90a4987f743e", 'name': 'test2'},
... ])
>>> devices
[test, test2]

Use bulk update by passing a list of Records:

>>> devices = list(nb.dcim.devices.filter())
>>> devices
[Device1, Device2, Device3]
>>> for d in devices:
...     d.name = d.name+'-test'
...
>>> devices = nb.dcim.devices.update(devices)
>>> devices
[Device1-test, Device2-test, Device3-test]

pynautobot.core.endpoint.GraphqlEndpoint

Bases: Endpoint

Extend Endpoint class to support run method for graphql queries.

run(query_id, *args, **kwargs)

Runs a saved graphql query based on the query_id provided.

Takes a kwarg of query_id to specify the query that should be run.

Parameters:

Name Type Description Default
*args str

Used as payload for POST method to the API if provided.

()
**kwargs str

Any additional argument the endpoint accepts can be added as a keyword arg.

{}
query_id (str, required)

The UUID of the query object that is being ran.

required

Returns:

Type Description
Response

An API response from the execution of the saved graphql query.

Examples:

To run a query no variables:

>>> query = nb.extras.graphql_queries.get("Example")
>>> query.run()

To run a query with variables as kwarg:

>>> query = nb.extras.graphql_queries.get("Example")
>>> query.run(
        variables={"foo": "bar"})
    )

To run a query with JSON payload as an arg:

>>> query = nb.extras.graphql_queries.get("Example")
>>> query.run(
        {"variables":{"foo":"bar"}}
    )

pynautobot.core.endpoint.JobsEndpoint

Bases: Endpoint

Extend Endpoint class to support run method only for jobs.

run(*args, api_version=None, **kwargs)

Runs a job based on the class_path provided to the job.

Takes a kwarg of class_path or job_id to specify the job that should be run.

Parameters:

Name Type Description Default
*args str

Freeform search string that's accepted on given endpoint.

()
**kwargs str

Any search argument the endpoint accepts can be added as a keyword arg.

{}
api_version str

Override default or globally-set Nautobot REST API version for this single request.

None

Returns:

Name Type Description
obj str

Job details: job_result object uuid found at obj.result.id.

Examples:

To run a job for verifying hostnames:

>>> nb.extras.jobs.run(
        class_path="local/data_quality/VerifyHostnames",
        data={"hostname_regex": ".*"},
        commit=True,
    )

run_and_wait(*args, api_version=None, interval=5, max_rechecks=50, **kwargs)

Runs a job and waits for the response.

Parameters:

Name Type Description Default
*args str

Freeform search string that's accepted on given endpoint.

()
**kwargs str

Any search argument the endpoint accepts can be added as a keyword arg.

{}
api_version str

Override default or globally-set Nautobot REST API version for this single request.

None
interval int

Time in seconds to wait between checking job results.

5
max_rechecks int

Number of times to check job result before exiting the method.

50

Returns:

Name Type Description
obj str

Job details: job_result object uuid found at obj.result.id.

Examples:

To run a job for verifying hostnames:

>>> response = nb.extras.jobs.run_and_wait(
        class_path="local/data_quality/VerifyHostnames",
        data={"hostname_regex": ".*"},
        commit=True,
        interval=5,
        max_rechecks=10,
    )
>>> print(f"Job completed, Job Result ID: {response.job_result.id}")
Job completed, Job Result ID: 123

pynautobot.core.endpoint.RODetailEndpoint

Bases: DetailEndpoint

Enables read-only Operations on detail endpoints.

create(data=None, api_version=None)

Raises a NotImplementedError for read-only endpoints.

pynautobot.core.endpoint.response_loader(req, return_obj, endpoint)

Loads the response from the API into an object.