Skip to content

Response

This page documents the classes that wrap responses returned by NetBox: Record (a single object) and RecordSet (a lazy collection of records).

Record Class

A Record represents a single object returned by the NetBox API. API fields are exposed as attributes; nested objects are recursively wrapped as their own Record instances. Records returned from a list endpoint are initially "shallow" — accessing an attribute not present in the list response causes pynetbox to fetch the full detail view on demand.

pynetbox.core.response.Record

Create Python objects from NetBox API responses.

Creates an object from a NetBox response passed as values. Nested dicts that represent other endpoints are also turned into Record objects. All fields are then assigned to the object's attributes. If a missing attr is requested (e.g. requesting a field that's only present on a full response on a Record made from a nested response) then pynetbox will make a request for the full object and return the requested value.

A subclass declares field type markers as class attributes (e.g. device_type = DeviceTypes, users = [Users], config_context = JsonField) to set how each field is parsed. Record.init_subclass wraps the markers, so declare them in the class body. If the payload omits a marker field, Record loads it like any other missing field.

Examples

Default representation of the object is usually its name:

x = nb.dcim.devices.get(1)
x
# test1-switch1

Querying a string field:

x = nb.dcim.devices.get(1)
x.serial
# 'ABC123'

Querying a field on a nested object:

x = nb.dcim.devices.get(1)
x.device_type.model
# 'QFX5100-24Q'

Casting the object as a dictionary:

from pprint import pprint
pprint(dict(x))
{
    'asset_tag': None,
    'cluster': None,
    'comments': '',
    'config_context': {},
    'created': '2018-04-01',
    'custom_fields': {},
    'role': {
        'id': 1,
        'name': 'Test Switch',
        'slug': 'test-switch',
        'url': 'http://localhost:8000/api/dcim/device-roles/1/'
    },
    'device_type': {...},
    'display_name': 'test1-switch1',
    'face': {'label': 'Rear', 'value': 1},
    'id': 1,
    'name': 'test1-switch1',
    'parent_device': None,
    'platform': {...},
    'position': 1,
    'primary_ip': {
        'address': '192.0.2.1/24',
        'family': 4,
        'id': 1,
        'url': 'http://localhost:8000/api/ipam/ip-addresses/1/'
    },
    'primary_ip4': {...},
    'primary_ip6': None,
    'rack': {
        'display_name': 'Test Rack',
        'id': 1,
        'name': 'Test Rack',
        'url': 'http://localhost:8000/api/dcim/racks/1/'
    },
    'site': {
        'id': 1,
        'name': 'TEST',
        'slug': 'TEST',
        'url': 'http://localhost:8000/api/dcim/sites/1/'
    },
    'status': {'label': 'Active', 'value': 1},
    'tags': [],
    'tenant': None,
    'vc_position': None,
    'vc_priority': None,
    'virtual_chassis': None
}

Iterating over a Record object:

for i in x:
    print(i)

# ('id', 1)
# ('name', 'test1-switch1')
# ('display_name', 'test1-switch1')
Source code in pynetbox/core/response.py
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
class Record:
    """Create Python objects from NetBox API responses.

    Creates an object from a NetBox response passed as `values`.
    Nested dicts that represent other endpoints are also turned
    into Record objects. All fields are then assigned to the
    object's attributes. If a missing attr is requested
    (e.g. requesting a field that's only present on a full response on
    a Record made from a nested response) then pynetbox will make a
    request for the full object and return the requested value.

    A subclass declares field type markers as class attributes (e.g.
    `device_type = DeviceTypes`, `users = [Users]`,
    `config_context = JsonField`) to set how each field is parsed.
    Record.__init_subclass__ wraps the markers, so declare them in the
    class body. If the payload omits a marker field, Record loads it
    like any other missing field.

    ## Examples

    Default representation of the object is usually its name:

    ```python
    x = nb.dcim.devices.get(1)
    x
    # test1-switch1
    ```

    Querying a string field:

    ```python
    x = nb.dcim.devices.get(1)
    x.serial
    # 'ABC123'
    ```

    Querying a field on a nested object:

    ```python
    x = nb.dcim.devices.get(1)
    x.device_type.model
    # 'QFX5100-24Q'
    ```

    Casting the object as a dictionary:

    ```python
    from pprint import pprint
    pprint(dict(x))
    {
        'asset_tag': None,
        'cluster': None,
        'comments': '',
        'config_context': {},
        'created': '2018-04-01',
        'custom_fields': {},
        'role': {
            'id': 1,
            'name': 'Test Switch',
            'slug': 'test-switch',
            'url': 'http://localhost:8000/api/dcim/device-roles/1/'
        },
        'device_type': {...},
        'display_name': 'test1-switch1',
        'face': {'label': 'Rear', 'value': 1},
        'id': 1,
        'name': 'test1-switch1',
        'parent_device': None,
        'platform': {...},
        'position': 1,
        'primary_ip': {
            'address': '192.0.2.1/24',
            'family': 4,
            'id': 1,
            'url': 'http://localhost:8000/api/ipam/ip-addresses/1/'
        },
        'primary_ip4': {...},
        'primary_ip6': None,
        'rack': {
            'display_name': 'Test Rack',
            'id': 1,
            'name': 'Test Rack',
            'url': 'http://localhost:8000/api/dcim/racks/1/'
        },
        'site': {
            'id': 1,
            'name': 'TEST',
            'slug': 'TEST',
            'url': 'http://localhost:8000/api/dcim/sites/1/'
        },
        'status': {'label': 'Active', 'value': 1},
        'tags': [],
        'tenant': None,
        'vc_position': None,
        'vc_priority': None,
        'virtual_chassis': None
    }
    ```

    Iterating over a Record object:

    ```python
    for i in x:
        print(i)

    # ('id', 1)
    # ('name', 'test1-switch1')
    # ('display_name', 'test1-switch1')
    ```
    """

    url = None

    # Internal Record metadata that should not be serialized for API updates.
    # These are object bookkeeping attributes, not NetBox API fields.
    _INTERNAL_ATTRS = frozenset(
        [
            "_api",  # API client instance
            "_endpoint",  # Endpoint object reference
            "url",  # Object URL (read-only field provided by API)
            "_has_details",  # Flag for lazy-loading full details
            "_default_ret",  # Default Record class for nested objects
        ]
    )

    # Old public names of the internal attributes above, kept as deprecated
    # aliases (#170). Resolved in __getattr__ so a NetBox field of the same
    # name still wins.
    _LEGACY_ALIASES = {
        "api": "_api",
        "endpoint": "_endpoint",
        "has_details": "_has_details",
        "default_ret": "_default_ret",
    }

    def __init_subclass__(cls, **kwargs):
        """Wrap each field type marker in the class body in a _FieldTypeMarker.

        The parent class already wraps inherited markers. This method does
        not see a marker set after class creation or declared on a
        non-Record mixin, and does not run if a subclass skips super().
        """
        super().__init_subclass__(**kwargs)
        for name, value in list(vars(cls).items()):
            if name.startswith("__") and name.endswith("__"):
                continue
            if _is_field_type_marker(value):
                setattr(cls, name, _FieldTypeMarker(name, value))

    def __init__(self, values, api, endpoint):
        self._has_details = False
        # Every re-parse refreshes this, not only __init__. _diff() compares
        # current values to it (#813).
        self._init_cache = {}
        self._api = api
        self._default_ret = Record
        self._endpoint = (
            self._endpoint_from_url(values["url"])
            if values and "url" in values and values["url"]
            else endpoint
        )
        if values:
            self._parse_values(values)

    def __getattr__(self, k):
        """Default behavior for missing attrs.

        We'll call `full_details()` if we're asked for an attribute
        we don't have.

        In order to prevent non-explicit behavior,`k='keys'` is
        excluded because casting to dict() calls this attr.

        Dunder attributes are excluded as well: they are never NetBox
        fields, and probing for them (e.g. pydantic's isinstance check
        calling `hasattr(obj, '__pydantic_decorators__')`, or copy and
        pickle machinery) must not trigger a network fetch that would
        also clobber local modifications.

        The pre-#170 names of the internal attributes (`api`, `endpoint`,
        `has_details`, `default_ret`) resolve here, with a
        DeprecationWarning. Because __getattr__ only runs when normal
        lookup fails, a NetBox field with one of those names takes
        precedence over the alias.
        """
        if k.startswith("__") and k.endswith("__"):
            raise AttributeError('object has no attribute "{}"'.format(k))

        if k in self._LEGACY_ALIASES:
            new_name = self._LEGACY_ALIASES[k]
            warnings.warn(
                "Record.{} is deprecated; use Record.{} instead.".format(k, new_name),
                DeprecationWarning,
                stacklevel=2,
            )
            return object.__getattribute__(self, new_name)

        if self.url:
            if self._has_details is False and k != "keys":
                if self.full_details():
                    # Unlike self.__dict__, this re-runs properties that raised
                    # before hydration. Unlike getattr(), it skips __getattr__.
                    try:
                        return object.__getattribute__(self, k)
                    except AttributeError:
                        pass

        raise AttributeError('object has no attribute "{}"'.format(k))

    def __iter__(self):
        # The caller's loop body can hydrate the record, which adds keys to
        # _init_cache (#813).
        for i in list(self._init_cache):
            cur_attr = getattr(self, i)
            if isinstance(cur_attr, Record):
                yield i, dict(cur_attr)
            elif isinstance(cur_attr, list) and all(
                isinstance(i, (Record, GenericListObject)) for i in cur_attr
            ):
                yield i, [dict(x) for x in cur_attr]
            else:
                yield i, cur_attr

    def __getitem__(self, k):
        return dict(self)[k]

    def __str__(self):
        return (
            getattr(self, "name", None)
            or getattr(self, "label", None)
            or getattr(self, "display", None)
            or ""
        )

    def __repr__(self):
        return str(self)

    def __getstate__(self):
        return self.__dict__

    def __setstate__(self, d):
        self.__dict__.update(d)

    def __key__(self):
        if hasattr(self, "id"):
            return (self._endpoint.name, self.id)
        return self._endpoint.name

    def __hash__(self):
        return hash(self.__key__())

    def __eq__(self, other):
        if isinstance(other, Record):
            return self.__key__() == other.__key__()
        return NotImplemented

    def _extract_app_endpoint(self, url):
        """Extract app/endpoint from a NetBox API URL.

        Extracts the app and endpoint portion from a URL like:
            https://netbox/api/dcim/rear-ports/12761/
        Returns:
            String like "dcim/rear-ports"
        """
        app_endpoint = "/".join(
            urlsplit(url).path[len(urlsplit(self._api.base_url).path) :].split("/")[1:3]
        )
        return app_endpoint

    def _get_obj_class(self, url):
        """Map API URL to corresponding Record class for cable tracing.

        Used by TraceableRecord and PathableRecord to deserialize objects
        encountered in cable trace/path responses.
        """
        # Import here to avoid circular dependency
        from pynetbox.models.circuits import CircuitTerminations
        from pynetbox.models.dcim import (
            Cables,
            ConsolePorts,
            ConsoleServerPorts,
            FrontPorts,
            Interfaces,
            PowerFeeds,
            PowerOutlets,
            PowerPorts,
            RearPorts,
        )

        uri_to_obj_class_map = {
            "circuits/circuit-terminations": CircuitTerminations,
            "dcim/cables": Cables,
            "dcim/console-ports": ConsolePorts,
            "dcim/console-server-ports": ConsoleServerPorts,
            "dcim/front-ports": FrontPorts,
            "dcim/interfaces": Interfaces,
            "dcim/power-feeds": PowerFeeds,
            "dcim/power-outlets": PowerOutlets,
            "dcim/power-ports": PowerPorts,
            "dcim/rear-ports": RearPorts,
        }

        app_endpoint = self._extract_app_endpoint(url)
        return uri_to_obj_class_map.get(app_endpoint, Record)

    def _add_cache(self, item):
        key, value = item
        self._init_cache[key] = get_return(value)

    def _parse_values(self, values):
        """Parses values init arg.

        Parses values dict at init and sets object attributes with the
        values within.
        """

        def generic_list_parser(key_name, list_item):
            from pynetbox.models.mapper import CONTENT_TYPE_MAPPER

            content_type_mapper = getattr(
                self._api, "_content_type_mapper", CONTENT_TYPE_MAPPER
            )

            if (
                isinstance(list_item, dict)
                and "object_type" in list_item
                and "object" in list_item
            ):
                lookup = list_item["object_type"]
                if model := content_type_mapper.get(lookup, None):
                    record = model(list_item["object"], self._api, self._endpoint)
                    return GenericListObject(record)

            return list_item

        def list_parser(key_name, list_item):
            if isinstance(list_item, dict):
                lookup = getattr(self.__class__, key_name, None)
                if not isinstance(lookup, list):
                    # This is *list_parser*, so if the custom model field is not
                    # a list (or is not defined), just return the default model
                    return self._default_ret(list_item, self._api, self._endpoint)
                model = lookup[0]
                return model(list_item, self._api, self._endpoint)

            return list_item

        def sibling_typed_list_parser(list_item, content_type):
            from pynetbox.models.mapper import CONTENT_TYPE_MAPPER

            content_type_mapper = getattr(
                self._api, "_content_type_mapper", CONTENT_TYPE_MAPPER
            )

            if isinstance(list_item, dict):
                if model := content_type_mapper.get(content_type, None):
                    return model(list_item, self._api, self._endpoint)
                return self._default_ret(list_item, self._api, self._endpoint)
            return list_item

        for k, v in values.items():
            if isinstance(v, dict):
                lookup = getattr(self.__class__, k, None)
                if k in ["custom_fields", "local_context_data"] or hasattr(
                    lookup, "_json_field"
                ):
                    self._add_cache((k, copy.deepcopy(v)))
                    setattr(self, k, v)
                    continue
                if isinstance(lookup, type) and issubclass(lookup, Record):
                    v = lookup(v, self._api, self._endpoint)
                else:
                    v = self._default_ret(v, self._api, self._endpoint)
                self._add_cache((k, v))

            elif isinstance(v, list):
                lookup = getattr(self.__class__, k, None)
                # An explicit JsonField marker means the column is raw JSON
                # (e.g. a plugin field holding a list of dicts). Keep it as-is
                # instead of coercing each dict into a nested Record, which
                # would break serialize()/save() (no id on plain JSON dicts).
                if hasattr(lookup, "_json_field"):
                    self._add_cache((k, copy.deepcopy(v)))
                    setattr(self, k, v)
                    continue
                # check if GFK
                if len(v) and isinstance(v[0], dict) and "object_type" in v[0]:
                    v = [generic_list_parser(k, i) for i in v]
                    # An unmapped object_type (e.g. a plugin whose extension
                    # hasn't been registered) falls through as the raw dict,
                    # so cache it directly instead of assuming .serialize().
                    to_cache = [
                        i.serialize() if hasattr(i, "serialize") else copy.deepcopy(i)
                        for i in v
                    ]
                elif k == "constraints":
                    # Permissions constraints can be either dict or list
                    to_cache = copy.deepcopy(v)
                elif (
                    k in SIBLING_TYPED_LIST_FIELDS
                    and len(v)
                    and isinstance(v[0], dict)
                    and isinstance(values.get(f"{k}_type"), str)
                ):
                    # NetBox cable-termination pattern: link_peers/
                    # connected_endpoints carry their item type in the sibling
                    # link_peers_type/connected_endpoints_type field rather
                    # than per-item. Cast each item to the model named by
                    # that sibling content type.
                    v = [sibling_typed_list_parser(i, values[f"{k}_type"]) for i in v]
                    to_cache = list(v)
                else:
                    v = [list_parser(k, i) for i in v]
                    to_cache = list(v)
                self._add_cache((k, to_cache))

            else:
                self._add_cache((k, v))
            setattr(self, k, v)

    def _endpoint_from_url(self, url):
        url_path = urlsplit(url).path
        base_url_path_parts = urlsplit(self._api.base_url).path.split("/")
        if len(base_url_path_parts) > 2:
            # There are some extra directories in the path, remove them from url
            extra_path = "/".join(base_url_path_parts[:-1])
            url_path = url_path[len(extra_path) :]
        split_url_path = url_path.split("/")
        if split_url_path[2] == "plugins":
            app = "plugins/{}".format(split_url_path[3])
            name = split_url_path[4]
        else:
            app, name = split_url_path[2:4]
        return getattr(pynetbox.core.app.App(self._api, app), name)

    def full_details(self):
        """Queries the hyperlinked endpoint if 'url' is defined.

        This method will populate the attributes from the detail
        endpoint when it's called. Sets `_has_details` so that
        attribute lookups don't call it more than once.

        :returns: True
        """
        if self.url:
            req = Request(
                base=self.url,
                token=self._api.token,
                http_session=self._api.http_session,
            )
            # Fields the caller has modified since the last sync. Hydrating
            # must not disturb these: _parse_values() would overwrite both the
            # attribute and its _init_cache baseline, silently discarding the
            # pending change so a later save() sends nothing. See issue #808.
            # These hold references, not copies, which keeps object identity
            # for a caller holding e.g. device.custom_fields. That relies on
            # _parse_values() assigning attributes with setattr() rather than
            # mutating them in place; were it to mutate, the restore below
            # would put back an already-overwritten value.
            # has_details is set while diffing so that serialize() reading a
            # deleted field does not re-enter full_details() (#822). A deleted
            # field is not kept as dirty; the fetch below reloads it.
            self.has_details = True
            try:
                dirty = {k for k in self._diff() if k in self.__dict__}
            finally:
                self.has_details = False
            dirty_values = {k: getattr(self, k) for k in dirty}
            dirty_baseline = {
                k: v for k, v in self._init_cache.items() if k in dirty
            }

            self._parse_values(next(req.get()))

            for k, v in dirty_values.items():
                setattr(self, k, v)
            self._init_cache.update(dirty_baseline)

            self._has_details = True
            return True
        return False

    def serialize(self, nested=False, init=False):
        """Serializes an object

        Pulls all the attributes in an object and creates a dict that
        can be turned into the json that netbox is expecting.

        If an attribute's value is a ``Record`` type it's replaced with
        the ``id`` field of that object.

        When ``init=False`` (default), includes both original fields from the
        API response and any fields that have been set on the object after
        initialization. This allows proper change detection for fields set
        to None or other values.

        When ``init=True``, returns only the original fields from the initial
        API response, used for comparing against the current state to detect
        changes.

        .. note::

            Using this to get a dictionary representation of the record
            is discouraged. It's probably better to cast to dict()
            instead. See Record docstring for example.

        :returns: dict.
        """
        if nested:
            return get_return(self)

        # Determine which fields to serialize
        if init:
            # For initial state, use only _init_cache
            fields_to_serialize = list(self._init_cache)
            init_vals = self._init_cache
        else:
            # For current state, include all fields (original + modified).
            # Preserve init_cache insertion order, then append any new
            # attributes set after init, so the serialized dict has a
            # deterministic key order across init=True/False calls (the
            # str-based list comparison in _diff() depends on it).
            init_cache_keys = list(self._init_cache)

            extra_keys = [
                k
                for k in self.__dict__.keys()
                if not k.startswith("_")
                and k not in self._INTERNAL_ATTRS
                and k not in self._init_cache
            ]

            fields_to_serialize = init_cache_keys + extra_keys
            init_vals = {}  # Not used when init=False

        ret = {}

        for i in fields_to_serialize:
            current_val = getattr(self, i, None) if not init else init_vals.get(i)
            if i == "custom_fields":
                ret[i] = flatten_custom(current_val)
            else:
                if isinstance(current_val, Record):
                    current_val = getattr(current_val, "serialize")(nested=True)

                if isinstance(current_val, list):
                    serialized_list = []
                    for v in current_val:
                        if isinstance(v, GenericListObject):
                            v = v.serialize()
                        elif isinstance(v, Record):
                            # FK-style list items (e.g. tagged_vlans) collapse to
                            # their id. NetBox 4.5+ also returns nested mapping
                            # objects without an id of their own (e.g.
                            # FrontPort.rear_ports items); preserve those as dicts
                            # so the API round-trips correctly.
                            v = v.id if hasattr(v, "id") else v.serialize(init=init)
                        serialized_list.append(v)
                    current_val = serialized_list
                    if i in LIST_AS_SET and (
                        all([isinstance(v, str) for v in current_val])
                        or all([isinstance(v, int) for v in current_val])
                    ):
                        current_val = list(dict.fromkeys(current_val))
                ret[i] = current_val

        return ret

    def _diff(self):
        def fmt_dict(k, v):
            if isinstance(v, dict):
                return k, Hashabledict(v)
            if isinstance(v, list):
                return k, ",".join(map(str, v))
            return k, v

        current_serialized = self.serialize()
        init_serialized = self.serialize(init=True)

        # custom_fields use merge semantics on PATCH: NetBox leaves any custom
        # field omitted from an update unchanged. Restrict the comparison to the
        # keys present in the current value so that assigning a subset of custom
        # fields isn't seen as removing the others (issue #748). To clear a
        # custom field the caller still sets it explicitly to None. Assigning an
        # empty dict is therefore a no-op (it touches no keys), matching NetBox's
        # merge semantics where an empty custom_fields body changes nothing.
        current_cf = current_serialized.get("custom_fields")
        init_cf = init_serialized.get("custom_fields")
        if isinstance(current_cf, dict) and isinstance(init_cf, dict):
            init_serialized = {
                **init_serialized,
                "custom_fields": {
                    k: v for k, v in init_cf.items() if k in current_cf
                },
            }

        current = Hashabledict({fmt_dict(k, v) for k, v in current_serialized.items()})
        init = Hashabledict(
            {fmt_dict(k, v) for k, v in init_serialized.items()}
        )
        return set([i[0] for i in set(current.items()) ^ set(init.items())])

    def _changed_custom_fields(self):
        """Return the custom fields whose raw value differs from the last sync.

        NetBox merges PATCHed custom fields, so unchanged ones are left out.
        Sending them back would round-trip read-only shapes such as the
        {value, label} objects NetBox 4.7 returns for selection fields (#806).
        """
        current = getattr(self, "custom_fields", None) or {}
        init = self._init_cache.get("custom_fields")
        if not isinstance(init, dict):
            init = {}
        return {k: v for k, v in current.items() if k not in init or init[k] != v}

    def updates(self):
        """Compiles changes for an existing object into a dict.

        Takes a diff between the objects current state and its state at init
        and returns them as a dictionary, which will be empty if no changes.
        ``custom_fields`` includes only the custom fields that changed.

        :returns: dict.
        :example:

        >>> x = nb.dcim.devices.get(name='test1-a3-tor1b')
        >>> x.serial
        ''
        >>> x.serial = '1234'
        >>> x.updates()
        {'serial': '1234'}
        >>>
        """
        if self.id:
            diff = self._diff()
            if diff:
                serialized = self.serialize()
                ret = {i: serialized[i] for i in diff}
                if "custom_fields" in ret:
                    ret["custom_fields"] = flatten_custom(self._changed_custom_fields())
                return ret
        return {}

    def save(self, changelog_message=None):
        """Saves changes to an existing object.

        Takes a diff between the objects current state and its state at init
        and sends them as a dictionary to Request.patch().

        :arg str changelog_message: Optional message to record in the
            resulting NetBox changelog entry (requires NetBox 4.4+). Nothing
            is sent if there are no changes to save.
        :returns: True if PATCH request was successful.
        :example:

        >>> x = nb.dcim.devices.get(name='test1-a3-tor1b')
        >>> x.serial
        ''
        >>> x.serial = '1234'
        >>> x.save(changelog_message="Set serial from asset audit")
        True
        >>>
        """
        updates = self.updates()
        if updates:
            if changelog_message is not None:
                updates["changelog_message"] = changelog_message
            req = Request(
                key=self.id,
                base=self._endpoint.url,
                token=self._api.token,
                http_session=self._api.http_session,
            )
            result = req.patch(updates)
            if result:
                # changelog_message is write-only, so NetBox never echoes it
                # back. Drop one set as an attribute so it isn't re-sent (and
                # seen as a pending change) on every later save().
                self.__dict__.pop("changelog_message", None)
                # Update object state with response from PATCH to keep cache in sync
                self._parse_values(result)
                return True
        return False

    def update(self, data, changelog_message=None):
        """Update an object with a dictionary.

        Accepts a dict and uses it to update the record and call save().
        For nested and choice fields you'd pass an int the same as
        if you were modifying the attribute and calling save().

        :arg dict data: Dictionary containing the k/v to update the
            record object with.
        :arg str changelog_message: Optional message to record in the
            resulting NetBox changelog entry (requires NetBox 4.4+).
        :returns: True if PATCH request was successful.
        :example:

        >>> x = nb.dcim.devices.get(1)
        >>> x.update({
        ...   "name": "test-switch2",
        ...   "serial": "ABC321",
        ... }, changelog_message="Renamed per ticket #4137")
        True

        """

        for k, v in data.items():
            setattr(self, k, v)
        return self.save(changelog_message=changelog_message)

    def delete(self, changelog_message=None):
        """Deletes an existing object.

        :arg str changelog_message: Optional message to record in the
            resulting NetBox changelog entry (requires NetBox 4.4+).
        :returns: True if DELETE operation was successful.
        :example:

        >>> x = nb.dcim.devices.get(name='test1-a3-tor1b')
        >>> x.delete(changelog_message="Decommissioned")
        True
        >>>
        """
        req = Request(
            key=self.id,
            base=self._endpoint.url,
            token=self._api.token,
            http_session=self._api.http_session,
        )
        data = None
        if changelog_message is not None:
            data = {"changelog_message": changelog_message}
        return True if req.delete(data=data) else False

delete(changelog_message=None)

Deletes an existing object.

:arg str changelog_message: Optional message to record in the resulting NetBox changelog entry (requires NetBox 4.4+). :returns: True if DELETE operation was successful. :example:

x = nb.dcim.devices.get(name='test1-a3-tor1b') x.delete(changelog_message="Decommissioned") True

Source code in pynetbox/core/response.py
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
def delete(self, changelog_message=None):
    """Deletes an existing object.

    :arg str changelog_message: Optional message to record in the
        resulting NetBox changelog entry (requires NetBox 4.4+).
    :returns: True if DELETE operation was successful.
    :example:

    >>> x = nb.dcim.devices.get(name='test1-a3-tor1b')
    >>> x.delete(changelog_message="Decommissioned")
    True
    >>>
    """
    req = Request(
        key=self.id,
        base=self._endpoint.url,
        token=self._api.token,
        http_session=self._api.http_session,
    )
    data = None
    if changelog_message is not None:
        data = {"changelog_message": changelog_message}
    return True if req.delete(data=data) else False

full_details()

Queries the hyperlinked endpoint if 'url' is defined.

This method will populate the attributes from the detail endpoint when it's called. Sets _has_details so that attribute lookups don't call it more than once.

:returns: True

Source code in pynetbox/core/response.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
def full_details(self):
    """Queries the hyperlinked endpoint if 'url' is defined.

    This method will populate the attributes from the detail
    endpoint when it's called. Sets `_has_details` so that
    attribute lookups don't call it more than once.

    :returns: True
    """
    if self.url:
        req = Request(
            base=self.url,
            token=self._api.token,
            http_session=self._api.http_session,
        )
        # Fields the caller has modified since the last sync. Hydrating
        # must not disturb these: _parse_values() would overwrite both the
        # attribute and its _init_cache baseline, silently discarding the
        # pending change so a later save() sends nothing. See issue #808.
        # These hold references, not copies, which keeps object identity
        # for a caller holding e.g. device.custom_fields. That relies on
        # _parse_values() assigning attributes with setattr() rather than
        # mutating them in place; were it to mutate, the restore below
        # would put back an already-overwritten value.
        # has_details is set while diffing so that serialize() reading a
        # deleted field does not re-enter full_details() (#822). A deleted
        # field is not kept as dirty; the fetch below reloads it.
        self.has_details = True
        try:
            dirty = {k for k in self._diff() if k in self.__dict__}
        finally:
            self.has_details = False
        dirty_values = {k: getattr(self, k) for k in dirty}
        dirty_baseline = {
            k: v for k, v in self._init_cache.items() if k in dirty
        }

        self._parse_values(next(req.get()))

        for k, v in dirty_values.items():
            setattr(self, k, v)
        self._init_cache.update(dirty_baseline)

        self._has_details = True
        return True
    return False

save(changelog_message=None)

Saves changes to an existing object.

Takes a diff between the objects current state and its state at init and sends them as a dictionary to Request.patch().

:arg str changelog_message: Optional message to record in the resulting NetBox changelog entry (requires NetBox 4.4+). Nothing is sent if there are no changes to save. :returns: True if PATCH request was successful. :example:

x = nb.dcim.devices.get(name='test1-a3-tor1b') x.serial '' x.serial = '1234' x.save(changelog_message="Set serial from asset audit") True

Source code in pynetbox/core/response.py
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
def save(self, changelog_message=None):
    """Saves changes to an existing object.

    Takes a diff between the objects current state and its state at init
    and sends them as a dictionary to Request.patch().

    :arg str changelog_message: Optional message to record in the
        resulting NetBox changelog entry (requires NetBox 4.4+). Nothing
        is sent if there are no changes to save.
    :returns: True if PATCH request was successful.
    :example:

    >>> x = nb.dcim.devices.get(name='test1-a3-tor1b')
    >>> x.serial
    ''
    >>> x.serial = '1234'
    >>> x.save(changelog_message="Set serial from asset audit")
    True
    >>>
    """
    updates = self.updates()
    if updates:
        if changelog_message is not None:
            updates["changelog_message"] = changelog_message
        req = Request(
            key=self.id,
            base=self._endpoint.url,
            token=self._api.token,
            http_session=self._api.http_session,
        )
        result = req.patch(updates)
        if result:
            # changelog_message is write-only, so NetBox never echoes it
            # back. Drop one set as an attribute so it isn't re-sent (and
            # seen as a pending change) on every later save().
            self.__dict__.pop("changelog_message", None)
            # Update object state with response from PATCH to keep cache in sync
            self._parse_values(result)
            return True
    return False

serialize(nested=False, init=False)

Serializes an object

Pulls all the attributes in an object and creates a dict that can be turned into the json that netbox is expecting.

If an attribute's value is a Record type it's replaced with the id field of that object.

When init=False (default), includes both original fields from the API response and any fields that have been set on the object after initialization. This allows proper change detection for fields set to None or other values.

When init=True, returns only the original fields from the initial API response, used for comparing against the current state to detect changes.

.. note::

Using this to get a dictionary representation of the record
is discouraged. It's probably better to cast to dict()
instead. See Record docstring for example.

:returns: dict.

Source code in pynetbox/core/response.py
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
def serialize(self, nested=False, init=False):
    """Serializes an object

    Pulls all the attributes in an object and creates a dict that
    can be turned into the json that netbox is expecting.

    If an attribute's value is a ``Record`` type it's replaced with
    the ``id`` field of that object.

    When ``init=False`` (default), includes both original fields from the
    API response and any fields that have been set on the object after
    initialization. This allows proper change detection for fields set
    to None or other values.

    When ``init=True``, returns only the original fields from the initial
    API response, used for comparing against the current state to detect
    changes.

    .. note::

        Using this to get a dictionary representation of the record
        is discouraged. It's probably better to cast to dict()
        instead. See Record docstring for example.

    :returns: dict.
    """
    if nested:
        return get_return(self)

    # Determine which fields to serialize
    if init:
        # For initial state, use only _init_cache
        fields_to_serialize = list(self._init_cache)
        init_vals = self._init_cache
    else:
        # For current state, include all fields (original + modified).
        # Preserve init_cache insertion order, then append any new
        # attributes set after init, so the serialized dict has a
        # deterministic key order across init=True/False calls (the
        # str-based list comparison in _diff() depends on it).
        init_cache_keys = list(self._init_cache)

        extra_keys = [
            k
            for k in self.__dict__.keys()
            if not k.startswith("_")
            and k not in self._INTERNAL_ATTRS
            and k not in self._init_cache
        ]

        fields_to_serialize = init_cache_keys + extra_keys
        init_vals = {}  # Not used when init=False

    ret = {}

    for i in fields_to_serialize:
        current_val = getattr(self, i, None) if not init else init_vals.get(i)
        if i == "custom_fields":
            ret[i] = flatten_custom(current_val)
        else:
            if isinstance(current_val, Record):
                current_val = getattr(current_val, "serialize")(nested=True)

            if isinstance(current_val, list):
                serialized_list = []
                for v in current_val:
                    if isinstance(v, GenericListObject):
                        v = v.serialize()
                    elif isinstance(v, Record):
                        # FK-style list items (e.g. tagged_vlans) collapse to
                        # their id. NetBox 4.5+ also returns nested mapping
                        # objects without an id of their own (e.g.
                        # FrontPort.rear_ports items); preserve those as dicts
                        # so the API round-trips correctly.
                        v = v.id if hasattr(v, "id") else v.serialize(init=init)
                    serialized_list.append(v)
                current_val = serialized_list
                if i in LIST_AS_SET and (
                    all([isinstance(v, str) for v in current_val])
                    or all([isinstance(v, int) for v in current_val])
                ):
                    current_val = list(dict.fromkeys(current_val))
            ret[i] = current_val

    return ret

update(data, changelog_message=None)

Update an object with a dictionary.

Accepts a dict and uses it to update the record and call save(). For nested and choice fields you'd pass an int the same as if you were modifying the attribute and calling save().

:arg dict data: Dictionary containing the k/v to update the record object with. :arg str changelog_message: Optional message to record in the resulting NetBox changelog entry (requires NetBox 4.4+). :returns: True if PATCH request was successful. :example:

x = nb.dcim.devices.get(1) x.update({ ... "name": "test-switch2", ... "serial": "ABC321", ... }, changelog_message="Renamed per ticket #4137") True

Source code in pynetbox/core/response.py
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
def update(self, data, changelog_message=None):
    """Update an object with a dictionary.

    Accepts a dict and uses it to update the record and call save().
    For nested and choice fields you'd pass an int the same as
    if you were modifying the attribute and calling save().

    :arg dict data: Dictionary containing the k/v to update the
        record object with.
    :arg str changelog_message: Optional message to record in the
        resulting NetBox changelog entry (requires NetBox 4.4+).
    :returns: True if PATCH request was successful.
    :example:

    >>> x = nb.dcim.devices.get(1)
    >>> x.update({
    ...   "name": "test-switch2",
    ...   "serial": "ABC321",
    ... }, changelog_message="Renamed per ticket #4137")
    True

    """

    for k, v in data.items():
        setattr(self, k, v)
    return self.save(changelog_message=changelog_message)

updates()

Compiles changes for an existing object into a dict.

Takes a diff between the objects current state and its state at init and returns them as a dictionary, which will be empty if no changes. custom_fields includes only the custom fields that changed.

:returns: dict. :example:

x = nb.dcim.devices.get(name='test1-a3-tor1b') x.serial '' x.serial = '1234' x.updates()

Source code in pynetbox/core/response.py
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
def updates(self):
    """Compiles changes for an existing object into a dict.

    Takes a diff between the objects current state and its state at init
    and returns them as a dictionary, which will be empty if no changes.
    ``custom_fields`` includes only the custom fields that changed.

    :returns: dict.
    :example:

    >>> x = nb.dcim.devices.get(name='test1-a3-tor1b')
    >>> x.serial
    ''
    >>> x.serial = '1234'
    >>> x.updates()
    {'serial': '1234'}
    >>>
    """
    if self.id:
        diff = self._diff()
        if diff:
            serialized = self.serialize()
            ret = {i: serialized[i] for i in diff}
            if "custom_fields" in ret:
                ret["custom_fields"] = flatten_custom(self._changed_custom_fields())
            return ret
    return {}

RecordSet Class

A RecordSet is a one-shot iterator over Record objects, returned by Endpoint.all() and Endpoint.filter(). It pages through results from NetBox on demand. To iterate the results more than once, materialize the set with list().

pynetbox.core.response.RecordSet

Iterator containing Record objects.

Returned by Endpoint.all() and Endpoint.filter() methods. Allows iteration of and actions to be taken on the results from the aforementioned methods. Contains Record objects.

Examples

To see how many results are in a query by calling len():

x = nb.dcim.devices.all()
len(x)
# 123

Simple iteration of the results:

devices = nb.dcim.devices.all()
for device in devices:
    print(device.name)

# test1-leaf1
# test1-leaf2
# test1-leaf3
Source code in pynetbox/core/response.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
class RecordSet:
    """Iterator containing Record objects.

    Returned by `Endpoint.all()` and `Endpoint.filter()` methods.
    Allows iteration of and actions to be taken on the results from the aforementioned
    methods. Contains Record objects.

    ## Examples

    To see how many results are in a query by calling `len()`:

    ```python
    x = nb.dcim.devices.all()
    len(x)
    # 123
    ```

    Simple iteration of the results:

    ```python
    devices = nb.dcim.devices.all()
    for device in devices:
        print(device.name)

    # test1-leaf1
    # test1-leaf2
    # test1-leaf3
    ```
    """

    def __init__(self, endpoint, request, **kwargs):
        self.endpoint = endpoint
        self.request = request
        self.response = self.request.get()
        self._response_cache = []

    def __iter__(self):
        return self

    def __next__(self):
        if self._response_cache:
            return self.endpoint.return_obj(
                self._response_cache.pop(), self.endpoint.api, self.endpoint
            )
        return self.endpoint.return_obj(
            next(self.response), self.endpoint.api, self.endpoint
        )

    def __len__(self):
        try:
            count = self.request.count
        except AttributeError:
            try:
                self._response_cache.append(next(self.response))
            except StopIteration:
                return 0
            count = self.request.count
        if count is None:
            # Cursor-based pagination omits the total count; fetch it
            # explicitly with a separate (offset-based) count request.
            count = self.request.get_count()
        return count

    def update(self, changelog_message=None, **kwargs):
        """Updates kwargs onto all Records in the RecordSet and saves these.

        Updates are only sent to the API if a value were changed, and only for
        the Records which were changed.

        ## Parameters

        * **changelog_message** (str, optional): Message to record in the
            NetBox changelog entry of each updated object (requires
            NetBox 4.4+).
        * **kwargs**: Fields and values to set on every Record.

        ## Returns
        True if the update succeeded, None if no update were required.

        ## Examples

        ```python
        result = nb.dcim.devices.filter(site_id=1).update(
            status='active', changelog_message='Site go-live'
        )
        # True
        ```
        """
        updates = []
        for record in self:
            # Update each record and determine if anything was updated
            for k, v in kwargs.items():
                setattr(record, k, v)
            record_updates = record.updates()
            if record_updates:
                # if updated, add the id to the dict and append to list of updates
                record_updates["id"] = record.id
                updates.append(record_updates)
        if updates:
            return self.endpoint.update(updates, changelog_message=changelog_message)
        return None

    def delete(self, changelog_message=None):
        """Bulk deletes objects in a RecordSet.

        Allows for batch deletion of multiple objects in a RecordSet.

        ## Parameters

        * **changelog_message** (str, optional): Message to record in the
            NetBox changelog entry of each deleted object (requires
            NetBox 4.4+).

        ## Returns
        True if bulk DELETE operation was successful.

        ## Examples

        Deleting offline `devices` on site 1:

        ```python
        netbox.dcim.devices.filter(site_id=1, status="offline").delete(
            changelog_message="Removing offline devices"
        )
        ```
        """
        return self.endpoint.delete(self, changelog_message=changelog_message)

delete(changelog_message=None)

Bulk deletes objects in a RecordSet.

Allows for batch deletion of multiple objects in a RecordSet.

Parameters
  • changelog_message (str, optional): Message to record in the NetBox changelog entry of each deleted object (requires NetBox 4.4+).
Returns

True if bulk DELETE operation was successful.

Examples

Deleting offline devices on site 1:

netbox.dcim.devices.filter(site_id=1, status="offline").delete(
    changelog_message="Removing offline devices"
)
Source code in pynetbox/core/response.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def delete(self, changelog_message=None):
    """Bulk deletes objects in a RecordSet.

    Allows for batch deletion of multiple objects in a RecordSet.

    ## Parameters

    * **changelog_message** (str, optional): Message to record in the
        NetBox changelog entry of each deleted object (requires
        NetBox 4.4+).

    ## Returns
    True if bulk DELETE operation was successful.

    ## Examples

    Deleting offline `devices` on site 1:

    ```python
    netbox.dcim.devices.filter(site_id=1, status="offline").delete(
        changelog_message="Removing offline devices"
    )
    ```
    """
    return self.endpoint.delete(self, changelog_message=changelog_message)

update(changelog_message=None, **kwargs)

Updates kwargs onto all Records in the RecordSet and saves these.

Updates are only sent to the API if a value were changed, and only for the Records which were changed.

Parameters
  • changelog_message (str, optional): Message to record in the NetBox changelog entry of each updated object (requires NetBox 4.4+).
  • kwargs: Fields and values to set on every Record.
Returns

True if the update succeeded, None if no update were required.

Examples
result = nb.dcim.devices.filter(site_id=1).update(
    status='active', changelog_message='Site go-live'
)
# True
Source code in pynetbox/core/response.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
def update(self, changelog_message=None, **kwargs):
    """Updates kwargs onto all Records in the RecordSet and saves these.

    Updates are only sent to the API if a value were changed, and only for
    the Records which were changed.

    ## Parameters

    * **changelog_message** (str, optional): Message to record in the
        NetBox changelog entry of each updated object (requires
        NetBox 4.4+).
    * **kwargs**: Fields and values to set on every Record.

    ## Returns
    True if the update succeeded, None if no update were required.

    ## Examples

    ```python
    result = nb.dcim.devices.filter(site_id=1).update(
        status='active', changelog_message='Site go-live'
    )
    # True
    ```
    """
    updates = []
    for record in self:
        # Update each record and determine if anything was updated
        for k, v in kwargs.items():
            setattr(record, k, v)
        record_updates = record.updates()
        if record_updates:
            # if updated, add the id to the dict and append to list of updates
            record_updates["id"] = record.id
            updates.append(record_updates)
    if updates:
        return self.endpoint.update(updates, changelog_message=changelog_message)
    return None