Webhook Relay
Search…
Enrich webhooks from 3rd party APIs
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:
1
local http = require("http")
2
local json = require("json")
3
​
4
-- API returns a JSON containing our pets and prices:
5
-- {
6
-- "cat": {
7
-- "size": "small",
8
-- "price": 50
9
-- },
10
-- "dog": {
11
-- "size": "medium",
12
-- "price": 120
13
-- },
14
-- "cow": {
15
-- "size": "large",
16
-- "price": 600
17
-- }
18
-- }
19
response, error_message = http.request("GET", "https://gist.githubusercontent.com/rusenask/c1b5840c62a70ea11fdedd9a6aabbd03/raw/8a0177791d94c22fdb9345243392c62ddb10a10f/pets.json")
20
if error_message then error(error_message) end
21
​
22
-- Parsing response body from the API
23
local api_response, err = json.decode(response.body)
24
if err then error(err) end
25
-- Parsing webhook body
26
-- {
27
-- "pet": "cat",
28
-- "quantity": 2
29
-- }
30
local request_body, err = json.decode(r.RequestBody)
31
if err then error(err) end
32
​
33
local message = "Purchased pet: " ..
34
request_body["pet"] .. " | quantity: " ..
35
request_body["quantity"] .. " | total:" .. request_body["quantity"] * api_response[request_body["pet"]]["price"]
36
​
37
-- Preparing new payload
38
local new_payload = {
39
action= "purchased",
40
message= message}
41
​
42
local encoded_payload, err = json.encode(new_payload)
43
if err then error(err) end
44
​
45
-- Set request header to application/json
46
r:SetRequestHeader("Content-Type", "application/json")
47
-- Set request method to PUT
48
r:SetRequestMethod("PUT")
49
-- Set modified request body
50
r:SetRequestBody(encoded_payload)
Copied!
Now, if you send a request such as:
1
{
2
"pet": "cat",
3
"quantity": 3
4
}
Copied!
To Input our Output in Webhook Relay (that has this Function attached), response is:
1
{
2
"action": "purchased",
3
"message": "Purchased pet: cat | quantity: 3 | total:150"
4
}
Copied!
Copy link