How to Use Webhook in API: Simple Guide with Example
To use a
webhook in an API, you provide a URL endpoint where the API can send real-time data via HTTP POST requests. Your server listens to this URL and processes the incoming data automatically when events happen.Syntax
A webhook setup typically involves these parts:
- Webhook URL: The endpoint on your server that receives data.
- Event Trigger: The API event that causes data to be sent.
- HTTP Method: Usually a
POSTrequest carrying a JSON payload. - Response: Your server usually responds with a
200 OKstatus to acknowledge receipt.
http
POST /webhook-endpoint HTTP/1.1 Host: yourserver.com Content-Type: application/json { "event": "event_name", "data": { ... } }
Example
This example shows a simple Node.js server using Express to receive webhook POST requests and log the data.
javascript
import express from 'express'; const app = express(); app.use(express.json()); app.post('/webhook', (req, res) => { console.log('Webhook received:', req.body); res.status(200).send('Received'); }); app.listen(3000, () => { console.log('Server listening on port 3000'); });
Output
Server listening on port 3000
Webhook received: { event: 'order_created', data: { id: 123, total: 49.99 } }
Common Pitfalls
- Not verifying webhook source: Always verify the request comes from the trusted API to avoid fake data.
- Ignoring response status: If your server doesn't respond with
200 OK, the API may retry sending the webhook. - Not handling retries: Webhooks may be sent multiple times; make your processing idempotent.
- Missing security: Use secret tokens or signatures to secure your webhook endpoint.
javascript
/* Wrong: No verification and no response */ app.post('/webhook', (req, res) => { processData(req.body); // No response sent }); /* Right: Verify and respond */ app.post('/webhook', (req, res) => { if (!verifySignature(req.headers['x-signature'], req.body)) { return res.status(403).send('Forbidden'); } processData(req.body); res.status(200).send('OK'); });
Quick Reference
| Step | Description |
|---|---|
| 1. Provide Webhook URL | Give the API a URL to send event data. |
| 2. Listen for POST Requests | Your server must accept HTTP POST with JSON payload. |
| 3. Verify Requests | Check signatures or tokens to confirm authenticity. |
| 4. Process Data | Handle the event data as needed in your app. |
| 5. Respond with 200 OK | Acknowledge receipt to stop retries. |
Key Takeaways
A webhook is a URL your API calls with event data via POST requests.
Always verify webhook requests to ensure they come from trusted sources.
Respond with HTTP 200 status to acknowledge and prevent retries.
Make webhook processing idempotent to handle repeated calls safely.
Secure your webhook endpoint using tokens or signatures.