An advanced level example on how to modify the webhooks based on data received from 3rd party API.
While integrating several systems with each other, quite often you need not just transform the webhook but fetch additional data from a 3rd party API or your own service. To do this, use http package which can be imported into your functions.
In this example we will fetch some data from HTTP API and merge it together with the incoming webhook to get a new message:
local http =require("http")local json =require("json")-- API returns a JSON containing our pets and prices:-- {-- "cat": {-- "size": "small",-- "price": 50-- },-- "dog": {-- "size": "medium",-- "price": 120-- },-- "cow": {-- "size": "large",-- "price": 600-- }-- }response, error_message = http.request("GET", "https://gist.githubusercontent.com/rusenask/c1b5840c62a70ea11fdedd9a6aabbd03/raw/8a0177791d94c22fdb9345243392c62ddb10a10f/pets.json")if error_message thenerror(error_message) end-- Parsing response body from the APIlocal api_response, err = json.decode(response.body)if err thenerror(err) end-- Parsing webhook body-- {-- "pet": "cat",-- "quantity": 2 -- }local request_body, err = json.decode(r.RequestBody)if err thenerror(err) endlocal message ="Purchased pet: " .. request_body["pet"] .." | quantity: " .. request_body["quantity"] .." | total:" .. request_body["quantity"] * api_response[request_body["pet"]]["price"] -- Preparing new payloadlocal new_payload = { action="purchased", message= message}local encoded_payload, err = json.encode(new_payload)if err thenerror(err) end-- Set request header to application/jsonr:SetRequestHeader("Content-Type", "application/json")-- Set request method to PUTr:SetRequestMethod("PUT")-- Set modified request bodyr:SetRequestBody(encoded_payload)
Now, if you send a request such as:
{
"pet": "cat",
"quantity": 3
}
To Input our Output in Webhook Relay (that has this Function attached), response is: