Meet us at Cisco Live Las Vegas 2024

To read data from API directly from the IP Fabric platform is very simple. The best way to start is to have a quick look at our documentation. Even for anyone who's never done any testing before. It's very standard and it contains useful information about API endpoint, authentication options or response codes to begin with.

In the previous post, we demonstrated a quick tutorial for Zabbix and Ansible integration with Bash script. The current post is dedicated to authenticating to IP Fabric's API with username and password, get token and use token-based authentication furthermore. And finally to read data from API.

Authenticating to IP Fabric's API

There are two main HTTP authentication methods with only one possible sequence. The first is basic authentication, for which local or LDAP users can be utilized. The second is token-based and to request a token, one has to authenticate with the first method to get the token. That clarifies the sequence order.

Very importantly, any user has to log in via GUI beforehand to accept the End-User License Agreement (EULA). Only then we may begin.

For testing the API we will use standard Python3 (3.6.6) console in Ubuntu (18.04.3 LTS). In Python3 we will abstract all requests with the help of the 'requests' library, which includes all we need.

#> python3
 Python 3.6.8 (default, Oct  7 2019, 12:59:55) 
 [GCC 8.3.0] on linux
 Type "help", "copyright", "credits" or "license" for more information.
>>>
import requests
serverName = 'https://ipfabric.domain/api/v1/'
authData = { 'username': 'username', 'password' : 'password' }
authEndpoint = serverName + 'auth/login'
authPost = requests.post(authEndpoint, json=authData, verify=False)
      

Testing responses in console

To confirm successful authentication, we may test for 'status_code' or 'reason' property from the response server.

authPost.status_code
>>> 200
authPost.reason
>>> 'OK'
authJson.json().keys()
>>> dict_keys(['accessToken', 'refreshToken'])

According to our response, we can tell we have the access and refresh token ready. The access token expires after 30 minutes, it needs to be refreshed before with the refresh token, that expires after 24 hours if not blacklisted.

Read data from API

After successful authentication and with having the accessToken at hand, we can start the data mining from IP Fabric. All technology tables have their own API endpoint, that can be found on request.

We will start with the device inventory. To be able to perform token-based authentication, we will create the 'tokenHeaders' for our request. To get the data, we need to specify the right endpoint and the payload. In the payload we will can define columns, filters or even sorting options.

>>>
snapshotId = '$last'
devicesEndpoint = serverName + 'tables/inventory/devices'
devicesPayload = {'columns':["sn","hostname", "vendor"], filters: {}, 'snapshot':snapshotId,}

accessToken = authPost.json()['accessToken']
tokenHeaders = { 'Authorization' : 'Bearer ' + accessToken}

reqDevices = requests.post(devicesEndpoint, headers=tokenHeaders, json=devicesPayload, verify=False)

reqDevices.json().keys()
>>> dict_keys(['data', '_meta'])
reqDevices.json()['_meta']
>>> {'limit': None, 'start': 0, 'count': 633, 'size': 633, 'snapshot': '86c65bbc-f3e2-4ca1-8b9a-f6eb859081ed'}         

The response provides two main dictionary keys: the 'data' (the actual data, list of devices with serial number and login IP) and '_meta' (contains response overview with a number of returned devices or snapshot identification). The full script with simple flow control is below.

"""
Simple python3 script example for authenticating to IP Fabric's API and printing the _meta data from device inventory to the console.
"""
# Built-in/Generic Imports
import requests,sys
# Suppressing SSL certificate warnings if needed
requests.packages.urllib3.disable_warnings()

# Starting with variables
serverName = 'https://ipf.wordpress-625423-2416527.cloudwaysapps.com/api/v1/'
snapshotId = '$last'
authData = { 'username': 'username', 'password' : 'password' }
authEndpoint = serverName + 'auth/login'
devicesEndpoint = serverName + 'tables/inventory/devices'
devicesPayload = {'columns':["sn","hostname", "vendor"],'snapshot':snapshotId,}

print('\n Attempting to authenticate to: ' + authEndpoint)
# Initiating authentication request to obtain authentication token
authPost = requests.post(authEndpoint, json=authData, verify=False)
if not authPost.ok:
    print('Unable to authenticate: ' + authPost.text)
    print('\n ..Script will exit.\n')
    sys.exit()

# Collecting the accessToken 
accessToken = authPost.json()['accessToken']
# Creating the tokenHeaders 
tokenHeaders = { 'Authorization' : 'Bearer ' + accessToken}

print('\n Requesting data from API endpoint: ' + devicesEndpoint)
# Contacting the API endpoint for device inventory
reqDevices = requests.post(devicesEndpoint, headers=tokenHeaders, json=devicesPayload, verify=False)
if not reqDevices.ok:
    print('Unable to authenticate: ' + reqDevices.text)
    print('\n ..Script will exit.\n')
    sys.exit()

# Printing _meta response
print('\n Data collected successfully…')
print('\n The _meta data: ' + str(reqDevices.json()['_meta']))
print('\nScript ends. \n ')

Thank you for reading and enjoy the first part of our recording:

If you have found this article helpful, please follow our company’s LinkedIn or Blog, where there will be more content emerging. Furthermore, if you would like to test our platform to evaluate how it can assist you in managing your network more effectively, please let us know through www.ipfabric.io.

The IP Fabric platform provides a standard Application Programming Interface (API), and this interface allows to integrate IP Fabric platform with any 3rd party software or build any custom scripts. See the official documentation for details on how to use our API.

Thanks to a unique discovery algorithm, IP Fabric is capable of collecting data about all active network devices automatically. It collects more than 1000 parameters from each individual device and provides the data in a standardized form. Those data can be viewed in GUI or accessed via API. Hence all available data serves as a perfect baseline for any automation or API integration efforts.

The goal of this article

This article demonstrates how to add devices to Zabbix monitoring software. Zabbix uses the SNMP protocol for monitoring; therefore, we have to check if a device has SNMP configured and if no, then we will configure it automatically using the Ansible tool.

Where to get API information in IP Fabric

The IP Fabric is a very flexible tool when it comes to getting information. The same applies to well-documented API fetch points. In every technology table, including the main device inventory, there's table description, that appears on request.

apiInventory
API Integration: URL for device inventory

The full device inventory can be accessed with a POST request to https://ipfabric.domain.com/api/v1/tables/inventory/devices. The response can be filtered by any column.

So let's say that we want to get all Cisco IOS, IOS-XE devices, the following code snippet will accomplish just that:

curl -k -s https://ipfabric.domain.com/api/v1/tables/inventory/devices \
   -u 'username:password' \
   -H 'Content-Type: application/json' \
   --data-binary '{"columns":["sn","hostname","loginIp","loginType"],"filters":{"or":[{"family":["eq", "ios"]},{"vendor":["eq","ios-xe"]}]},"snapshot":"$last"}'

Access the SNMP data from the IP Fabric

All data related to SNMP configuration for all discovered devices is presented in a different technology table related to SNMP. If in doubt, there's always the search box that will help with finding a specific target. Let's say we are looking for SNMP information, let's just type 'SNMP' and see results. The platform will provide us with information about tables, including SNMP information. We will navigate to SNMP Summary, where we again collect API link.

apiSnmp
API integration with Ansible and Zabbix 1

In the same way, we collected full device inventory, filtering IOS and IOS-XE, we can collect all devices with that has no SNMP community configured.

curl -k -s  https://ipfabric.domain.com/api/v1/tables/management/snmp/summary \
     -u 'username:password' \
     -H 'Content-Type: application/json' \
     --data-binary '{"columns":["id"],"filters":{"communitiesCount":["eq",0],"sn":["eq","'"$sn"'"]},"snapshot":"$last"}'

By comparing Inventory with IOS or IOS-XE devices and SNMP summary table information, where we can find devices with no configured SNMP community, we will get the full list of devices that need to be added to Zabbix and configured with Ansible.

The entire bash script can be seen in our public repository.

Ansible automation

YAMLCodeLogo 1
API integration with Ansible and Zabbix 2

Ansible is an open-source configuration management and application-deployment tool. It helps to automate configuration updates with templates called the 'playbooks' with various network vendors, including servers.

We used the Ansible version 2.5.1. Our simple Ansible playbook will add a new SNMP community and trap the host server as well.

Please note, that you may want to modify the YAML file to fit your environment, we only used 'dummy' SNMP server IP, which may be the Zabbix IP address and SNMP community as an example. The following snippet may need an update per case.

     - name: Add SNMP config
      ios_config:
        lines:
        - snmp-server community newCommunity ro
        - snmp-server host 10.10.10.10 version 2c snmpCommunity
      notify:
      - Save Configuration 

The entire Yaml file can be seen in our public repository.

Zabbix automation

ZABBIXCodeLogo
API integration with Ansible and Zabbix 3

The Zabbix configuration is updated with the help of powerful Zabbix-CLI, which was originally developed by members of the Department for IT Infrastructure at the Center for Information Technology at the University of Oslo, Norway. It's a very user-friendly and powerful solution for connecting to Zabbix's API.

The connector needs to be preinstalled and configured accordingly. For the full installation process, please, follow the documentation.

Thank you for reading!

If you have found this article helpful, please follow our company’s LinkedIn or Blog, where there will be more content emerging.

Groupe de masques 26

Get IP Fabric

Try our self-guided demo and discover how to increase 
your networks visibility & get better time efficiency.
Free Demo | Zero Obligation
Try our Demo
We're Hiring!
Join the Team and be part of the Future of Network Automation
Available Positions
IP Fabric, Inc.
115 BROADWAY, 5th Floor
NEW YORK NY, 10006
United States
This is a block of text. Double-click this text to edit it.
Phone : +1 617-821-3639
IP Fabric s.r.o.
Kateřinská 466/40
Praha 2 - Nové Město, 120 00
Czech Republic
This is a block of text. Double-click this text to edit it.
Phone : +420 720 022 997
IP Fabric UK Limited
Gateley Legal, 1 Paternoster Square, London,
England EC4M 7DX
This is a block of text. Double-click this text to edit it.
Phone : +420 720 022 997
IP Fabric, Inc. © 2024 All Rights Reserved