Back to all posts

What is Webhooks? How it different from API?


A webhook and an API (Application Programming Interface) are both methods for cummunication between different software systems.
But they operate in distinct ways:

Key Differences

  • Trigger Mechanism: Webhooks are triggered by events, while APIs require explicit requests.
  • Communication Flow: Webhooks push data automatically when an event occurs, whereas APIs require the client to pull data by making requests.
  • Real-Time vs. Polling: Webhooks provide real-time updates, whereas APIs may need polling to achieve similar functionality.
  • Implementation Use Cases: Webhooks are ideal for scenarios where real-time data is needed immediately upon an event, such as notifications, while APIs are better suited for more complex interactions and operations on data.

Example Use Cases

  • Webhook: When a new order is placed on an e-commerce platform, a webhook can immediately send order details to a fulfillment service.
  • API: A mobile app retrieves the latest user data from a server whenever the app is opened or refreshed by making an API call.

Send automated Discord messages through Webhooks using JavaScript.

Here i am using a web hook from my discord. Using this I am adding message to general chat section.

 <body>
    <button onclick="sendMessage()">Send</button>
  </body>

  <script>
    function sendMessage() {
      const request = new XMLHttpRequest();
      request.open("POST", "https://discord.com/api/webhooks/12674*******02****76/atlcWUFKDe_lmM*********z077nAITmvRUVvsurn********ukocuxHX*****");

      request.setRequestHeader('Content-type', 'application/json');

      const params = {
        username: "My Webhook Name",
        avatar_url: "",
        content: "The message to send"
      }

      request.send(JSON.stringify(params));
    }
  </script>

Output:

Resource: