Azure automation runbook Python – webhook data

Question:

I am preparing Azure automation, I am using Python SDK Automation runbook, runbook will be triggered by a webhook. I tested webhook, and I am able to run Python runbook using webhook. Automation Runbook Job status is Completed, I can see output data.

input data

"WebhookName":"webhookname","RequestBody":"{"name": "Mike", "Nazwisko": "Tyson"}","RequestHeader":{"Connection":"keep-alive","Accept":"*/*","Accept-Encoding":"gzip","Host":"XXXzzzWWW.webhook.wus2.azure-automation.net","User-Agent":"python-requests/2.27.1","x-ms-request-id":"AAAbbbCCC"}}

output data

['C:\Temp\ce51on0d.0c4\XXvvBB', '{WebhookName:webhookname,RequestBody:{"name":', '"Mike",', '"Nazwisko":', '"Tyson"},RequestHeader:{Connection:keep-alive,Accept:*/*,Accept-Encoding:gzip,Host:AAAbbbCCC.webhook.wus2.azure-automation.net,User-Agent:python-requests/2.27.1,x-ms-request-id:AAbbCC}}']

Python script for sending webhook

import requests
import json

url = 'webhookURL'
payload = {'name': 'Mike','Nazwisko': 'Tyson'}
requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'})

My question is how can I get, in my Automation Python runbook, specific values from Webhook data. like:

var1 = payload.name
var2 = payload.nazwisko

I was trying with sys module, but it does not work as expected.

import sys

test = str(sys.argv)
print(test)
Asked By: tester81

||

Answers:

Finally I prepared my Azure Automation runbook, and works as expected, below, Python runbook code.

import sys
import json

jsonStr = str(sys.argv)
split_RequestHeader = jsonStr.split('RequestHeader')
split_RequestBody = split_RequestHeader[0].split('RequestBody')
final_format = split_RequestBody[1]
final_format_2 = final_format.lstrip("':").rstrip(",'")
final_format_3 = final_format_2.replace("'",'')
final_format_4 = final_format_3.replace(":,",':')
final_format_5 = final_format_4.replace(",,", ",")
data_dict = json.loads(final_format_5)
print(data_dict)
print(data_dict["var1"])
print(data_dict["var2"])
print(data_dict["var3"])
Answered By: tester81

Thanks for the help here. I solved in a similar manner:

def webhookDataHandler(): 
    Dict = {}
    data = sys.argv[1]
    data = data.replace("{", ',').replace("}", "").replace(""","")
    data = data.split(",")    
    for i in data:
      i = i.replace('\', "")
      try:
        temp = i.split(":")
        Dict[temp[0]] = temp[1]
        print(temp[0], temp[1])
      except:
        pass
    return Dict

The "try" statement helps me overcome errors from nested lists when pushing everything into a dict.

I had to do surgery on the list that argv provided. This just removed the excess syntax and reorganizes things into dictionary format. Hope this helps the next person!

Answered By: Alex Olguin