Webhook API Integration Tutorial: Real-Time Notifications with InstantAPI
Alex Chen
Developer Advocate
Introduction
When you integrate AI into production applications, polling for results is inefficient and wasteful. Every second your code spends checking "is it done yet?" is a second of wasted compute. Webhooks solve this problem by flipping the model: instead of you asking InstantAPI for results, InstantAPI tells you when results are ready.
In this webhook API integration tutorial, you will learn how to configure webhook endpoints, verify request signatures for security, handle retries gracefully, and build a production-ready webhook listener in both JavaScript and Python.
If you have ever wondered how to receive real-time notifications from an API without polling, this guide is for you.
Why Webhooks Matter for AI Workloads
AI tasks like summarization, sentiment analysis, and data extraction can take variable amounts of time depending on the input size. With a traditional request-response model, your application blocks while waiting. Webhooks decouple the request from the response, allowing your app to remain responsive while heavy AI processing happens in the background.
Key benefits of using webhooks with InstantAPI:
- No polling overhead — save server resources and reduce API calls
- Real-time updates — get notified the instant your task completes
- Better user experience — update your UI as soon as results arrive
- Scalability — handle thousands of concurrent AI tasks without blocking threads
Prerequisites
Before you begin, make sure you have:
Step 1: Register Your Webhook Endpoint
First, register a webhook URL in your InstantAPI dashboard. Navigate to the Webhooks section and add your endpoint URL. InstantAPI will send a verification request to confirm the endpoint is reachable.
JavaScript (Express.js)
const express = require("express");
const crypto = require("crypto");
const app = express();
app.use(express.json());
const WEBHOOK_SECRET = process.env.INSTANTAPI_WEBHOOK_SECRET;
// Webhook endpoint
app.post("/webhooks/instantapi", (req, res) => {
// Acknowledge receipt immediately
res.status(200).json({ received: true });
// Process the webhook payload asynchronously
handleWebhookEvent(req.body);
});
app.listen(3000, () => {
console.log("Webhook listener running on port 3000");
});
Python (Flask)
from flask import Flask, request, jsonify
import hashlib
import hmac
import os
app = Flask(__name__)
WEBHOOK_SECRET = os.environ.get("INSTANTAPI_WEBHOOK_SECRET")
@app.route("/webhooks/instantapi", methods=["POST"])
def handle_webhook():
# Acknowledge receipt immediately
payload = request.get_json()
# Process the webhook payload asynchronously
handle_webhook_event(payload)
return jsonify({"received": True}), 200
if __name__ == "__main__":
app.run(port=3000)
Step 2: Verify Webhook Signatures
Never trust incoming webhook requests blindly. InstantAPI signs every webhook payload with your webhook secret using HMAC-SHA256. Always verify the signature before processing any data.
JavaScript Signature Verification
function verifyWebhookSignature(payload, signature, secret) {
const expectedSignature = crypto
.createHmac("sha256", secret)
.update(JSON.stringify(payload))
.digest("hex");
const trusted = crypto.timingSafeEqual(
Buffer.from(signature, "hex"),
Buffer.from(expectedSignature, "hex")
);
if (!trusted) {
throw new Error("Invalid webhook signature");
}
return true;
}
// Usage in your Express route
app.post("/webhooks/instantapi", (req, res) => {
const signature = req.headers["x-instantapi-signature"];
try {
verifyWebhookSignature(req.body, signature, WEBHOOK_SECRET);
} catch (err) {
console.error("Signature verification failed:", err.message);
return res.status(401).json({ error: "Invalid signature" });
}
res.status(200).json({ received: true });
handleWebhookEvent(req.body);
});
Python Signature Verification
def verify_webhook_signature(payload, signature, secret):
expected = hmac.new(
secret.encode("utf-8"),
msg=request.get_data(),
digestmod=hashlib.sha256
).hexdigest()
if not hmac.compare_digest(expected, signature):
raise ValueError("Invalid webhook signature")
return True
@app.route("/webhooks/instantapi", methods=["POST"])
def handle_webhook():
signature = request.headers.get("X-InstantAPI-Signature")
try:
verify_webhook_signature(
request.get_json(), signature, WEBHOOK_SECRET
)
except ValueError as e:
return jsonify({"error": str(e)}), 401
payload = request.get_json()
handle_webhook_event(payload)
return jsonify({"received": True}), 200
Step 3: Send Async API Requests with a Webhook Callback
Now that your listener is ready, you can make API calls that include a webhook_url parameter. When the task finishes, InstantAPI will POST the result to your endpoint.
JavaScript
const INSTANTAPI_KEY = process.env.INSTANTAPI_KEY;
const API_URL = "https://instantapis.net/api/v1/generate";
async function submitAsyncTask(task, input, options = {}) {
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Authorization": `Bearer ${INSTANTAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
task,
input,
options,
webhook_url: "https://yourserver.com/webhooks/instantapi",
}),
});
const data = await response.json();
console.log("Task submitted, ID:", data.task_id);
return data.task_id;
}
// Submit a summarization task
submitAsyncTask("summarize", longDocumentText, { length: "short" });
Python
import requests
INSTANTAPI_KEY = os.environ.get("INSTANTAPI_KEY")
API_URL = "https://instantapis.net/api/v1/generate"
def submit_async_task(task, input_data, options=None):
headers = {
"Authorization": f"Bearer {INSTANTAPI_KEY}",
"Content-Type": "application/json",
}
payload = {
"task": task,
"input": input_data,
"options": options or {},
"webhook_url": "https://yourserver.com/webhooks/instantapi",
}
response = requests.post(API_URL, json=payload, headers=headers)
data = response.json()
print(f"Task submitted, ID: {data['task_id']}")
return data["task_id"]
# Submit a summarization task
submit_async_task("summarize", long_document_text, {"length": "short"})
Step 4: Process Webhook Events
When a task completes, InstantAPI sends a POST request to your webhook URL with a JSON payload containing the task result, status, and metadata.
JavaScript Event Handler
function handleWebhookEvent(event) {
const { event_type, task_id, status, result, usage } = event;
switch (event_type) {
case "task.completed":
console.log(`Task ${task_id} completed successfully`);
console.log("Result:", result);
console.log("Cost:", usage.cost);
// Store result in your database, update UI, etc.
break;
case "task.failed":
console.error(`Task ${task_id} failed:`, result.error);
// Implement retry logic or alert your team
break;
default:
console.log("Unknown event type:", event_type);
}
}
Python Event Handler
def handle_webhook_event(event):
event_type = event.get("event_type")
task_id = event.get("task_id")
if event_type == "task.completed":
print(f"Task {task_id} completed successfully")
result = event.get("result")
usage = event.get("usage")
print(f"Result: {result}")
print(f"Cost: {usage['cost']}")
# Store result in your database, update UI, etc.
elif event_type == "task.failed":
error = event.get("result", {}).get("error")
print(f"Task {task_id} failed: {error}")
# Implement retry logic or alert your team
else:
print(f"Unknown event type: {event_type}")
Step 5: Handle Retries and Idempotency
Webhooks can be delivered more than once due to network issues. Always design your handler to be idempotent — processing the same event twice should not cause problems.
const processedEvents = new Set();
function handleWebhookEvent(event) {
// Skip duplicate events
if (processedEvents.has(event.task_id)) {
console.log(`Duplicate event for task ${event.task_id}, skipping`);
return;
}
processedEvents.add(event.task_id);
// Process the event as normal
if (event.event_type === "task.completed") {
saveResultToDatabase(event.task_id, event.result);
}
}
For production systems, use a database or Redis to track processed event IDs instead of an in-memory Set.
Best Practices for Webhook Integrations
Conclusion
Webhooks transform your InstantAPI integration from a synchronous bottleneck into a responsive, event-driven architecture. By following this tutorial, you now have a production-ready webhook listener with signature verification, retry handling, and clean event processing.
Ready to get started? Head to your dashboard to register your first webhook endpoint, or explore the full API documentation for all webhook configuration options. You can also test your webhook payloads interactively in the playground before deploying to production.
Ready to try InstantAPI?
Sign up today and get 10 free credits to explore all 6 AI capabilities. No credit card required.
Get 10 Free Credits