Get Affinity List
We will first import "request" and "json" module, as we need those module for calling the API
Then, we will import our own url function from a file called functions.py, which can be referred to in the "Common Stuff" section linked at the bottom.
Next, we create a function getAffinityList, which require AffinityID to be passed in.
Inside the function, we will declare the serviceName and build the headerObj straight.
Then, we will create the final url, where we will use the url() function to get the API url, and append the headerObj to the API url.
We will then post the final_url and store the server response in the variable "response".
We will then retrieve a list of Affinitiy from the 'response' variable and store in Affinity variable.
After that, we create 3 empty list, ID_List and Level1_List and Level2_List.
We will create a for-loop where we will loop through all the items in 'types' variable.
As we loop through the items in 'types', we will append the AffinityID, Level1 and Level2 to the ID_List, Level1_list and Level2_List respectively.
Then we create a 'if' condition, where we will check if the AffinityID passed in, is in the ID_List.
If the AffinityID passed in, is in the ID_List, we will retrieve the index of the AffinityID in the ID_List, and proceed to return the Level1 and Level2 in Level1_List and Level2_List respectively.
Else, we return "Not Found".
Entire Code:
import requests, json
from functions import url
def getAffinityList(AffinityID):
serviceName = 'getAffinityList',
headerObj = {
'Header': {
'serviceName': serviceName,
'userID': '',
'PIN': '',
'OTP': ''
}
}
final_url="{0}?Header={1}".format(url(),json.dumps(headerObj))
response = requests.post(final_url)
Affinity = response.json()['Content']['ServiceResponse']['AffinityList']['Affinity']
ID_List= []
Level1_List = []
Level2_List = []
for i in range(len(Affinity)):
AffinityType = Affinity[i]
ID_List.append(AffinityType['AffinityID'])
Level1_List.append(AffinityType['Level1'])
Level2_List.append(AffinityType['Level2'])
if AffinityID in ID_List:
index = ID_List.index(AffinityID)
return Level1_List[index], Level2_List[index]
else:
return 'Record not found'
Created with the Personal Edition of HelpNDoc: Create iPhone web-based documentation