Giter Club home page Giter Club logo

python-netboxapi's Introduction

Python Netbox API

Build Status Coverage Status

Python client API for Netbox, using requests.

Usage

Netbox API

Import NetboxAPI:

from netboxapi import NetboxAPI

Initialize a new NetboxAPI object:

netbox_api = NetboxAPI(url="netbox.example.com/api")

# or if you enabled the authentication
netbox_api = NetboxAPI(
    url="netbox.example.com/api", username="user", password="password"
)

# or if you have generated a token
netbox_api = NetboxAPI(
    url="netbox.example.com/api", token="token"
)

# but the following is useless, as the token will not be used
netbox_api = NetboxAPI(
    url="netbox.example.com/api", username="user", password="password",
    token="token"
)

Then use multiple available methods to interact with the api:

>>> netbox_api.get("dcim/sites/1/racks/")
{
    "id": 1,
    "name": "Some rack",
    …
}

>>> netbox_api.post("dcim/device-roles/", json={"name": "test", …},)
{
    "id": 1,
    "name": "test",
    …
}

>>> netbox_api.patch("dcim/device-roles/", json={"slug": "test"},)
{
    "id": 1,
    "name": "test",
    "slug": "test",
    …
}

>>> netbox_api.put("dcim/device-roles/1/", json={"name": "test", …},)
{
    "id": 1,
    "name": "test",
    "slug": "test",
    …
}

>>> netbox_api.delete("dcim/sites/1/")
<<Response [204]>>

Netbox Mapper

NetboxMapper is available to interact with Netbox objects. Received json from the netbox API is converted into mapper objects, by setting its attributes accordingly to the dict. To use it, first import NetboxMapper:

from netboxapi import NetboxAPI, NetboxMapper

Initialize a new NetboxMapper object:

netbox_api = NetboxAPI(
    url="netbox.example.com/api", username="user", password="password"
)
netbox_mapper = NetboxMapper(netbox_api, app_name="dcim", model="sites")

GET

Then get all objects of the model:

>>> sites = list(netbox_mapper.get())
[<NetboxMapper>, <NetboxMapper>, …]

>>> print(sites[0].id)
1
>>> print(sites[0].name)
"Some site"

Or get a specific site by its id:

>>> netbox_mapper.get(1)

It is possible to get a subresourses of an object, and/or specify a query:

>>> netbox_mapper.get("1", "racks", q="name_to_filter")

Any kwargs (here q=) is used as a GET parameter for the request.

Pagination is transparently handled, but it is possible to specify how many items are wanted per page by setting the GET parameter limit, to limit the number of requests done to Netbox in case of long iterations.

Foreign keys

Foreign keys are handle automatically by the mapper.

>>> site = next(netbox_mapper.get())
>>> print(site.region.name)
"Some region"

When accessing to site.region, a query will be done to fetch the foreign object. It will then be saved in cache to avoid unnecessary queries for next accesses.

To refresh an object and its foreign keys, just do:

>>> site = next(site.get())

POST

Use the kwargs of a mapper to send a post request and create a new object:

>>> netbox_mapper.post(name="A site", slug="a_site", region="Some region")
<NetboxMapper>  # corresponding to the new created object

If a mapper is sent as parameter, post() will automatically take its id. However, it will not update the foreign object.

PUT

Use put() in a child mapper to update the resource upstream by reflecting the changes made in the object attributes:

>>> child_mapper = netbox_mapper.get(1)
>>> child_mapper.name = "another name"
>>> child_mapper.put()
<requests>  # requests object containing the netbox response

PATCH

PATCH is not supported in mappers, as it does not make really sense (to me) with the mapper logic.

DELETE

Delete an object upstream by calling delete():

>>> netbox_mapper.delete(1)
<requests>  # requests object containing the netbox response

# OR

>>> child_mapper = netbox_mapper.get(1)
>>> child_mapper.delete()
<requests>  # requests object containing the netbox response

But trying to delete another object of the same model from a child mapper is not possible:

>>> child_mapper = netbox_mapper.get(1)
>>> child_mapper.delete(2)
Exception ForbiddenAsChildError

Dependencies

  • python 3.4 (it certainly works with prior versions, just not tested)

License

Tool under the BSD license. Do not hesitate to report bugs, ask me some questions or do some pull request if you want to!

python-netboxapi's People

Contributors

aruhier avatar nahun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-netboxapi's Issues

Fix foreign keys in mapper

Foreign keys are broken when using the mapper: using put() after getting an object with the mapper will try to send the exact same dict it received before, when it should send the ID for attributes related to foreign keys.

Self-signed netbox certificate

There was a problem if netbox was forcibly transferred to ssl with a self-signed certificate, while adding the root certificate to the trusted ones in the OS, it gives an error:urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:
The only thing that helps to change this is in the lines:
python-netboxapi / netboxapi / api.py: 91 req_url, auth = (self.username, self.password), verify = False, ** kwargs
python-netboxapi / netboxapi / api.py: 95 req_url, auth = _HTTPTokenAuth (self.token), verify = False, ** kwargs

But this is not correct in theory. How to do it right?
In this case, so that the settings are applied from netbox_netprod_importer.

Update cable metod put.

Environment

  • Python version: 3.6.6
  • NetBox version: 2.5.5
  1. Create cable, Length length_unit do not fill.
  2. If use class NetboxMapper in netboxapi and change termination.
  3. Сalling the put method, returns an error that length_unit cannot be empty. Even if you first remove the attributes from the object. They are added to the to_dict functions class NetboxMapper. Here is an example of what is being transmitted in json:

{'id': 612, 'termination_a_type': 'dcim.interface', 'termination_a_id': 10488, 'termination_b_type': 'dcim.interface', 'termination_b_id': 8491, 'type': 3040, 'status': True, 'label': '', 'color': '', 'length': None, 'length_unit': None, 'termination_a': 10488, 'termination_b': 8492}

Add a check method

Add a check() method that would do a get+json() on the root api endpoint, to verify that the indicated URL is usable.

Handle pagination in mappers

Mappers should handle pagination in get(), and fetch the results as it iterates so it would not even be visible for the user.

NetboxMapper return format has changed

NetboxMapper objects now return the data inside a results hash, so in order to use them one needs to

virt_clusters = NetboxMapper(netbox_api, app_name="virtualization", model="clusters")
clusters = list(virt_clusters.get(name=cluster_name))[0].results

This is a bit clumsy and doesn't match the documentation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.