Network Automation Hands-on with REST- API (Tools - Python, Postman, NetBox)

PURPOSE

This blog aims at HTTP-based RESTCONF protocol that provides a programmatic interface for accessing data defined in YANG, using the datastore concepts defined in the Network Configuration Protocol (NETCONF). Using REST API with Browser, Server CLI, POSTMAN and Python programs. The scripts use RESTAPI to demonstrate various configurations you can run as examples in NetBox.

SCOPE

The scope of this blog describes how to set-up and configure an HTTP-based RESTCONF API. To work with network devices and Postman you’ll want to use RESTCONF, which is the HTTP variation of NETCONF that uses YANG models to drive the API. RESTCONF typically will run on port 443, though this can be changed and configured.

Introduction

This blog describes how to set-up and configure an HTTP-based protocol-Representational State Transfer Configuration Protocol (RESTCONF). RESTCONF provides a programmatic interface based on standard mechanisms for accessing configuration data, state data, data-model-specific Remote Procedure Call (RPC) operations and events defined in the YANG model.

Overview of RESTConf

The protocols and modelling languages that enable a programmatic way of writing configurations to a network device.

RESTCONF—Uses structured data (XML or JSON) and YANG to provide a REST-like APIs, enabling you to programmatically access different network devices. RESTCONF APIs use HTTPs methods.

YANG—A data modelling language that is used to model configuration and operational features. YANG determines the scope and the kind of functions that can be performed by NETCONF and RESTCONF APIs.

Why we need or care about REST API?

Need for standard mechanisms to allow Web applications to access the configuration data, state data, data-model-specific Remote Procedure Call (RPC) operations, and event notifications within a networking device, in a modular and extensible manner.

HTTP-based protocol-Representational State Transfer Configuration Protocol (RESTCONF). RESTCONF provides a programmatic interface based on standard mechanisms for accessing configuration data, state data, data-model-specific Remote Procedure Call (RPC) operations and events defined in the YANG model. Using the datastore concepts defined in the Network Configuration Protocol (NETCONF) [RFC6241].

For example: lot of times IP address management tools have REST APIs or Data-center infrastructure Management tools have REST APIs,

- Infoblox, Netbox, these kind of tools have Rest APIs that you might need to programmatically interface to

- Another category that might need to use REST APIs are the centralized controllers [SDN or SD WAN] that has a REST interface that we need to programmatically interface to

- Actual devices [routers/ switches] that uses REST API

- Internet services for work-flow like GIThub, most of internet services have RESTAPIs

The following figure shows the system components if a RESTCONF servers implemented in a device:

 +-----------+           +-----------------+
 |  Web app  | <-------> |                 |
 +-----------+  RESTCONF | network device  |
                         |                 |
                         +-----------------+
                                
The API resource contains the RESTCONF root resource for the RESTCONF datastore and operation resources. It is the top-level resource located at {+restconf} and has the media type "application/yang-data+xml" or "application/yang-data+json".
YANG tree diagram for an API resource:
                                
    +---- {+restconf}
        +---- data
        | ...
        +---- operations?
        | ...
        +--ro yang-library-version    string
                                
The "yang-api" YANG data template is defined using the "yang-data" extension in the "ietf-restconf" module. It specifies the structure and syntax of the conceptual child resources within the API resource. The API resource can be retrieved with the GET method.

NETCONF

NETCONF (from "NETwork CONFiguration") is the primary transport protocol used with YANG data models today. It defines how a manager (client) and agent (server) communicate in a standard fashion.

Why Data Model-Driven Management?

• APIs derived from the data models:
• Data models = definitions and constraints
• The protocol: NETCONF, RESTCONF, GRPC
• The encoding: JSON, XML, protobuf
• The programming language: Python, Ruby, Java, C, Erlang, ...
• Industry focusing on YANG as the data modeling language for services and devices

NETCONF Communications



NETCONF Protocol Stack



As a transport protocol, NETCONF has a layered approach that defines how the manager (client) and agent (server) communicate.
All SSH-features[encryption/security/authentication] will be inherited to Netconf protocol.

NETCONF defines configuration datastores and a set of Create, Read, Update, Delete (CRUD) operations that can be used to access these datastores. NETCONF also defines a protocol for invoking these operations.
The YANG language defines the syntax and semantics of datastore content, configuration, state data, RPC operations, and event notifications.

RESTCONF

RESTCONF uses HTTP methods to provide CRUD operations on a conceptual datastore containing YANG-defined data, which is compatible with a server that implements NETCONF datastores.

RestConf Protocol Stack:







NetBox is an open source web application designed to help manage and document computer networks. Initially conceived by the network engineering team at DigitalOcean, NetBox was developed specifically to address the needs of network and infrastructure engineers.

It encompasses the following aspects of network management:

- IP address management (IPAM) - IP networks and addresses, VRFs, and VLANs

- Equipment racks - Organized by group and site

- Devices - Types of devices and where they are installed

- Connections - Network, console, and power connections among devices

- Virtualization - Virtual machines and clusters

- Data circuits - Long-haul communications circuits and providersv

- Secrets - Encrypted storage of sensitive credentials

Application Stack

NetBox is built on the Django Python framework and utilizes a PostgreSQL database. It runs as a WSGI service behind your choice of HTTP server.

Function Component
HTTP service nginx or Apache
WSGI service gunicorn or uWSGI
Application Django/Python
Database PostgreSQL 9.6+
Task queuing Redis/django-rq
Live device access NAPALM

What is Rest API?

Rest stands for Representational state transfer, is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the internet. RESTful Web services allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations
Interfacing using HTTP or HTTPs, there will be some URLs we access [URL will be entity or resource that we are accessing
URL: https://netbox.lasthop.io/api/

netbox.lasthop.io is the server that I am running and /API on it ;

HTTPs is the protocol

So, we are accessing the Netbox machine and using this API

Now, going to a different URL, accessing a different resource [inside the Data-centre Infrastructure Management]

REST API access using Browser

I am accessing the Rest API using the browser and able to check out the available the DCIM [Data-centre Infrastructure Management], where I can select different available resources:

Switching into different resource using different URL - IPAM part of Netbox



The purpose to illustrate an API that will be used for networking purpose and I am using Netbox as an example to show and demonstrate these things

This URL “https://netbox.lasthop.io/api/ipam/” is specifying the resources of what we are talking to, what is the thing we are referring to on that remote entity

Now, with these resources we very typically have references that we can find programmatically to something else inside the API Let’s go to DCIM [Data-centre Infrastructure Management] part, we have devices here



And this tells me in hypertext, where do I need to go to find that thing. So, it gives me references where I might need to go to find particular thing Accessing the device Instance using the Netbox GUI,



Here, it comes back as JSON inside the list and I can access each of the devices, by accessing the element of this list: Now, how can I find or extract specific devices detail? From the received JSON in the list format, each of the device is accessible by the element of this list: Access the device 2 Instance using the Netbox GUI,



REST API access using Server CLI

Accessing the device Instances from the server CLI

(py_venv) [ssharma@lab1]$ curl -s https://netbox.lasthop.io/api/ --insecure | jq
"circuits": "http://netbox.lasthop.io/api/circuits/",
"dcim": "http://netbox.lasthop.io/api/dcim/",
"extras": "http://netbox.lasthop.io/api/extras/",
"ipam": "http://netbox.lasthop.io/api/ipam/",
"secrets": "http://netbox.lasthop.io/api/secrets/",
"tenancy": "http://netbox.lasthop.io/api/tenancy/",
"virtualization": "http://netbox.lasthop.io/api/virtualization/                                  
                              
Now, If I append on DCIM, so I can see the Data-center Infrastructure Management Part, what is that?
(py_venv) [	@lab1]$ curl -s https://netbox.lasthop.io/api/dcim/ --insecure | jq "."
{
  "_choices": "http://netbox.lasthop.io/api/dcim/_choices/",
  "regions": "http://netbox.lasthop.io/api/dcim/regions/",
  "sites": "http://netbox.lasthop.io/api/dcim/sites/",
  "rack-groups": "http://netbox.lasthop.io/api/dcim/rack-groups/",
  "rack-roles": "http://netbox.lasthop.io/api/dcim/rack-roles/",
  "racks": "http://netbox.lasthop.io/api/dcim/racks/",
  "rack-reservations": "http://netbox.lasthop.io/api/dcim/rack-reservations/",
  "manufacturers": "http://netbox.lasthop.io/api/dcim/manufacturers/",
  "device-types": "http://netbox.lasthop.io/api/dcim/device-types/",
  "console-port-templates": "http://netbox.lasthop.io/api/dcim/console-port-templates/",
  "console-server-port-templates": "http://netbox.lasthop.io/api/dcim/console-server-port-templates/",
  "power-port-templates": "http://netbox.lasthop.io/api/dcim/power-port-templates/",
  "power-outlet-templates": "http://netbox.lasthop.io/api/dcim/power-outlet-templates/",
  "interface-templates": "http://netbox.lasthop.io/api/dcim/interface-templates/",
  "device-bay-templates": "http://netbox.lasthop.io/api/dcim/device-bay-templates/",
  "device-roles": "http://netbox.lasthop.io/api/dcim/device-roles/",
  "platforms": "http://netbox.lasthop.io/api/dcim/platforms/",
  "devices": "http://netbox.lasthop.io/api/dcim/devices/",
  "console-ports": "http://netbox.lasthop.io/api/dcim/console-ports/",
  "console-server-ports": "http://netbox.lasthop.io/api/dcim/console-server-ports/",
  "power-ports": "http://netbox.lasthop.io/api/dcim/power-ports/",
  "power-outlets": "http://netbox.lasthop.io/api/dcim/power-outlets/",
  "interfaces": "http://netbox.lasthop.io/api/dcim/interfaces/",
  "device-bays": "http://netbox.lasthop.io/api/dcim/device-bays/",
  "inventory-items": "http://netbox.lasthop.io/api/dcim/inventory-items/",
  "console-connections": "http://netbox.lasthop.io/api/dcim/console-connections/",
  "power-connections": "http://netbox.lasthop.io/api/dcim/power-connections/",
  "interface-connections": "http://netbox.lasthop.io/api/dcim/interface-connections/",
  "virtual-chassis": "http://netbox.lasthop.io/api/dcim/virtual-chassis/",
  "connected-device": "http://netbox.lasthop.io/api/dcim/connected-device/"
}
                              
Similarly, I can check the devices section in the DCIM
 (py_venv) [ssharma@lab1]$ curl -s https://netbox.lasthop.io/api/dcim/devices/ --insecure | jq "."
{
  "detail": "Authentication credentials were not provided."
}
(py_venv) [ssharma@lab1]$
                              
However, as soon as I try to transition into devices section, authentication error pops out – In NetBox we actually need an Authorized token that I need to provide to get additional information.

Using curl to access "https://netbox.lasthop.io/api/dcim/devices/". This API endpoint requires authentication; use the "-H" flag to provide this authentication information.

Note, the lab has a NETBOX_TOKEN environment variable. Consequently, should be able to do the following:
Following output will extract detail of all the devices from the NetBox:
    (py_venv) [ssharma@lab1]$ curl -H "Authorization: Token $NETBOX_TOKEN" https://netbox.lasthop.io/api/dcim/devices/ --insecure | jq
    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                   Dload  Upload   Total   Spent    Left  Speed
  100 12242  100 12242    0     0  63103      0 --:--:-- --:--:-- --:--:-- 63103
  {
    "count": 10,
    "next": null,
    "previous": null,
    "results": [
      {
        "id": 3,
        "name": "Switch1",
        "display_name": "Switch1",
        "device_type": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/2/",
          "manufacturer": {
            "id": 6,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/6/",
            "name": "Switch",
            "slug": "Switch"
          },
          "model": "vEOS",
          "slug": "veos"
        },
        "device_role": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/3/",
          "name": "Distribution Switch",
          "slug": "distribution-switch"
        },
        "tenant": null,
        "platform": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/4/",
          "name": "Switch EOS",
          "slug": "Switch-eos"
        },
        "serial": "",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/racks/1/",
          "name": "RK1",
          "display_name": "RK1"
        },
        "position": null,
        "face": {
          "value": 0,
          "label": "Front"
        },
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": {
          "id": 5,
          "url": "http://netbox.lasthop.io/api/ipam/ip-addresses/5/",
          "family": 4,
          "address": "184.105.247.72/26"
        },
        "primary_ip4": {
          "id": 5,
          "url": "http://netbox.lasthop.io/api/ipam/ip-addresses/5/",
          "family": 4,
          "address": "184.105.247.72/26"
        },
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [
          "some_group",
          "another_group"
        ],
        "custom_fields": {},
        "created": "2020-09-01",
        "last_updated": "2020-10-03T14:33:59.835208-07:00",
        "local_context_data": null
      },
      {
        "id": 4,
        "name": "Switch2",
        "display_name": "Switch2",
        "device_type": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/2/",
          "manufacturer": {
            "id": 6,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/6/",
            "name": "Switch",
            "slug": "Switch"
          },
          "model": "vEOS",
          "slug": "veos"
        },
        "device_role": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/3/",
          "name": "Distribution Switch",
          "slug": "distribution-switch"
        },
        "tenant": null,
        "platform": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/4/",
          "name": "Switch EOS",
          "slug": "Switch-eos"
        },
        "serial": "",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/racks/1/",
          "name": "RK1",
          "display_name": "RK1"
        },
        "position": null,
        "face": null,
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": null,
        "primary_ip4": null,
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [],
        "custom_fields": {},
        "created": "2020-10-03",
        "last_updated": "2020-10-030T12:48:27.699741-07:00",
        "local_context_data": null
      },
      {
        "id": 5,
        "name": "Switch3",
        "display_name": "Switch3",
        "device_type": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/2/",
          "manufacturer": {
            "id": 6,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/6/",
            "name": "Switch",
            "slug": "Switch"
          },
          "model": "vEOS",
          "slug": "veos"
        },
        "device_role": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/3/",
          "name": "Distribution Switch",
          "slug": "distribution-switch"
        },
        "tenant": null,
        "platform": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/4/",
          "name": "Switch EOS",
          "slug": "Switch-eos"
        },
        "serial": "",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/racks/1/",
          "name": "RK1",
          "display_name": "RK1"
        },
        "position": null,
        "face": null,
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": null,
        "primary_ip4": null,
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [],
        "custom_fields": {},
        "created": "2020-10-03",
        "last_updated": "2020-10-030T14:37:56.312030-07:00",
        "local_context_data": null
      },
      {
        "id": 6,
        "name": "Switch4",
        "display_name": "Switch4",
        "device_type": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/2/",
          "manufacturer": {
            "id": 6,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/6/",
            "name": "Switch",
            "slug": "Switch"
          },
          "model": "vEOS",
          "slug": "veos"
        },
        "device_role": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/3/",
          "name": "Distribution Switch",
          "slug": "distribution-switch"
        },
        "tenant": null,
        "platform": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/4/",
          "name": "Switch EOS",
          "slug": "Switch-eos"
        },
        "serial": "",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/racks/1/",
          "name": "RK1",
          "display_name": "RK1"
        },
        "position": null,
        "face": null,
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": null,
        "primary_ip4": null,
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [],
        "custom_fields": {},
        "created": "2020-10-03",
        "last_updated": "2020-10-03T12:12:23.153134-07:00",
        "local_context_data": null
      },
      {
        "id": 7,
        "name": "Switch5",
        "display_name": "Switch5",
        "device_type": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/2/",
          "manufacturer": {
            "id": 6,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/6/",
            "name": "Switch",
            "slug": "Switch"
          },
          "model": "vEOS",
          "slug": "veos"
        },
        "device_role": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/3/",
          "name": "Distribution Switch",
          "slug": "distribution-switch"
        },
        "tenant": null,
        "platform": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/4/",
          "name": "Switch EOS",
          "slug": "Switch-eos"
        },
        "serial": "",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/racks/1/",
          "name": "RK1",
          "display_name": "RK1"
        },
        "position": null,
        "face": null,
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": null,
        "primary_ip4": null,
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [],
        "custom_fields": {},
        "created": "2020-10-03",
        "last_updated": "2020-10-03T12:28:21.631754-07:00",
        "local_context_data": null
      },
      {
        "id": 8,
        "name": "Switch6",
        "display_name": "Switch6",
        "device_type": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/2/",
          "manufacturer": {
            "id": 6,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/6/",
            "name": "Switch",
            "slug": "Switch"
          },
          "model": "vEOS",
          "slug": "veos"
        },
        "device_role": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/3/",
          "name": "Distribution Switch",
          "slug": "distribution-switch"
        },
        "tenant": null,
        "platform": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/4/",
          "name": "Switch EOS",
          "slug": "Switch-eos"
        },
        "serial": "",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/racks/2/",
          "name": "RK2",
          "display_name": "RK2"
        },
        "position": null,
        "face": null,
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": null,
        "primary_ip4": null,
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [],
        "custom_fields": {},
        "created": "2020-10-03",
        "last_updated": "2020-10-03T14:45:37.042129-07:00",
        "local_context_data": null
      },
      {
        "id": 9,
        "name": "Switch7",
        "display_name": "Switch7",
        "device_type": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/2/",
          "manufacturer": {
            "id": 6,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/6/",
            "name": "Switch",
            "slug": "Switch"
          },
          "model": "vEOS",
          "slug": "veos"
        },
        "device_role": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/3/",
          "name": "Distribution Switch",
          "slug": "distribution-switch"
        },
        "tenant": null,
        "platform": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/4/",
          "name": "Switch EOS",
          "slug": "Switch-eos"
        },
        "serial": "",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/racks/2/",
          "name": "RK2",
          "display_name": "RK2"
        },
        "position": null,
        "face": null,
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": null,
        "primary_ip4": null,
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [],
        "custom_fields": {},
        "created": "2020-10-03",
        "last_updated": "2020-10-03T10:47:47.570863-07:00",
        "local_context_data": null
      },
      {
        "id": 22,
        "name": "Switch9",
        "display_name": "Switch9",
        "device_type": {
          "id": 2,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/2/",
          "manufacturer": {
            "id": 6,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/6/",
            "name": "Switch",
            "slug": "Switch"
          },
          "model": "vEOS",
          "slug": "veos"
        },
        "device_role": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/3/",
          "name": "Distribution Switch",
          "slug": "distribution-switch"
        },
        "tenant": null,
        "platform": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/4/",
          "name": "Switch EOS",
          "slug": "Switch-eos"
        },
        "serial": "",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/racks/1/",
          "name": "RK1",
          "display_name": "RK1"
        },
        "position": null,
        "face": null,
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": null,
        "primary_ip4": null,
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [],
        "custom_fields": {},
        "created": "2020-05-29",
        "last_updated": "2020-05-29T07:11:51.714996-07:00",
        "local_context_data": null
      },
      {
        "id": 1,
        "name": "router1",
        "display_name": "router1",
        "device_type": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/1/",
          "manufacturer": {
            "id": 2,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/2/",
            "name": "Router",
            "slug": "router"
          },
          "model": "881",
          "slug": "router881"
        },
        "device_role": {
          "id": 7,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/7/",
          "name": "Router",
          "slug": "router"
        },
        "tenant": null,
        "platform": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/1/",
          "name": "Router IOS",
          "slug": "router-ios"
        },
        "serial": "FTX1512038X",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/racks/1/",
          "name": "RK1",
          "display_name": "RK1"
        },
        "position": null,
        "face": {
          "value": 0,
          "label": "Front"
        },
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/ipam/ip-addresses/3/",
          "family": 4,
          "address": "184.105.247.70/26"
        },
        "primary_ip4": {
          "id": 3,
          "url": "http://netbox.lasthop.io/api/ipam/ip-addresses/3/",
          "family": 4,
          "address": "184.105.247.70/26"
        },
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [],
        "custom_fields": {},
        "created": "2020-10-03",
        "last_updated": "2020-10-03T15:09:15.249257-07:00",
        "local_context_data": null
      },
      {
        "id": 2,
        "name": "router2",
        "display_name": "router2",
        "device_type": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/device-types/1/",
          "manufacturer": {
            "id": 2,
            "url": "http://netbox.lasthop.io/api/dcim/manufacturers/2/",
            "name": "Router",
            "slug": "router"
          },
          "model": "881",
          "slug": "router881"
        },
        "device_role": {
          "id": 7,
          "url": "http://netbox.lasthop.io/api/dcim/device-roles/7/",
          "name": "Router",
          "slug": "router"
        },
        "tenant": null,
        "platform": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/platforms/1/",
          "name": "Router IOS",
          "slug": "router-ios"
        },
        "serial": "FTX18298312",
        "asset_tag": null,
        "site": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
          "name": "Fremont Data Center",
          "slug": "fremont-dc"
        },
        "rack": {
          "id": 1,
          "url": "http://netbox.lasthop.io/api/dcim/racks/1/",
          "name": "RK1",
          "display_name": "RK1"
        },
        "position": null,
        "face": {
          "value": 0,
          "label": "Front"
        },
        "parent_device": null,
        "status": {
          "value": 1,
          "label": "Active"
        },
        "primary_ip": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/ipam/ip-addresses/4/",
          "family": 4,
          "address": "184.105.247.71/26"
        },
        "primary_ip4": {
          "id": 4,
          "url": "http://netbox.lasthop.io/api/ipam/ip-addresses/4/",
          "family": 4,
          "address": "184.105.247.71/26"
        },
        "primary_ip6": null,
        "cluster": null,
        "virtual_chassis": null,
        "vc_position": null,
        "vc_priority": null,
        "comments": "",
        "tags": [],
        "custom_fields": {},
        "created": "2020-10-03",
        "last_updated": "2020-10-03T15:25:01.152779-07:00",
        "local_context_data": null
      }
    ]
  }  
Accessing the selective device Instances from the server CLI, Using curl to retrieve only the device information for a single device (ID=2 for example). Once again this will require authorization. The API URL for this would be (assuming ID 2): https://netbox.lasthop.io/api/dcim/devices/2/
    py_venv) [ssharma@lab1]$ curl -H "Authorization: Token $NETBOX_TOKEN" https://netbox.lasthop.io/api/dcim/devices/2/ --insecure | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1381  100  1381    0     0   8369      0 --:--:-- --:--:-- --:--:--  8369
{
  "id": 2,
  "name": "router2",
  "display_name": "router2",
  "device_type": {
    "id": 1,
    "url": "http://netbox.lasthop.io/api/dcim/device-types/1/",
    "manufacturer": {
      "id": 2,
      "url": "http://netbox.lasthop.io/api/dcim/manufacturers/2/",
      "name": "Router",
      "slug": "router"
    },
    "model": "881",
    "slug": "router881"
  },
  "device_role": {
    "id": 7,
    "url": "http://netbox.lasthop.io/api/dcim/device-roles/7/",
    "name": "Router",
    "slug": "router"
  },
  "tenant": null,
  "platform": {
    "id": 1,
    "url": "http://netbox.lasthop.io/api/dcim/platforms/1/",
    "name": "Router IOS",
    "slug": "router-ios"
  },
  "serial": "FTX18298312",
  "asset_tag": null,
  "site": {
    "id": 1,
    "url": "http://netbox.lasthop.io/api/dcim/sites/1/",
    "name": "Fremont Data Center",
    "slug": "fremont-dc"
  },
  "rack": {
    "id": 1,
    "url": "http://netbox.lasthop.io/api/dcim/racks/1/",
    "name": "RK1",
    "display_name": "RK1"
  },
  "position": null,
  "face": {
    "value": 0,
    "label": "Front"
  },
  "parent_device": null,
  "status": {
    "value": 1,
    "label": "Active"
  },
  "primary_ip": {
    "id": 4,
    "url": "http://netbox.lasthop.io/api/ipam/ip-addresses/4/",
    "family": 4,
    "address": "184.105.247.71/26"
  },
  "primary_ip4": {
    "id": 4,
    "url": "http://netbox.lasthop.io/api/ipam/ip-addresses/4/",
    "family": 4,
    "address": "184.105.247.71/26"
  },
  "primary_ip6": null,
  "cluster": null,
  "virtual_chassis": null,
  "vc_position": null,
  "vc_priority": null,
  "comments": "",
  "tags": [],
  "custom_fields": {},
  "config_context": {},
  "created": "2020-10-03",
  "last_updated": "2020-10-03T15:25:01.152779-07:00",
  "local_context_data": null
}


There will be certain operations we can do with the resources, we are accessing?
In general, we can do 4 fundamental operations using HTTP methods:

1. GET - GET retrieves data for a transfer or a set of transfers
2. POST - POST creates a new transferv
3. PUT - PUT updates a transfer identified by its IDTU
4. DELETE - DELETE removes a transfer

These operations are done using GET, POST, PUT and DELETE HTTP requests. The requests are comprised of a URL and parameters, where a different URL is used for each operation.
The HTTP body can only be sent in json format, and application/json is the only Content-Type accepted.

Manage transfers with REST API

You can perform the following operations using REST API:
 Create transfers using an HTTP POST request.
 Modify existing transfers using HTTP PUT request.
 View transfer catalog records using HTTP GET request.
 Delete a transfer using HTTP DELETE request, to remove a transfer based on its IDTU.

These are also known as CRUD, if you have database applications. CRUD stands for Create, Read, Update, and Delete.

In regards to its use in RESTful APIs, CRUD is the standardized use of HTTP. This means that if you want to create a new record you should be using “POST.” If you are trying to read a record, you should be using “GET.” To update a record utilizing “PUT” or “PATCH.” And to delete a record, using “DELETE.”

REST API access using POSTMAN

There are tools available to use with RestAPI, one of the most common tool to use - POSTMAN [I am using plugin of postman for Chrome] You can see here my URL: https://netbox.lasthop.io/api/dcim/devices/ that I am accessing



 NOTE: Above, this Actually require a Token, I’ve added the Accept and Authorization [these both are HTTP headers]

Accept - application/json; version=2.4;
Authorization – Token xxxxxxxxxxxx {just a string}

Once I get authorized and click on send, I’ll get all my devices coming back to me

As soon as I am clicking on the send button – The request is getting authorized and I am able to see all the devices detail /configuration extracted
                                




REST API access using Python

Showing, how we can access the REST API using Python programs. First thing to do, interfacing to RestAPI using the python requests library, to perform an HTTP GET on the base URL of the NetBox server (https://netbox.lasthop.io/api/).

Ensuring not to verify the SSL certificate.

Print the HTTP status code, the response text, the JSON response, and the HTTP response headers. These items can be accessed using the following attributes/methods in the Python-requests Response object:

response.status_code
response.text
response.json()
response.headers

RESTAPI GET operation to extract devices detail using Python

Properly construct the HTTP request headers as follows: http_headers = {} http_headers["accept"] = "application/json; version=2.4;"

You will need to pass these HTTP headers into your HTTP GET request. Once again print the HTTP status code, the response text, the JSON response, and the HTTP response headers.

(py_venv) [ssharma@lab1]$ cat request_get.py 
import requests
from pprint import pprint
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
if __name__ == "__main__":
    # Failed auth
    # url = "https://netbox.lasthop.io/api/dcim/devices/"
    # Working no auth
    url = "https://netbox.lasthop.io/api/dcim/"
    # url = "https://api.github.com/"
    http_headers = {"accept": "application/json; version=2.4;"}
    response = requests.get(url, headers=http_headers, verify=False)
    response = response.json()
    print()
    pprint(response)
    print()

                                
Running the Python program to extract the following devices detail from the netBox using Python program,

HTTP GET request to retrieve all of the endpoints under the "/api/dcim" parent. Pretty print out the response.json() from this output.

This should be a dictionary with the key being the next part of the URL after "/api/dcim" and the value being the full URL.
    (py_venv) [ssharma@lab1]$ python request_get.py 

{'_choices': 'http://netbox.lasthop.io/api/dcim/_choices/',
 'connected-device': 'http://netbox.lasthop.io/api/dcim/connected-device/',
 'console-connections': 'http://netbox.lasthop.io/api/dcim/console-connections/',
 'console-port-templates': 'http://netbox.lasthop.io/api/dcim/console-port-templates/',
 'console-ports': 'http://netbox.lasthop.io/api/dcim/console-ports/',
 'console-server-port-templates': 'http://netbox.lasthop.io/api/dcim/console-server-port-templates/',
 'console-server-ports': 'http://netbox.lasthop.io/api/dcim/console-server-ports/',
 'device-bay-templates': 'http://netbox.lasthop.io/api/dcim/device-bay-templates/',
 'device-bays': 'http://netbox.lasthop.io/api/dcim/device-bays/',
 'device-roles': 'http://netbox.lasthop.io/api/dcim/device-roles/',
 'device-types': 'http://netbox.lasthop.io/api/dcim/device-types/',
 'devices': 'http://netbox.lasthop.io/api/dcim/devices/',
 'interface-connections': 'http://netbox.lasthop.io/api/dcim/interface-connections/',
 'interface-templates': 'http://netbox.lasthop.io/api/dcim/interface-templates/',
 'interfaces': 'http://netbox.lasthop.io/api/dcim/interfaces/',
 'inventory-items': 'http://netbox.lasthop.io/api/dcim/inventory-items/',
 'manufacturers': 'http://netbox.lasthop.io/api/dcim/manufacturers/',
 'platforms': 'http://netbox.lasthop.io/api/dcim/platforms/',
 'power-connections': 'http://netbox.lasthop.io/api/dcim/power-connections/',
 'power-outlet-templates': 'http://netbox.lasthop.io/api/dcim/power-outlet-templates/',
 'power-outlets': 'http://netbox.lasthop.io/api/dcim/power-outlets/',
 'power-port-templates': 'http://netbox.lasthop.io/api/dcim/power-port-templates/',
 'power-ports': 'http://netbox.lasthop.io/api/dcim/power-ports/',
 'rack-groups': 'http://netbox.lasthop.io/api/dcim/rack-groups/',
 'rack-reservations': 'http://netbox.lasthop.io/api/dcim/rack-reservations/',
 'rack-roles': 'http://netbox.lasthop.io/api/dcim/rack-roles/',
 'racks': 'http://netbox.lasthop.io/api/dcim/racks/',
 'regions': 'http://netbox.lasthop.io/api/dcim/regions/',
 'sites': 'http://netbox.lasthop.io/api/dcim/sites/',
 'virtual-chassis': 'http://netbox.lasthop.io/api/dcim/virtual-chassis/'}

RESTAPI to extract devices detail with Authentication using Python

Retrieve a list of all the devices in NetBox. This will require authentication. As in the previous task, create your headers manually and pass them into your request. In order to perform the NetBox authentication, you should do the following:

import os # Set the token based on the NETBOX_TOKEN environment variable

token = os.environ["NETBOX_TOKEN"]

Then add the following key to your HTTP Headers: http_headers["Authorization"] = f"Token {token}"

From this returned data structure (the NetBox "/api/dcim/devices/"), print out all of the device "display_names".

Note, the response.json() will contain a "results" key. This "results" key will refer to a list of dictionaries. These dictionaries will contain information about each one of the devices in NetBox. Now Let’s see, how we layer on Authentication information in python program

 (py_venv) [ssharma@lab1]$ cat request_get_w_auth.py 
import os
import requests
from pprint import pprint
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
if __name__ == "__main__":

    token = os.environ["NETBOX_TOKEN"]
    # url = "https://netbox.lasthop.io/api/dcim/devices"
    url = "https://netbox.lasthop.io/api/dcim/devices/1"
    http_headers = {"accept": "application/json; version=2.4;"}
    if token:
        http_headers["authorization"] = "Token {}".format(token)
    response = requests.get(url, headers=http_headers, verify=False)
    response = response.json()

    print()
    pprint(response)
    print()
When we execute the Authentication python program with Token information to Net Box to do the authentication

Apparently, we will get some sort of API key which will get authenticated and let us access certain things

Following output, we have received back from the NetBox and have received detail of all the devices:

    (py3_venv) [ssharma@lab1 collateral]$ python request_get_w_auth.py 
{'asset_tag': None,
 'cluster': None,
 'comments': '',
 'config_context': {},
 'created': '2020-09-01',
 'custom_fields': {},
 'device_role': {'id': 7,
                 'name': 'Router',
                 'slug': 'router',
                 'url': 'http://netbox.lasthop.io/api/dcim/device-roles/7/'},
 'device_type': {'id': 1,
                 'manufacturer': {'id': 2,
                                  'name': 'Router',
                                  'slug': 'router',
                                  'url': 'http://netbox.lasthop.io/api/dcim/manufacturers/2/'},
                 'model': '881',
                 'slug': 'router881',
                 'url': 'http://netbox.lasthop.io/api/dcim/device-types/1/'},
 'display_name': 'router1',
 'face': {'label': 'Front', 'value': 0},
 'id': 1,
 'last_updated': ‘2020-10-03T15:09:15.249257-07:00',
 'local_context_data': None,
 'name': 'router1',
 'parent_device': None,
 'platform': {'id': 1,
              'name': 'Router IOS',
              'slug': 'router-ios',
              'url': 'http://netbox.lasthop.io/api/dcim/platforms/1/'},
 'position': None,
 'primary_ip': {'address': '184.105.247.70/26',
                'family': 4,
                'id': 3,
                'url': 'http://netbox.lasthop.io/api/ipam/ip-addresses/3/'},
 'primary_ip4': {'address': '184.105.247.70/26',
                 'family': 4,
                 'id': 3,
                 'url': 'http://netbox.lasthop.io/api/ipam/ip-addresses/3/'},
 'primary_ip6': None,
 'rack': {'display_name': 'RK1',
          'id': 1,
          'name': 'RK1',
          'url': 'http://netbox.lasthop.io/api/dcim/racks/1/'},
 'serial': 'FTX1512038X',
 'site': {'id': 1,
          'name': 'Fremont Data Center',
          'slug': 'fremont-dc',
          'url': 'http://netbox.lasthop.io/api/dcim/sites/1/'},
 'status': {'label': 'Active', 'value': 1},
 'tags': [],
 'tenant': None,
 'vc_position': None,
 'vc_priority': None,
 'virtual_chassis': None}

Till now, above we have covered python request library to retrieve information and how to add authentication layer into that, and how to create objects using Python request library. Now, let’s check how we can modify device code

RESTAPI to Modify Devices detail using Python

(py_venv) [ssharma@lab1]$ cat modify_device.py 
import os
import requests
import json
from pprint import pprint

from urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

if __name__ == "__main__":
    """
    HTTP PUT
    URL: https://netbox.lasthop.io/api/dcim/devices/8/
    HTTP Headers: {'Content-Type': 'application/json; version=2.4;', 'authorization': 'Token x'}
    PUT DATA: {'id': 8, 'name': 'Switch6', 'display_name': 'Switch6', 'device_type': 2,
    'device_role': 3, 'tenant': None, 'platform': 4, 'serial': '', 'asset_tag': None,
    'site': 1, 'rack': 2, 'position': None,
    'face': None, 'parent_device': None, 'status': 1, 'primary_ip': None, 'primary_ip4': None,
    'primary_ip6': None, 'cluster': None, 'virtual_chassis': None, 'vc_position': None,
    'vc_priority': None, 'comments': '', 'tags': [], 'custom_fields': {}, 'created': '2020-06-01',
    'last_updated': '2020-09-01T12:29:41.716417-07:00', 'local_context_data': None}
    """

    token = os.environ["NETBOX_TOKEN"]

    # Switch6
    url = "https://netbox.lasthop.io/api/dcim/devices/8/"
    http_headers = {
        "accept": "application/json; version=2.4;",
        "authorization": "Token {}".format(token),
    }
    response = requests.get(url, headers=http_headers, verify=False)
    Switch6 = response.json()

    http_headers = {
        "Content-Type": "application/json; version=2.4;",
        "authorization": "Token {}".format(token),
    }
    # Reformat to get the proper structure for the existing object
    for field in ["device_role", "device_type", "platform", "site", "rack"]:
        Switch6[field] = Switch6[field]["id"]
    Switch6["status"] = 1
    Switch6["rack"] = 2
    response = requests.put(
        url, headers=http_headers, data=json.dumps(Switch6), verify=False
    )
    response = response.json()
    print()
    pprint(response)
    # print(response._content.decode())
    print()
                            
In above, Python program, modifying the NetBox router named ”Switch6” rack number to 2; in the NetBox its currently marked as 1. When we execute this python program and check the status again, it will be changed to Rack 2.
(py_venv) [ssharma@lab1]$ python modify_device.py

{'asset_tag': None,
 'cluster': None,
 'comments': '',
 'created': '2020-09-01',
 'custom_fields': {},
 'device_role': {'id': 3,
                 'name': 'Distribution Switch',
                 'slug': 'distribution-switch',
                 'url': 'http://netbox.lasthop.io/api/dcim/device-roles/3/'},
 'device_type': {'id': 2,
                 'manufacturer': {'id': 6,
                                  'name': 'Switch',
                                  'slug': 'Switch',
                                  'url': 'http://netbox.lasthop.io/api/dcim/manufacturers/6/'},
                 'model': 'vEOS',
                 'slug': 'veos',
                 'url': 'http://netbox.lasthop.io/api/dcim/device-types/2/'},
 'display_name': 'Switch6',
 'face': None,
 'id': 8,
 'last_updated': '2020-10-05T08:03:56.655950-07:00',
 'local_context_data': None,
 'name': 'Switch6',
 'parent_device': None,
 'platform': {'id': 4,
              'name': 'Switch EOS',
              'slug': 'Switch-eos',
              'url': 'http://netbox.lasthop.io/api/dcim/platforms/4/'},
 'position': None,
 'primary_ip': None,
 'primary_ip4': None,
 'primary_ip6': None,
 'rack': {'display_name': 'RK2',
          'id': 2,
          'name': 'RK2',
          'url': 'http://netbox.lasthop.io/api/dcim/racks/2/'},
 'serial': '',
 'site': {'id': 1,
          'name': 'Fremont Data Center',
          'slug': 'fremont-dc',
          'url': 'http://netbox.lasthop.io/api/dcim/sites/1/'},
 'status': {'label': 'Active', 'value': 1},
 'tags': [],
 'tenant': None,
 'vc_position': None,
 'vc_priority': None,
 'virtual_chassis': None}

RESTAPI to Add Devices/detail using Python

Creating Objects using Python request library:

(py_venv) [ssharma@lab1]$ cat add_device.py 
import os
import requests
import json
from pprint import pprint
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

if __name__ == "__main__":
    """
    --------------------------------------------------------------------------------
    HTTP POST
    URL: https://netbox.lasthop.io/api/dcim/devices/
    HTTP Headers: {'Content-Type': 'application/json; version=2.4;',
        'authorization': 'Token aaaabbbbccccddddeeeeffff0000111122223333'}
    POST DATA: {'name': 'Switch4', 'device_role': 3, 'device_type': 2, 'display_name': 'Switch4',
        'platform': 4, 'rack': 1, 'site': 1, 'status': 1}
    --------------------------------------------------------------------------------
    """
    token = os.environ["NETBOX_TOKEN"]
    url = "https://netbox.lasthop.io/api/dcim/devices/"
    http_headers = {
        "Content-Type": "application/json; version=2.4;",
        "authorization": "Token {}".format(token),
    }
    post_data = {
        "name": "Switch8",
        "device_role": 3,  # Distribution Switch
        "device_type": 2,  # vEOS
        "display_name": "Switch8",
        "platform": 4,  # Switch EOS
        "rack": 1,  # RK1
        "site": 1,  # Fremont Data Center
        "status": 1,  # Active
    }
    response = requests.post(
        url, headers=http_headers, data=json.dumps(post_data), verify=False
    )
    response = response.json()
    print()
    pprint(response)
    # print(response._content.decode())
    print()

                                


Importing (Python request library), (JSON library), (pretty-print library) When executing the above python program. It will freshly create a new device in the NetBox API named “Switch8” You can check login into the NetBox device, alternatively

(py_venv) [ssharma@lab1]$  python add_device.py 
{'asset_tag': None,
 'cluster': None,
 'comments': '',
 'created': '2020-10-05',
 'device_role': {'id': 3,
                 'name': 'Distribution Switch',
                 'slug': 'distribution-switch',
                 'url': 'http://netbox.lasthop.io/api/dcim/device-roles/3/'},
 'device_type': {'id': 2,
                 'manufacturer': {'id': 6,
                                  'name': 'Switch',
                                  'slug': 'Switch',
                                  'url': 'http://netbox.lasthop.io/api/dcim/manufacturers/6/'},
                 'model': 'vEOS',
                 'slug': 'veos',
                 'url': 'http://netbox.lasthop.io/api/dcim/device-types/2/'},
 'display_name': 'Switch8',
 'face': None,
 'id': 28,
 'last_updated': '2020-10-05T08:10:30.244885-07:00',
 'local_context_data': None,
 'name': 'Switch8',
 'parent_device': None,
 'platform': {'id': 4,
              'name': 'Switch EOS',
              'slug': 'Switch-eos',
              'url': 'http://netbox.lasthop.io/api/dcim/platforms/4/'},
 'position': None,
 'primary_ip': None,
 'primary_ip4': None,
 'primary_ip6': None,
 'rack': {'display_name': 'RK1',
          'id': 1,
          'name': 'RK1',
          'url': 'http://netbox.lasthop.io/api/dcim/racks/1/'},
 'serial': '',
 'site': {'id': 1,
          'name': 'Fremont Data Center',
          'slug': 'fremont-dc',
          'url': 'http://netbox.lasthop.io/api/dcim/sites/1/'},
 'status': {'label': 'Active', 'value': 1},
 'tags': [],
 'tenant': None,
 'vc_position': None,
 'vc_priority': None,
 'virtual_chassis': None}

RESTAPI to Delete Devices/detail using Python

Using RestAPI, how to delete a Device. Let’s delete device previously created named “Switch8”

(py_venv) [ssharma@lab1]$ cat delete_device.py 
import os
import requests
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

if __name__ == "__main__":
    token = os.environ["NETBOX_TOKEN"]
    # Will need updated to map to Switch8 that is created via add_device.py
    url = "https://netbox.lasthop.io/api/dcim/devices/15/"
    http_headers = {
        "Content-Type": "application/json; version=2.4;",
        "authorization": "Token {}".format(token),
    }
    response = requests.delete(url, headers=http_headers, verify=False)
    if response.ok:
        print("Device deleted successfully")

                        


As soon as we execute our “delete_device” python program, will see that recently created above shown device “Switch8” will get delete from the NetBox

(py_venv) [ssharma@lab1]$ python delete_device.py
Device deleted successfully
(py_venv) [ssharma@lab1]$

                        

CONCLUSION

In conclusion, the utilization of the HTTP-based RESTCONF protocol for network configuration and management opens up a world of possibilities for network administrators and developers. By leveraging REST APIs, you can automate tasks, streamline operations, and retrieve valuable information to optimize your network infrastructure. This blog has provided valuable insights and practical examples to guide you on your journey towards network automation and orchestration.

Stay connected to the latest advancements in network technology and continue to explore the potential of RESTCONF. Keep pushing the boundaries, stay motivated, and embrace the power of programmability in network management. We hope that this blog has ignited your passion for network automation and inspired you to take your network to new heights.

Thank you for joining us on this enlightening journey. We look forward to sharing more valuable insights and guiding you towards success in our upcoming blogs. Until then, stay connected, keep learning, and we will see you in the next blog shortly.

Happy automating!