Writing a Webhook | Aayu Technologies
Home Blog Writing a Webhook

Writing a Webhook

Write and deploy your own webhook request handler endpoint to process real-time incoming message/MDN push notifications from AS2 Gateway

17 Jul 2020

Webhook (HTTP) Request Handlers

A webhook request handler is a program, web-app or piece of code that can accept, read and understand an incoming HTTP request; containing HTTP headers and optionally a payload or body, depending on the caller’s (a.k.a. client) intent.

Once written, the handler code has to be deployed - by associating it with:

  • a public (internet visible) IP address/host (e.g. my.webhook.hostname), and
  • a context path (e.g. http://my.webhook.hostname/handler/path/for/messages).

Simplifying Deployment

If you are implementing the webhook application from scratch (e.g. inside a clean physical or virtual machine or container), you may also need to implement a web server or listener that would register and expose your handler and perform the HTTP level semantics (low-level protocol operations) before passing along the request to your logic - and similarly before sending the response back to the invoking client. However if you use one of the modern and popular web deployment methods, this part is already taken care of; making your life much easier:

  • an online service; web hosting provider, virtual private server (VPS), or a dedicated webhook hosting service
  • a prominent web server (Apache, Nginx etc.), servlet container (Jetty, Tomcat etc.) or enterprise middleware platform (e.g. an ESB, or API manager)
  • a cloud-native PaaS or SaaS provider such as Heroku, AWS Lambda, or Google’s App Engine, Apps Script or Cloud Functions

Webhook Examples

Standard

Using scripting languages like Node.JS or Python, you can quickly write a handler to process requests posted by AS2 Gateway:

// a typical Node.JS handler using Express.JS framework:
// https://expressjs.com/en/api.html#req

app.post("/webhook", (request, response) => {
    // read and process data from request
    response.send("success");
});
# a typical Python handler using Flask framework:
# https://flask.palletsprojects.com/en/1.0.x/api/

def hello_http(request):
    # read and process data from request
    return "success"

If you wish to implement the server/listener component as well:

// an Express.JS server

var express = require("express");
var app = express();

// our handler goes here
app.post("/webhook", (request, response) => {
    // read and process data from request
    response.send("success");
});

// run server on port 8080
app.listen(8080, "0.0.0.0");
# webhook.py

from flask import Flask
app = Flask(__name__)

# our handler goes here, with an `app.route` annotation
@app.route("/webhook", methods=["POST"])
def hello_http(request):
    # read and process data from request
    return "success"



# external command (Linux/Mac): run server on port 8080
# FLASK_APP=webhook.py flask run --host=0.0.0.0 --port=8080

A complete Java example using Apache HttpComponents for the HTTP aspect and server component:

import org.apache.http.impl.bootstrap.ServerBootstrap;
import org.apache.http.HttpStatus;
import org.apache.http.entity.StringEntity;

public class WebhookServer {
    public static void main(String[] args) throws Exception {

        ServerBootstrap s = ServerBootstrap.bootstrap();

        s.registerHandler("/webhook", (request, response, ctx) -> {
            // a typical Apache-HC HttpRequest handler
            // read and process data from request, and populate response

            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(new StringEntity("success"));
        });

        s.setListenerPort(8080).create().start();
    }
}

Custom Platform

You can cut down on the overall complexity by using a cloud platform that provides off-the-shelf managed services for HTTP handling and hosting of handler logic.

Python on AWS Lambda, with AWS API Gateway as the HTTP layer (many other languages also supported, including NodeJS):

def handler(event, context):
    return "success"

NodeJS on AWS Lambda:

exports.handler = async (event) => {
    return "success";
};

NodeJS (ExpressJS-compatible) on Google Cloud Functions, with a HTTP trigger (other languages also supported, including Python):

exports.handler = function(request, response) {
    response.send("success");
};

Python (Flask-compatible) on Google Cloud Functions:

def handler(request):
    return "success"

You can deploy and manage such cloud-based custom webhooks quite easily, using cloud-native development tools.