AirVantage API call example

Connection to server

The first step is to authenticate against AirVantage platform.

As an example, we will use the oauth Resource Owner Flow, given a username and a password as well as a client id and client secret that you can grab adding a new "API client" in the AirVantage UI. So in the following cell, you'll have to replace the values for the variables:

base_url
client_id
client_secret

At first, input your username and password hacking the notebook with some HTML and javascript:


In [1]:
from IPython.display import HTML

base_url = "https://<AirVantage server>"
client_id = "<your client id>"
client_secret = "<your client secret>"

input_form = """
<div style="background-color:gainsboro; border:solid black; width:300px; padding:20px;">
UserName: <input type="text" id="username"><br>
Password: <input type="password" id="password"><br>
<button onclick="set_credentials()">Set credentials</button>
</div>
"""

javascript = """
<script type="text/Javascript">
    function set_credentials(){
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;
        var set_username = "username = '" + username + "'";
        var set_password = "password = '" + password + "'";
        var kernel = IPython.notebook.kernel;
        kernel.execute(set_username);
        kernel.execute(set_password);
        alert("done!")
    }
</script>
"""

HTML(input_form + javascript)


Out[1]:
UserName:
Password:

Then run the following example that:

  • connect to the platform
  • request a token
  • display the platform response as raw text

In [3]:
import requests
import json

authentication_api_url = base_url + "/api/oauth/token?grant_type=password&username=" + username + "&password=" + password
authentication_api_url += "&client_id=" + client_id + "&client_secret=" + client_secret

response = requests.get(authentication_api_url, verify=False)

print("response status:")
print(response)
print("response content:")
print(json.dumps(response.json(), sort_keys=True, indent=4, separators=(',', ': ')))


response status:
<Response [200]>
response content:
{
    "access_token": "7b16c8b5-30f9-4790-9579-8d662e883e8a",
    "expires_in": 86399,
    "refresh_token": "7899afa3-ee9d-4ef8-81b1-33ac3c1eff2c",
    "token_type": "bearer"
}

That's fine. Next step is to decode json returned data:


In [4]:
import requests

authentication_api_url = base_url + "/api/oauth/token?grant_type=password&username=" + username + "&password=" + password
authentication_api_url += "&client_id=" + client_id + "&client_secret=" + client_secret

response = requests.get(authentication_api_url, verify=False)

access_token = response.json().get("access_token")
refresh_token = response.json().get("refresh_token")

print("access token = " + access_token + ", refresh token = " + refresh_token)


access token = 60c495cc-0127-4861-804a-ee1aaa886767, refresh token = 83854a95-b790-4b24-a9f4-9ba2371c9b43

Getting a list of systems

Now a more usefull piece of code that will return a list of systems:


In [5]:
import requests
import json
from pandas import DataFrame

def get_access_token(base_url, username, password, client_id, client_secret):
    authentication_api_url = base_url + "/api/oauth/token?grant_type=password&username=" + username + "&password=" + password
    authentication_api_url += "&client_id=" + client_id + "&client_secret=" + client_secret
    response = requests.get(authentication_api_url, verify=False)
    access_token = response.json().get("access_token")
    return access_token

def get_systems(base_url, access_token):
    systems_api_url = base_url + "/api/v1/systems?fields=uid,name,data"
    systems_api_url += "&access_token=" + access_token
    response = requests.get(systems_api_url, verify=False)
    return response.json().get("items")

def get_dataframe_from_systems(systems):
    uids = []
    network_service_types = []
    rssi_levels = []
    for system in systems:
        data = system["data"]
        uids.append(system["uid"])
        network_service_types.append(data["networkServiceType"])
        rssi_levels.append(data["rssiLevel"])
    return DataFrame({"uid": uids, "network service type": network_service_types, "rssi level": rssi_levels})

access_token = get_access_token(base_url, username, password, client_id, client_secret)
systems = get_systems(base_url, access_token)
df = get_dataframe_from_systems(systems)

# display the first 10 systems
df[:10]


Out[5]:
network service type rssi level uid
0 UNKNOWN NO_REPORT 4d110339028043efadb406609d05e48c
1 UNKNOWN NO_REPORT 2b31ef63ea72431a835fe4698e2c33b4
2 HSPA+ GOOD faa723dca2e74bb29fcda8562f3289c6
3 HSPA+ GOOD 0281c3ef7f3d40ebbb23613d61a39d41
4 UNKNOWN NO_REPORT be43cfe5a99e47a8a03be3106aab8f4a
5 UNKNOWN NO_REPORT b4835e34545841e682f08dd1a4dad1bc
6 UNKNOWN NO_REPORT 226e722788434f3681ed8d333284430d
7 UNKNOWN NO_REPORT d123f47032c147519200875d74224c52
8 LTE EXCELLENT c0de410ea8bf4b7b9064e51f6da24f80
9 UNKNOWN NO_REPORT f687fcd8bb514353b85310f75d99dc2e

Drawing a pie chart (network type distribution)

Let's plot the network service type distribution with a pie-chart:


In [8]:
%matplotlib inline
import requests
import json
import matplotlib.pyplot as plt

network_type_counters = {'NONE': 0, 'UNKNOWN': 0, 'GSM': 0, 'EDGE': 0, 'UMTS': 0, '3G': 0, 'HSPA': 0, 'HSPA+': 0, 'LTE': 0}
color_map = {'NONE': 'black', 'UNKNOWN': 'white', 'GSM': 'green', 'EDGE': 'blue', 'UMTS': 'orange', '3G': 'brown', 'HSPA': 'cyan', 'HSPA+': 'magenta', 'LTE': 'red'}

def get_access_token(base_url, username, password, client_id, client_secret):
    authentication_api_url = base_url + "/api/oauth/token?grant_type=password&username=" + username + "&password=" + password
    authentication_api_url += "&client_id=" + client_id + "&client_secret=" + client_secret
    response = requests.get(authentication_api_url, verify=False)
    access_token = response.json().get("access_token")
    return access_token

def get_systems(base_url, access_token):
    systems_api_url = base_url + "/api/v1/systems?fields=uid,name,data"
    systems_api_url += "&access_token=" + access_token
    response = requests.get(systems_api_url, verify=False)
    return response.json().get("items")

def get_dataframe_from_systems(systems):
    uids = []
    network_service_types = []
    rssi_levels = []
    for system in systems:
        data = system["data"]
        uids.append(system["uid"])
        network_service_types.append(data["networkServiceType"])
        rssi_levels.append(data["rssiLevel"])
    return DataFrame({"uid": uids, "network service type": network_service_types, "rssi level": rssi_levels})

def update_counters(systems):
    for system in systems:
        data = system["data"]
        network_type_counters[data["networkServiceType"]] += 1
        
def draw_pie():
    labels = []
    sizes = []
    colors = []
    explode = []
    for network_type in network_type_counters:
        labels.append(network_type)
        sizes.append(network_type_counters[network_type])
        colors.append(color_map[network_type])
        if (network_type == 'UNKNOWN'):
            explode.append(0.1)
        else:
            explode.append(0)
    plt.pie(sizes, labels=labels, colors=colors, explode=explode, shadow=True)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    plt.show()
    
access_token = get_access_token(base_url, username, password, client_id, client_secret)
systems = get_systems(base_url, access_token)
update_counters(systems)
draw_pie()


That's it for now!