0

So I have this long confusion about creating webhook API for my local app. This project is for learning purpose only so I need to understand what is the difference between simple REST API and webhook, in terms of implementation. I know the difference in terms of working but I can't get the technical difference.

For example, when I use Firebase in my web app and use the real-time database to get the updated values on the client-side, it works seamlessly and I don't need to make the POST or GET call every second or minute. It gets updated instantaneously. I know they might not be using webhook as such but rather using web-socket to keep the connection open between a client web app.

Okay now back to the webhook on the local machine - How can I create my own webhook server where the client can hook to the endpoint and get updates automatically.

Let me share some code

WebHook NodeJS server

// Require express and body-parser
const express = require("express")
const bodyParser = require("body-parser")

// Initialize express and define a port
const app = express()
const PORT = 3000

// Tell express to use body-parser's JSON parsing
app.use(bodyParser.json())

// Start express on the defined port
app.listen(PORT, () => console.log(` Server running on port ${PORT}`))

app.use(bodyParser.json())
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    if (req.method === 'OPTIONS') {
        var headers = {};
    // headers["Access-Control-Allow-Origin"] = req.headers.origin;
        headers["Access-Control-Allow-Origin"] = "*";
        headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
        headers["Access-Control-Allow-Credentials"] = false;
        headers["Access-Control-Max-Age"] = '86400'; // 24 hours
        res.writeHead(200, headers);
       res.end();
    } else {
        next();
    }
})


const processSomething = callback => {
  setTimeout(callback, 1000);
}


app.post("/hook", (req, res) => {
    console.log(req.body) // Call your action on the request here
     processSomething(() => {
          res.status(200).send({
               id: "ABC123",
               message: "New record added!"
          });
     });  
})

Web client running

index.html -

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Webhook Test Client</title>
</head>
<body>
    <h1>Hello World</h1>
    <div class="result">Data</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $.post("http://localhost:3000/hook", function (data) {
            console.log("data -- >",data);
            $(".result").html("data -- > " + data);
        });
    </script>
</body>
</html>

nodejs to server the page -

const express = require('express'),
    app = express(),
    server = app.listen(1000);

app.use(express.static('public'));

console.log("server running...");

I have seen so many tutorials on Medium or other tech blogs but they mostly talk about connecting to webhook API hosted somewhere on a webserver that they have built as service or something.

So far I have understood and not understood is that.

  1. I can't make webhook API call from the web client.
  2. Only nodejs client-server can make webhook calls to the webhook endpoint. What I mean by this is - in my example webhook can't be called from HTML page but server serving that page can make the call. Maybe I am wrong.
  3. Webhook is not so different from REST API.
  4. Webhook is not made for the web client.

I will update this question as I get relevant replies and testing them.

Why I am interested in webhook because I wanted to create an API where the user doesn't have to make calls to an API to get an update but at the same time the API can be used from the web client, like firebase but avoid WebSocket at the same time. Or can I avoid WebSocket?

Edit: - So I got confirmation on webhooks are designed for server-to-server communication.

Most of the demos available online are using githud, discord, zapier, etc to create webhooks. Can you please share where we can just make custom webhooks without using third party libs ?

Greyfrog
  • 926
  • 1
  • 8
  • 19
  • Ordinarily a *webhook* originates from a server when something interesting happens. For example, github has a webhook for pushes. A github user can specify one or more URL for the webhook, and then whenever the repo gets a push, from anybody,, some server code at Github sends requests to all those URLs. The webhook is a way for one server to tell another something has happened. Please [edit] your question to explain more about your use of the term *webhook*. It doesn't seem to match the usual usage. – O. Jones Nov 06 '20 at 15:58
  • @O.Jones First of all thank you for the reply. I know what webhook is and that's exactly what I have explained. I just try to explained in layman term but that exactly what I mean. Also, I guess you are confirming that webhooks are designed to communicate and update between servers but not between server and a client, Am I right? Another one is, if that the case can you tell me how can I make my own webhook servers on my local machine which can talk to each other with webhooks. Thank you :) :) – Greyfrog Nov 06 '20 at 17:11

0 Answers0