Python

This tutorial provides you with a step-by-step walkthrough on how to interact with the IoT Connect 365 API

This is not a production-ready application. Please take your time to make it meet your business requirements and production standards.

Steps

Code

keyboard_arrow_down
1
2
3
4
5
# _Step_1
[API]
user=user
password=password
base_url=https://sapiotconnect365.sapdigitalinterconnect.com/api/v1
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/env python
#
# getops.py : get IoT Connect 365 list of known operators
#
import json
import requests
import argparse
import sys
import dialogs
from requests.exceptions import ProxyError

global auth_body, auth_token, useProxies
global TMOUS, STATUS200

demo_user = ""
demo_password = ""
base_url = "https://sapiotconnect365.sapdigitalinterconnect.com/api/v1"
auth_url = base_url + "/authenticate"
endpoint_url = base_url + "/endpoint"
getoperator_url = base_url + "/operator"
STATUS200=200
auth_token=None
verbose = 0
useProxies = 0

def enableProxies() :
    global useProxies
    useProxies = 1 
    return

def disableProxies() :
    global useProxies
    useProxies = 0
    return

def getProxies() :
    global useProxies
    if useProxies :
        return {
            'http': 'http://bluecoat-proxy:8080',
            'https': 'http://proxy.phl.sap.corp:8080'
        }
    return {}

# _Step_2
def getAuthToken():
    global verbose, auth_token
    auth_body = {"username": demo_user, "password": demo_password}
    try :                       # try Digital Interconnect proxies first
        if (verbose) : print("auth 1st try")
        resp = requests.post(auth_url, json=auth_body, proxies=getProxies())
    except ProxyError as exc:                     # otherwise no proxies
        disableProxies()
        if (verbose) :
            print("Oops!",sys.exc_info()[0],"occurred.")
            print(exc)
            print("auth 2nd try")
        resp = requests.post(auth_url, json=auth_body, proxies=getProxies())
    if STATUS200 == resp.status_code :
        if (verbose) : print("authenticated ",resp) 
        auth_token = json.loads(resp.text)['auth_token']
    else :
        print("error**** in auth",resp)
        auth_token = None
    return

def getHeaders():
    global auth_token
    return {'Content-Type': 'application/json',
            'Authorization': 'Bearer ' +auth_token}

def getOps(f,l): # use filter function f on list l of operators
    match = list(filter(f,l))   # filtered list
    for o in match[:]:
        o['title'] = '{:5} {:5} {}'.format(
            o['id'],
            o['country']['country_code'],
            o['name_and_country'])
    return match

def getArgs() :
    parser = argparse.ArgumentParser(description=
        "List the operator identifiers available in the IoT Connect 365 " \
        "system by country name or country code. These identifiers can be"\
        "used by other utilities for example to manage endpoint blacklists."\
        "With no arguments, it takes name from console (like --name))")
    grp = parser.add_mutually_exclusive_group()
    grp.add_argument("-a","--all",
                     action="store_true",help="List all operators")
    grp.add_argument("-e","--endpoints",
                     action="store_true",help="List all endpoints")
    grp.add_argument("-n","--name",
                     help="name search within Country name or Operator name "\
                     "e.g. Austr")
    grp.add_argument("-c","--ccode",
                     help="Country code e.g. 49",type=int)
    parser.add_argument("-v","--verbose",
                        action="store_true")
    return parser.parse_args()

def modify_blacklist(addOp,opId,eId):
    global endpoint_url
    url = endpoint_url + "/" + str(eId) + "/operator_blacklist/" + str(opId)
    h=getHeaders()
    if addOp : return requests.put(url,headers=h,proxies=getProxies())
    else     : return requests.delete(url,headers=h,proxies=getProxies())

def add_blacklist(eId,opId):
    return modify_blacklist(1,opId,eId)

def del_blacklist(eId,opId):
    return modify_blacklist(0,opId,eId)

def get_blacklist(eId):
    h=getHeaders()
    resp = requests.get(endpoint_url + "/" + str(eId)
                        + "/operator_blacklist",
                        headers=h,
                        proxies=getProxies())
    blacklist=json.loads(resp.text)
    rlist=[]
    for b in blacklist[:] :
        rlist.append({'title':'{} {} / {}'.format(b['id'],
                                                 b['country']['name'],
                                                 b['name']),
                      'id':b['id']})
    return rlist


def getOperatorList(matchString) :
    resp = requests.get(getoperator_url,
                        headers=getHeaders(),
                        proxies=getProxies())
    if not(STATUS200 == resp.status_code) :
        print("Error in operator call:",resp.status_code,resp.text)
        quit()
    ops = json.loads(resp.text)
    #
    # now filter by supplied criteria and display
    #
    matchList = getOps(lambda e :
                       matchString.lower() in e['name_and_country'].lower(),
                       ops)
    return matchList

def processShowBlacklist(ept) :
    blist = get_blacklist(ept)
    act = dialogs.list_dialog("Blacklist for " + str(ept),blist)
    return

def processAddBlacklist(ept) :
    matchString = dialogs.text_dialog("Search operators for:","")
    matchList = getOperatorList(matchString)
    operator = dialogs.list_dialog("Add blacklist for " + str(ept),matchList)
    if (operator) :
        add_blacklist(ept,operator['id'])
    return

def processDelBlacklist(ept) :
    blist = get_blacklist(ept)
    operator = dialogs.list_dialog("Delete blacklist for " + str(ept),blist)
    if (operator) :
        del_blacklist(ept,operator['id'])
    return


#############################################################
# begin
# parse out the arguments
#
args = getArgs()
verbose = args.verbose
#
# Create Authorization Token
#
getAuthToken()
if not(auth_token) : quit()
#
#
#
resp = requests.get(endpoint_url + '?sort=-last_updated', # newest first
                    headers=getHeaders(),
                proxies=getProxies())
if not(STATUS200 == resp.status_code) :
    print("Error in endpoint call:",resp.status_code,resp.text)
    exit(2)
endpts = json.loads(resp.text)
if (verbose) : print("Endpoints found: {}".format(len(endpts)))
#if (len(endpts)>0):
#    print("{:>8} {:20.20} {:>16.16} {:>8}".format("Id",
#                                                "Name",
#                                                  "Last Updated",
#                                                  "ICCID"))

# _Step_3
es=[]
for e in endpts[:]:
    es.append(
        {'title':'{:8} {:20.20} {:16.16} ...'.format(
            e['id'],
            e['name'],
            e['last_updated']),
#           e['sim']['iccid'][-5:]),
         'id':e['id']})
i = dialogs.list_dialog("Choose an endpoint",es);
ept=i['id']
#print(i,ept)

#resp = requests.get(endpoint_url + '/{:d}/stats'.format(ept),
#                    headers=getHeaders(),
#                    proxies=getProxies())
#if not(STATUS200 == resp.status_code) :
#    print("Error in endpoint stats call:",resp.status_code,resp.text)
#    exit(2)
#stats = json.loads(resp.text)
#print("current month data volume",
#      stats['current_month']['data']['volume'])

# _Step_4
actions = [{'title':'add to blacklist','n':0},
           {'title':'delete from blacklist','n':1},
        {'title':'show blacklist','n':2}]
act=1
while (act) :
    act = dialogs.list_dialog("Choose an action",actions);
    if (not(act)) : break
    elif (act['n']==0) : processAddBlacklist(ept)
    elif (act['n']==1) : processDelBlacklist(ept)
    elif (act['n']==2) : processShowBlacklist(ept)
    else : exit(2)

quit()

resp = get_blacklist(ept)
blacklist = json.loads(resp.text)
if (len(blacklist)==0) : print ("No blacklist for ",ept)

ops = getOps()
if (ops) :
    for o in ops[:] :
        r = add_blacklist(ept,o['id'])


    #
    # Get list of all operators
    #
    resp = requests.get(getoperator_url,
                        headers=getHeaders(),
                        proxies=getProxies())
    if not(STATUS200 == resp.status_code) :
        print("Error in operator call:",resp.status_code,resp.text)
        quit()
        ops = json.loads(resp.text)
    #
    # now filter by supplied criteria and display
    #
    if   (args.ccode): # filter by country code
        match = getOps(lambda e :
                       int(e['country']['country_code']) == args.ccode,
                       ops)
    elif (args.all) : # don't filter 
        match = getOps(lambda e : 1, ops)
    else            : # filter by name (ignore case)
        if (args.name) : nameMatch = args.name 
        else :
            nameMatch = input("Enter search to match country/operator name " \
                              "(or just hit return for all)")
            match = getOps(lambda e :
                           nameMatch.lower() in e['name_and_country'].lower(),
                           ops)

            quit()