API Fundamentals Course
API Fundamentals
/
Intermediate

Webhooks

Definition

A mechanism for an application to provide real-time data to other applications. It is a user-defined HTTP POST callback triggered by a specific event occurring in the source system.

Explain Like I'm New

Standard API: You call the server and ask 'Did the user pay yet?'. You have to ask every 5 minutes (Polling). Webhook: You give the server your phone number (a URL) and say 'Don't make me ask. Just call me the exact second the user pays.'

Real World Example

GitHub Webhooks. You tell GitHub: 'When someone pushes code to the `main` branch, send an HTTP POST request to `https://my-ci-server.com/deploy`'. GitHub automatically hits your API, triggering your build script instantly.

Common Use Cases

  • •Payment success notifications
  • •CI/CD pipelines
  • •Bot integrations (Slack/Discord)

Interactive Example

// Node.js Express Server RECEIVING a Webhook from Stripe

app.post('/api/webhooks/stripe', (req, res) => {
  const payload = req.body;
  const sigHeader = req.headers['stripe-signature'];

  try {
    // 1. Verify the signature mathematically to prevent hackers
    const event = stripe.webhooks.constructEvent(payload, sigHeader, endpointSecret);

    // 2. React to the event!
    if (event.type === 'payment_intent.succeeded') {
      const paymentData = event.data.object;
      fulfillOrder(paymentData);
    }

    // 3. You MUST return a 200 OK quickly, or Stripe will think your 
    // server is dead and will keep retrying the webhook over and over.
    res.status(200).send();

  } catch (err) {
    res.status(400).send(`Webhook Error: ${err.message}`);
  }
});

Interview Questions

basic

  • In a Webhook architecture, who initiates the HTTP request: Your Server or the Third-Party Service?

intermediate

  • How do you ensure that a Webhook hitting your server actually came from Stripe, and not a hacker trying to fake a payment?

Flash Cards

Question

Who initiates?

Click to reveal answer
Answer

The Third-Party Service (e.g., Stripe, GitHub). They act as the Client, and YOUR server acts as the API endpoint receiving the data.

Question

How to verify?

Click to reveal answer
Answer

Webhook Signatures. Stripe cryptographically signs the payload using a shared secret and puts the signature in the HTTP Header (e.g., `Stripe-Signature`). Your server calculates the math; if the signatures don't match, you reject it as a hacker.