AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Integrating Elai.io REST API and Webhooks: Automated Bulk Video Generation from Dynamic Templates

Félix Briones · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Scaling personalized avatar video production inside enterprise LMS platforms, customer onboarding flows, and automated marketing engines quickly exposes the limits of browser-based editing. Manually assembling slides, toggling avatar assets, and pasting bespoke voiceover scripts in a graphical user interface cannot support hundreds or thousands of unique videos each week.

At 365Finds, our architectural assessment is clear: engineering teams should strictly decouple visual presentation from data ingestion. Graphic designers and instructional authors should craft master templates within the Elai.io Builder using dynamic placeholders, while backend developers drive rendering completely headless through the Elai.io REST API and ingest completed assets via asynchronous webhooks. Treating video generation as an asynchronous queue-backed pipeline eliminates manual friction and ensures consistent render execution.

This guide provides an end-to-end technical blueprint for authenticating with the Elai.io API (v1), structuring parameterized payloads for dynamic templates, establishing cryptographically verified webhook receivers, and building resilient reconciliation loops that withstand transient network failures.


1. Authentication & API Operational Boundary

All Elai.io API endpoints operate under https://apis.elai.io/api/v1. Authentication relies on Bearer tokens scoped to a workspace rather than individual user accounts.

Authorization: Bearer <YOUR_WORKSPACE_API_TOKEN>
Accept: application/json
Content-Type: application/json

Critical Account and Permission Rules


2. Dynamic Template Architecture: Placeholders and Media Anchors

Enterprise pipelines require rapid iteration without constantly updating backend JSON schemas. The cleanest architectural pattern utilizes a published template video inside Elai.io containing dynamic variables.

flowchart LR
    A[Instructional Designer<br/>Builds Master Video in UI] --> B[Insert Variables:<br/>Speech & Canvas Tags]
    B --> C[Extract Video ID &<br/>Canvas Media API IDs]
    C --> D[Backend Service<br/>POST /videos/renderTemplate]

Text and Speech Placeholders

In the Elai.io Builder, define dynamic text using double curly brackets {{tag}}. Placeholders are supported across three distinct layers:

  1. Speech Scripts: Avatar narration (e.g., Welcome {{first_name}} to the {{department}} team at {{company}}.).
  2. Video Titles: Custom naming for LMS indexing (e.g., Onboarding - {{first_name}} {{last_name}}).
  3. Canvas Text Elements: Visual labels, lower thirds, or slide bullet points.

Constraint: Placeholder keys must use English alphanumeric characters, underscores, dashes, or spaces (e.g., {{employee_name}} or {{first name}}). Special characters like punctuation or non-ASCII characters in key names will fail validation.

Dynamic Canvas Media (Images and Video B-Roll)

To replace company logos, user profile pictures, or contextual screenshots dynamically:

  1. Add a placeholder image or video element to the canvas in the Elai.io UI.
  2. Select the object in the editor sidebar to retrieve its unique numeric API ID (e.g., 457597335176).
  3. In your API render payload, provide this API ID as the object key and pass a publicly accessible HTTPS URL as the value.

3. Bulk Rendering via POST /videos/renderTemplate/{videoId}

While Elai.io provides a raw slide construction endpoint (POST /videos) that accepts Fabric.js canvas trees, 365Finds strongly advises against generating entire canvas layouts programmatically unless you are rendering non-standard geometric graphs. Building complex multi-slide videos from raw JSON is fragile and incurs significant maintenance overhead.

The production-grade method is calling POST /videos/renderTemplate/{videoId}, where {videoId} represents your published template video.

Payload Specification

{
  "requestId": "batch-onboarding-cohort-2026-11-04",
  "tags": ["onboarding", "automated-pipeline", "cohort-q4"],
  "fitTextBox": true,
  "public": false,
  "render": true,
  "emailNotification": false,
  "templateData": [
    {
      "first_name": "Elena",
      "department": "Platform Architecture",
      "company": "Acme Corp",
      "457597335176": "https://assets.acme.internal/badges/elena-arch.png"
    },
    {
      "first_name": "Marcus",
      "department": "Security Operations",
      "company": "Acme Corp",
      "457597335176": "https://assets.acme.internal/badges/marcus-sec.png"
    }
  ]
}

Key Parameter Controls

cURL Invocation Example

curl -X POST "https://apis.elai.io/api/v1/videos/renderTemplate/63ea63c1c00dfe1a72cc7426" \
  -H "Authorization: Bearer sec_live_99f01ab2c884" \
  -H "Content-Type: application/json" \
  -d '{
    "requestId": "onboarding-req-8891",
    "fitTextBox": true,
    "emailNotification": false,
    "templateData": [
      {
        "first_name": "Sarah",
        "department": "Customer Engineering"
      }
    ]
  }'

Understanding Asynchronous Response Semantics

When submitting templateData with a single item, the API returns HTTP 200 with both accepted: true and the newly allocated videoId:

{
  "accepted": true,
  "requestId": "onboarding-req-8891",
  "videoId": "64bc19df82aa3190ef22a104"
}

When submitting multiple items (e.g., 2 to 200 rows), the API response returns only:

{
  "accepted": true,
  "requestId": "onboarding-req-8891"
}

An HTTP 200 OK indicates only that your batch has been successfully enqueued into Elai.io's rendering cluster. Deep validations—such as avatar duration limits or account credit exhaustion—run asynchronously post-acceptance.


4. Configuring Webhooks and Cryptographic Signature Verification

Because rendering high-fidelity avatars takes anywhere from 45 seconds to several minutes per minute of output, polling is wasteful. Elai.io dispatches asynchronous webhook events for video states.

Workspace Subscription and the Ordering Rule

Webhooks are configured at the workspace level (one active webhook URL per workspace).

  1. Register the Webhook Endpoint:

    curl -X POST "https://apis.elai.io/api/v1/webhook/" \
      -H "Authorization: Bearer YOUR_API_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "url": "https://api.yourdomain.com/webhooks/elai",
        "techEmail": "devops-alerts@yourdomain.com",
        "enabled": true
      }'
    

    Requirements: The URL must use https://. Non-TLS (http://), localhost, and internal domain targets containing elai.io are rejected with 400 Bad Request.

  2. Configure the HMAC Signing Secret:

    curl -X POST "https://apis.elai.io/api/v1/webhook/secret" \
      -H "Authorization: Bearer YOUR_API_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "secret": "whsec_79cbf208a1d48c081e8f237bf4c"
      }'
    

[!CAUTION] The Secret Configuration Ordering Trap: The signing secret is stored only if an active webhook subscription is already enabled. If you invoke POST /webhook/secret before POST /webhook/ or while enabled: false, the API responds with a false-positive 200 OK, but the secret is silently discarded. Subsequent webhook events will arrive without signatures. Always subscribe first, set the secret second, and verify configuration state via GET /apiConfig.

Cryptographic Verification Algorithm

When a secret is configured, Elai.io attaches two headers to every webhook delivery:

The signed string follows this exact format: $$\text{Signature} = \text{HMAC-SHA256}_{\text{SECRET}}\left(\text{Elai-Timestamp} + \text{"."} + \text{raw_body}\right)$$

Production Node.js / Express Webhook Receiver

import express, { Request, Response } from 'express';
import crypto from 'crypto';

interface ExtendedRequest extends Request {
  rawBody?: string;
}

const app = express();
const WEBHOOK_SECRET = process.env.ELAI_WEBHOOK_SECRET || 'whsec_79cbf208a1d48c081e8f237bf4c';
const MAX_DRIFT_MS = 5 * 60 * 1000; // 5 minutes replay protection

// Capture exact raw string before body parsers alter JSON formatting
app.use(
  express.json({
    verify: (req: ExtendedRequest, _res: Response, buf: Buffer) => {
      req.rawBody = buf.toString('utf8');
    },
  })
);

function verifyElaiSignature(req: ExtendedRequest): boolean {
  const timestamp = req.headers['elai-timestamp'] as string;
  const receivedSig = req.headers['elai-signature'] as string;

  if (!timestamp || !receivedSig || !req.rawBody) {
    return false;
  }

  // Prevent replay attacks
  const tsNum = parseInt(timestamp, 10);
  if (isNaN(tsNum) || Math.abs(Date.now() - tsNum) > MAX_DRIFT_MS) {
    return false;
  }

  const expectedSig = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(`${timestamp}.${req.rawBody}`)
    .digest('hex');

  const receivedBuf = Buffer.from(receivedSig, 'utf8');
  const expectedBuf = Buffer.from(expectedSig, 'utf8');

  if (receivedBuf.length !== expectedBuf.length) {
    return false;
  }

  return crypto.timingSafeEqual(receivedBuf, expectedBuf);
}

app.post('/webhooks/elai', (req: ExtendedRequest, res: Response) => {
  if (!verifyElaiSignature(req)) {
    return res.status(401).json({ error: 'Invalid webhook signature or expired timestamp' });
  }

  // CRITICAL: Acknowledge within 10 seconds to avoid delivery failure
  res.status(200).json({ received: true });

  // Offload processing to asynchronous worker/message broker
  const payload = req.body;
  enqueueVideoJob(payload).catch((err) => {
    console.error('Failed to dispatch background job:', err);
  });
});

async function enqueueVideoJob(payload: any) {
  const { event, error, requestId, batchRowId, video } = payload;

  if (event === 'video_ready') {
    console.log(`Video ready: ID=${video._id}, Request=${requestId}, RowIndex=${batchRowId}`);
    console.log(`CDN URL: ${video.url}`);
    console.log(`Thumbnail: ${video.thumbnail}`);
    // Update internal database: Video.update({ status: 'ready', cdnUrl: video.url }, ...)
  } else if (event === 'video_error') {
    console.error(`Video generation failed: ID=${video?._id}, Reason=${error}`);
    // Mark record as failed, log error details, notify admin queue
  }
}

app.listen(3000, () => console.log('Elai webhook consumer running on port 3000'));

5. Resilient Industrial Pipeline Design

The Elai.io webhook system operates under a single-attempt delivery model:

sequenceDiagram
    autonumber
    participant App as Enterprise Backend
    participant Elai as Elai.io REST API
    participant Hook as Webhook Handler
    participant Queue as Redis / BullMQ Queue
    participant Worker as Storage & Sync Worker

    App->>Elai: POST /videos/renderTemplate/{templateId}
    Elai-->>App: 200 OK (accepted: true, requestId)
    
    rect rgb(240, 248, 255)
    Note over Elai, Hook: Fast Path: Webhook Push
    Elai->>Hook: POST /webhooks/elai (video_ready)
    Hook-->>Elai: 200 OK (< 200ms)
    Hook->>Queue: Push raw job payload
    Queue->>Worker: Consume job
    Worker->>Worker: Ingest CDN MP4 to Internal S3/LMS
    end

    rect rgb(255, 245, 245)
    Note over App, Elai: Fallback Path: Reconciliation Cron
    App->>Elai: GET /videos?status=ready&limit=50
    Elai-->>App: Array of completed video objects
    App->>App: Reconcile unconfirmed jobs
    end

Architectural Mandates for Production Reliability

  1. Immediate Decoupled Acknowledgments: Never perform database joins, video transcoding, or third-party asset transfers inside the webhook HTTP route. Respond with HTTP 200 immediately, then place the payload onto an internal message queue (e.g., BullMQ, AWS SQS, or RabbitMQ).
  2. Reconciliation Polling Worker: Treat webhooks as the fast processing path, but maintain an asynchronous reconciliation cron job running every 10–15 minutes. Query GET /videos?status=ready or check specific pending records via GET /videos/{videoId} to reconcile video records that missed single-attempt webhook delivery.
  3. Idempotency Safeguards: Because reconciliation workers and webhooks can process the same asset concurrently, your database updates must be idempotent using video._id or requestId + batchRowId as a unique compound index.

6. 365Finds Implementation Recommendations

Component365Finds RecommendationKey Technical Justification
Workflow StrategyTemplate-driven rendering (/videos/renderTemplate)Decouples creative design from backend engineering; avoids maintaining fragile Fabric.js canvas objects in code.
Batch SizingBatches of 50 to 100 itemsStays well beneath the hard limit of 200 rows per batch; minimizes blast radius if payload validation fails.
Webhook DeliveryNon-blocking ack + BullMQ/SQS ingestionPrevents exceeding the 10-second timeout that triggers the account-wide 10-failure webhook deactivation.
Security ValidationHMAC-SHA256 with byte-exact rawBodyReserializing parsed JSON objects creates subtle formatting mismatches that break hash verification.
Fault ToleranceScheduled reconciliation cron via GET /videosGuarantees pipeline completeness despite Elai.io's single-attempt delivery policy.

By following this decoupled architecture, development teams can reliably automate high-volume personalized avatar generation, feeding tailored video assets directly into enterprise training and communication portals without operational overhead.


References