How to send entity values to API to fetch data?
Sending entity values to API to fetch data
Once the entity value is stored in a variable on the Code step, you can use this variable to send this to the API and fetch the real-time data. You can send this variable as a payload to the API endpoint.
The following is a sample code for fetching order details -
def main(event, context):
"""
event['body'] is a string dict with the following keys:
node, event, user, entities.
Currently, we pass user_id, user_name, full_name, device_platform and language_code in the user dictionary.
Args:
event (dict): Data corresponding to this event
context
Returns
(dict): response with statusCode and the response for the User
"""
body = json.loads(event['body'])
entities = body.get('entities')
user_data = body.get('user')
conversation_details = body.get('conversation_details')
env_variables = body.get("env_variables")
entity = Entities(entities)
order_id = entity.get('capture_track_orderid_copy', '')
order_details = get_order_details(env_variables, order_id)
if 'Statuscode' in order_details:
return order_details
message = get_order_message(order_details)
# get_order_message() returns order details in a button HSL
final_response = {
'status': True,
'message': message
}
response = {'statusCode': 200, 'body': json.dumps(final_response), 'headers': {'Content-Type': 'application/json'}}
return response
def get_order_details(env_variables, order_id):
url = "<API_ENDPOINT>"
payload = {
"order_id": order_id.upper()
}
headers = {
'Content-Type': 'application/json'
}
try:
response = requests.request(
"POST",
url,
headers=headers,
data = json.dumps(payload),
timeout=7
)
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
error = "Timeout Error"
response = generate_response(error)
return response
except Exception as err:
print("Oops: Something Else", err)
error = "Api Failure"
response = generate_response(error)
return response
if response.status_code == 200:
order_details = json.loads(response.text)
order_details = order_details.get('results', {})
return order_details
else:
print("API FAILED. STATUS CODE: ", response.status_code, response.text)
error = "Api Failure"
response = generate_response(error)
return response