skip to Main Content

I am trying to interact with NetBox by using python from CentOS. What I have done is that I installed netbox with docker , so everytime I run “docker-compose up” from centOS I am able to access netbox api in my browser. I managed to add manually some new devices. So what I am trying to do now is that I want to write a python file so as to get this information that I manually added. My problem is that I cannot understand the documentation and nothing is working from those simple examples they provide in it.

The only thing that I managed to do is to retrieve the following json reply by importing the requests package:

{u'dcim': u'http://ansible.mpl.nh:2435/api/dcim/', u'circuits': u'http://ansible.mpl.nh:2435/api/circuits/', u'ipam': u'http://ansible.mpl.nh:2435/api/ipam/', u'secrets': u'http://ansible.mpl.nh:2435/api/secrets/', u'tenancy': u'http://ansible.mpl.nh:2435/api/tenancy/', u'extras': u'http://ansible.mpl.nh:2435/api/extras/', u'virtualization': u'http://ansible.mpl.nh:2435/api/virtualization/', u'plugins': u'http://ansible.mpl.nh:2435/api/plugins/'}

So what I basically do is just this:

rest_response = requests.get(url="http://ansible.../api/")

But this is just something very simple and basic. If I change the url I can get a reply from every API. How can I actually interact with NetBox and retrieving for example a device that I manually added in the API by using python ?

3

Answers


  1. Try the official python client, it makes API accesses way easier and includes samples https://github.com/digitalocean/pynetbox

    Login or Signup to reply.
  2. Here is an helloworld example:

    import json, requests
    
    url = 'http://127.0.0.1:8000/api/dcim/devices/'
    params = { 'name': "junos-dev-ex4200" }
    headers = {'Authorization': "Token xyz123456789" }                    
    
    r = requests.get(url, params=params, headers=headers)                       
    
    print(json.dumps(r.json(), indent=4))
    

    The detailed API documentation is available at http://127.0.0.1:8000/api/docs/.
    Here 127.0.0.1:8000 is your netbox instance.

    Login or Signup to reply.
  3. I recommend using the pynetbox module.

    Example:

    import pynetbox
    nb = pynetbox.api(url='https://netbox-url/', token='<API-token>')
    
    #fetch all devices
    nb_devicelist = nb.dcim.devices.all()
    
    # focus on 1 single device
    nb_device = nb_devicelist[1]
    print (nb_device)
    
    # do something with all devices in the list
    for nb_device in nb_devicelist:
        platform = str(nb_device.platform)
        pri_ip = str(nb_device.primary_ip)
        asset = nb_device.asset_tag
        print (nb_device,platform,pri_ip,asset)
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search