Skip to content
Vendrix
← Back to blog

How to Connect Applications with APIs and Webhooks

An API is a request interface: your application can call it on demand or at regular intervals (polling). A webhook is a push notification pattern: when an event occurs, the sender posts a request to a URL you configured. A reliable connection also ne

Vendrix · · 7 min

How to Connect Applications with APIs and Webhooks

An API is a request interface: your application can call it on demand or at regular intervals (polling). A webhook is a push notification pattern: when an event occurs, the sender posts a request to a URL you configured. A reliable connection also needs authentication, error handling, duplicate protection, retries, and a way to verify the actual outcome.

The example below receives a signed GitHub webhook, stores it durably in PostgreSQL, and responds quickly. A worker can then call a business API. The code is a pattern to adapt: no GitHub repository, server, payment account, or production API was connected or tested for this article.

API or webhook: which one should you use?

With an API, your application starts the exchange. It can request a product list, create an order, or check a status. You need to know the HTTP method, endpoint, parameters, expected format, authentication, and rate limits.

With a webhook, the provider sends a notification after an event, such as a payment status change or a new support ticket. You provide a receiving URL and choose which events to subscribe to. A webhook commonly uses an HTTP request to your endpoint, so APIs and webhooks are not opposing protocols. Polling instead means calling an API repeatedly to look for changes, with a delay and additional requests. A webhook alone may not prove an object’s current state; when order or exact state matters, your application may need to retrieve the resource from the API.

The two mechanisms work together: a webhook signals an event; your application validates and stores that notification; it can then call an API to retrieve the current object or perform an authorized action.

Describe the flow before coding

Write down these details for each integration:

1. What event starts the flow, and which service sends it?

2. What data does the receiving application need?

3. How will you verify that the request is authentic?

4. Which key identifies the same event when it is delivered again?

5. Which API will the application call next, and with what permissions?

6. What exact result allows you to call the action successful?

7. What happens if the database or destination service is unavailable?

Subscribe only to relevant events. Store secrets in a secret manager or protected environment variables. Enforce permissions on the server, even if a client or interface claims a user is authorized.

Example: receive a GitHub webhook with Node.js

The following code is a minimal receiver. It verifies GitHub’s signature against the original request bytes, rejects invalid signatures, and places selected events in a PostgreSQL table. The unique constraint prevents a redelivery with the same X-GitHub-Delivery value from creating a second job.

Install the dependencies in a Node.js project:

bash

npm install express pg

Create the table first:

sql

CREATE TABLE webhook_inbox (

provider text NOT NULL,

delivery_id text NOT NULL,

event_type text NOT NULL,

payload jsonb NOT NULL,

status text NOT NULL DEFAULT 'pending'

CHECK (status IN ('pending', 'processing', 'done', 'failed')),

attempts integer NOT NULL DEFAULT 0,

received_at timestamptz NOT NULL DEFAULT now(),

PRIMARY KEY (provider, delivery_id)

);

Set DATABASE_URL and GITHUB_WEBHOOK_SECRET in the server’s secure environment. Do not add real values to the repository. Example server.mjs:

js

import express from "express";

import pg from "pg";

import { createHmac, timingSafeEqual } from "node:crypto";

const { Pool } = pg;

const app = express();

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

const secret = process.env.GITHUB_WEBHOOK_SECRET;

if (!secret) throw new Error("GITHUB_WEBHOOK_SECRET is required");

app.post(

"/webhooks/github",

express.raw({ type: "application/json", limit: "1mb" }),

async (req, res) => {

const signature = req.get("x-hub-signature-256") ?? "";

const deliveryId = req.get("x-github-delivery");

const eventType = req.get("x-github-event");

if (!Buffer.isBuffer(req.body) || !deliveryId || !eventType) {

return res.sendStatus(400);

}

const expected = Buffer.from(

sha256=${createHmac("sha256", secret).update(req.body).digest("hex")}

);

const received = Buffer.from(signature);

if (expected.length !== received.length || !timingSafeEqual(expected, received)) {

return res.sendStatus(401);

}

let payload;

try {

payload = JSON.parse(req.body.toString("utf8"));

} catch {

return res.sendStatus(400);

}

// Keep only the event types the integration actually needs.

if (eventType !== "issues" || !["opened", "closed"].includes(payload.action)) {

return res.sendStatus(204);

}

try {

const saved = await pool.query(

INSERT INTO webhook_inbox (provider, delivery_id, event_type, payload)

VALUES ('github', $1, $2, $3::jsonb)

ON CONFLICT (provider, delivery_id) DO NOTHING

RETURNING delivery_id,

[deliveryId, eventType, JSON.stringify(payload)]

);

return res.status(202).json({

accepted: true,

duplicate: saved.rowCount === 0,

});

} catch {

// The event was not durably stored. Ask the sender to retry where supported.

return res.sendStatus(503);

}

}

);

app.listen(3000);

In GitHub, create an HTTPS webhook, select only the events needed, and set a random high-entropy secret. GitHub signs the body with HMAC-SHA256 and sends the signature in X-Hub-Signature-256. Verify the original, unmodified body with a constant-time comparison. X-GitHub-Delivery helps recognize ordinary redeliveries, but this header is not included in the body signature; do not treat it as proof of authenticity or complete replay protection. Keep the secret on your server and make downstream business effects idempotent too.

The receiver sends 202 Accepted only after the insert is durable. This means the event was accepted for processing; it does not mean a later business action has completed. GitHub expects a 2xx response within 10 seconds, so production must bound database connection and write waits to meet that deadline. If the event was not durably stored, return an error instead of accepting it. Also add schema validation, a strict payload limit, logs without secrets, and a retention policy. The schema provides an inbox, but this example does not include the complete worker for claiming jobs, tracking attempts, retrying, and recording terminal failure. This is an instructional example, not a server ready to expose without review.

Process the event without creating duplicates

A worker reads a pending job, briefly claims it, and marks it processing. If it stops, an expired claim should be recoverable. The worker validates the event and business state, then calls the destination API.

For a write POST, do not assume retrying is harmless. The HTTP RFC distinguishes idempotent methods and advises against automatically repeating a non-idempotent request unless you know the first attempt was not applied or have made the operation repeat-safe. An API may document an Idempotency-Key; use the same key for every retry of the same business effect. In the worker example, keep supportsIdempotencyKey disabled unless the API confirms support. If it does not, implement deduplication in your own application, for example with a unique external reference and a state check before creating anything.

Example request shape, only when the connected API documents support for this key:

bash

curl -X POST "$API_BASE_URL/v1/orders" \

-H "Authorization: Bearer $API_TOKEN" \

-H "Content-Type: application/json" \

-H "Idempotency-Key: $OPERATION_ID" \

-d '{"external_reference":"<BUSINESS_REFERENCE>","items":[{"sku":"SKU-100","quantity":1}]}'

Limit the token to the required operations and store it outside the code. A 2xx response may not by itself confirm an order: validate the response body and returned identifier against the API contract, then save that identifier. Report success to a customer only after this check.

Handle retries and errors

Providers do not all use the same redelivery policy. Stripe retries some events for several days and does not guarantee event ordering. GitHub documents X-GitHub-Delivery and lets you request redelivery, but verify retry behavior for the webhook type you use. Keep your own event history instead of relying on the provider as the only queue.

A careful retry policy separates cases:

- Authentication or validation 4xx: fix credentials or input; do not retry the same request forever.

- 429 or 503: honor Retry-After when present; otherwise use bounded backoff with jitter.

- Timeout or dropped connection: the effect may already have happened; check state or reuse the same idempotency key before trying again.

- Permanent failure: retain a visible failure state, alert an operator, and offer a controlled replay.

Never send “order created” just because a webhook arrived or a model generated a message. Base the confirmation on the API’s verified response and include its returned reference when available.

Test before production

Use the provider’s test environment and check at least: missing signature, invalid signature, valid event, same delivery ID twice, unexpected event, unavailable database, API 401/403, 429, 5xx, timeout, and redelivery after recovery. Verify the inbox rows and final state in the target application.

Logs should help you trace an operation without exposing keys or retaining unnecessary personal data. Record the delivery ID, event type, correlation ID, attempt count, HTTP status, timestamps, and returned resource ID. Remove or minimize the payload after processing according to diagnostic needs and applicable rules.

In summary

An API lets your application request or change data; a webhook lets a service announce that an event occurred. A reliable integration verifies the signature, stores the event before accepting it, deduplicates redeliveries, processes work outside the response path, and repeats writes only with a documented idempotency strategy. Those safeguards make the connection verifiable instead of simply wiring two URLs together.

Sources

- IETF — RFC 9110: HTTP Semantics

- GitHub Docs — Validating webhook deliveries

- GitHub Docs — Best practices for using webhooks

- GitHub Docs — Using webhooks

- Stripe Docs — Receive Stripe events in your webhook endpoint

- Zapier — Webhook vs API