Rewrite webhook body

Oct 8, 2019, by Karolis Rusenas

update webhook

In this short guide we will create a Python script that reads webhook body, extracts some data and sends a new webhook request to the configured destination.

Prerequisites

Create a bucket

Buckets group webhook input endpoints and output destinations. Go to buckets page and create one:

bucket config

As a destination you can use Webhook Bin service which can provide a free an easy to use webhook testing ground.

Example input and desired output

For the sake of this example, our input JSON payload will be:

{
"status": "succeeded",
"payload": "pipeline was successful",
"user": "harry"
}

Our desired output JSON will be:

{
"summary": "succeeded",
"text": "pipeline was successful, user 'harry'"
}

As you can see, to achieve this we will need to create a new JSON structure based on existing fields.

Write some Python

Relay CLI injects payload via STDIN with some optional data like destination, bucket name and so on. For this use case we will need that additional data.

First things first, let’s craft our testing payload. I used this tool https://tools.knowledgewalls.com/jsontostring to convert my input JSON into a string:

"{\"status\":\"succeeded\",\"payload\":\"pipeline was successful\",\"user\":\"harry\"}"

Now, input JSON (that we care about) will look like:

input.json

{
"type": "webhook",
"meta": {
"output_destination": "https://bin.webhookrelay.com/v1/webhooks/655f0c36-4b53-47e2-8cf8-6db63917c620"
},
"body": "{\"status\":\"succeeded\",\"payload\":\"pipeline was successful\",\"user\":\"harry\"}",
"method": "POST",
}

Let’s write a simple Python app that just prints the payload back to us:

import sys
payload = sys.stdin.read()
print(payload)

Now, to run it:

cat input.json | python rewrite.py
{
"type": "webhook",
"meta": {
"output_destination": "https://bin.webhookrelay.com/v1/webhooks/655f0c36-4b53-47e2-8cf8-6db63917c620"
},
"body": "{\"status\":\"succeeded\",\"payload\":\"pipeline was successful\",\"user\":\"harry\"}",
"method": "POST"
}

We can see the print file

Start relay agent in exec mode

Now, to start relay agent in exec mode we will have to supply several options:

relay forward --bucket rewrite-body --relayer exec --input-mode json --command python rewrite.py