Handling source data
Until now, the only purpose of the requests that we sent from ReqBin to our webhook URL was to trigger the package. The package did not contain any logic to handle the data that was sent to it.
We will now improve that.
First, add a log line to the package to print the data that was sent to it. Replace the "Hello, world!" line with the following:
log("Incoming message", source);
The source variable is a special standard variable that is
always available to a package. For inbound webhooks, it reflects the content of the request, including the request
headers and request body.
Let's take a look at what's sent to our package.
Switch to ReqBin. Underneath the input field for the URL, click on the Body tab, select "JSON" from the radio button options, and add the following to the text field:
{ "searchQuery": "phone" }
Next, press Send to send another POST request to our webhook URL.
Go back to the automator, refresh the package logs and check the results. The should look something like this:
{
"body": {
"searchQuery": "phone"
},
"headers": {
"accept": "...",
"...": "..."
}
}
Great! The data was successfully received by the package, which means we can use it in our package logic.
The DummyJSON service supports searching products. We will use
the searchQuery parameter to search for products, provided that it is present in the webhook payload.
Remove the following line from the package:
const response = rest_get("/products", "DummyJSON");
Replace it with the following:
let url = "/products";
if (source.body.searchQuery) {
url += `/search?q=${source.body.searchQuery}`;
}
const response = rest_get(url, "DummyJSON");
The rest of the package stays the same, so the full code, except the header comment, should now look like this:
log("Incoming message", source);
let url = "/products";
if (source.body.searchQuery) {
url += `/search?q=${source.body.searchQuery}`;
}
const response = rest_get(url, "DummyJSON");
const products = response.products.slice(0, 10);
const productTitles = products.map(product => product.title);
log("Products", productTitles);
rest_post("/", { products: productTitles }, "Webhook.site");
Save the package and trigger another POST request to our webhook URL from ReqBin.
In a few moments, the package should have run and webhook.site should have received the results:
{
"products": [
"Apple AirPods Max Silver",
"Apple iPhone Charger",
"..."
]
}
This concludes the tutorial. You have learned how to create a package, how to trigger it from the outside world, and how to configure accounts so that your package can send and retrieve data from external services.
The next tutorial will show you how to use services and templates to build a web application with the automator.