Get Product Types
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 getProductTypes, which require ProductID 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 Product from the 'response' variable and store in 'product' variable.
After that, we create 2 empty list, ID_List and Name_List.
We will create a for-loop where we will loop through all the items in 'product' variable.
As we loop through the items in 'product', we will append the ProductID and ProductName to the ID_List and Name_List respectively.
Then we create a 'if' condition, where we will check if the ProductID passed in, is in the ID_List.
If the ProductID passed in, is in the ID_List, we will retrieve the index of the ProductID in the ID_List, and proceed to return the ProductName in Name_List.
Else, we return "Not Found".
Entire Code:
import requests, json
from functions import url
def getProductTypes(ProductID):
serviceName = 'getProductTypes'
headerObj = {
'Header': {
'serviceName': serviceName,
'userID': '',
'PIN': '',
'OTP': ''
}
}
final_url="{0}?Header={1}".format(url(),json.dumps(headerObj))
response = requests.post(final_url)
product = response.json()['Content']['ServiceResponse']['ProductList']['Product']
ID_List= []
Name_List = []
for i in range(len(product)):
ProductType = product[i]
ID_List.append(ProductType['ProductID'])
Name_List.append(ProductType['ProductName'])
if ProductID in ID_List:
index = ID_List.index(ProductID)
return Name_List[index]
else:
return 'Record not found'
Created with the Personal Edition of HelpNDoc: Easily create Web Help sites