Enrich webhooks from 3rd party APIs

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 then error(error_message) end

-- Parsing response body from the API
local api_response, err = json.decode(response.body)
if err then error(err) end
-- Parsing webhook body
-- {
-- "pet": "cat",
-- "quantity": 2
-- }
local request_body, err = json.decode(r.RequestBody)
if err then error(err) end

local message = "Purchased pet: " ..
request_body["pet"] .. " | quantity: " ..
request_body["quantity"] .. " | total:" .. request_body["quantity"] * api_response[request_body["pet"]]["price"]

-- Preparing new payload
local new_payload = {
action= "purchased",
message= message}

local encoded_payload, err = json.encode(new_payload)
if err then error(err) end

-- Set request header to application/json
r:SetRequestHeader("Content-Type", "application/json")
-- Set request method to PUT
r:SetRequestMethod("PUT")
-- Set modified request body
r: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:

{
"action": "purchased",
"message": "Purchased pet: cat | quantity: 3 | total:150"
}