AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Programmatic Video Generation with Synthesia API: Dynamic Templates, Webhooks, and Automated Pipelines

Rubén Arteaga · 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

Synthesia's Video API enables engineering teams to replace repetitive manual video editing with automated, headless video synthesis pipelines. Instead of logging into Synthesia Studio to manually swap customer names, slide backgrounds, and scripts for individual onboarding clips or sales outreach videos, developers can programmatically trigger customized avatar video renders using dynamic variables and handle rendering completions asynchronously via webhooks.

At 365Finds, our core architectural recommendation is clear: enterprise engineering teams should build dynamic video workflows around the Template-driven endpoint (POST /v2/videos/fromTemplate) rather than assembling raw scenes (POST /v2/videos) from scratch in code.

Treating pre-configured Studio templates as parameterized rendering functions preserves design fidelity, separates creative styling from business logic, and drastically reduces API payload complexity. Below is the end-to-end technical guide to architecting, authenticating, and operating an automated Synthesia video generation pipeline.


Architecture Overview: The Event-Driven Video Pipeline

Video rendering is computationally intensive and cannot operate as a synchronous request-response flow. A 60-second avatar video typically requires between two to eight minutes to render, synthesize neural speech, animate facial landmarks, and pass automated safety moderation.

Attempting to poll the Synthesia REST API for status updates wastes rate limits, introduces network latency, and strains worker threads. The recommended production pattern relies on an event-driven architecture using asynchronous message dispatch, persistent correlation IDs, and cryptographically verified webhooks.

sequenceDiagram
    autonumber
    participant App as Backend Service / CRM
    participant Queue as Task Queue (Redis / SQS)
    participant SynAPI as Synthesia Video API (v2)
    participant Worker as Background Worker
    participant Hook as Webhook Receiver
    participant Storage as Cloud Storage (S3 / R2)

    App->>SynAPI: POST /v2/videos/fromTemplate (templateId, templateData, callbackId)
    SynAPI-->>App: 201 Created (video id, status: "in_progress")
    App->>App: Store video id & callbackId in DB (status: "queued")
    
    Note over SynAPI: Asynchronous Rendering, Speech Synthesis & Moderation
    
    SynAPI->>Hook: POST webhook payload (event: "video.completed", HMAC signature)
    Hook->>Hook: Verify Synthesia-Signature (HMAC-SHA256)
    Hook-->>SynAPI: 200 OK (immediate response within 6s SLA)
    Hook->>Queue: Enqueue VideoDownloadedJob(download_url, callbackId)
    
    Queue->>Worker: Dequeue Job
    Worker->>Storage: Stream MP4 asset from download_url to S3 bucket
    Worker->>App: Update DB record (status: "ready", s3_url)

Key Architectural Boundaries

  1. Client / CRM Layer: Triggers an event (e.g., user signup, lead enrichment, course registration) and sends a single atomic POST request to Synthesia.
  2. Ingress / Dispatch: Attaches an immutable callbackId (e.g., user UUID or internal job ID) to link the output video back to your internal database row.
  3. Webhook Ingestion Layer: Verifies incoming cryptographic signatures and acknowledges receipt with an HTTP 200 OK within Synthesia's strict 6-second window.
  4. Asset Processor: Downloads the temporary MP4 asset from Synthesia's CDN and uploads it to private object storage (AWS S3, Cloudflare R2, or Google Cloud Storage) before the temporary link expires.

Step 1: Authentication and Scopes Setup

All requests to Synthesia's v2 Video API require an API key passed in the standard Authorization request header.

Generating Keys with the Correct Scope

To provision API access:

  1. Navigate to your Synthesia Studio workspace and click Developers in the left navigation bar.
  2. Select the API keys tab and click New API key.
  3. Enter a descriptive key name (e.g., prod-crm-video-pipeline).
  4. Select the required scope: Legacy (v2).
  5. Set an expiration window (default is 30 days; select Never for persistent production services, subject to your company's key rotation policies).
  6. Copy the raw key immediately upon generation.

Important: Synthesia enforces fine-grained scopes. If your key lacks the Legacy (v2) scope, requests to https://api.synthesia.io/v2/* will fail with an HTTP 403 Forbidden (insufficient_scope). Also note that the Key ID visible in the settings dashboard is an administrative identifier, not the secret token used for HTTP authorization.


Step 2: Designing Parameterized Templates in Synthesia Studio

Before writing backend code, create and publish your video template inside Synthesia Studio. A template serves as the visual scaffold containing your brand elements, animations, layout positions, background music, and avatar selections.

The 4 Types of Template Variables

Synthesia supports four distinct variable mechanisms that you can map to dynamic API data:

Variable TypeHow to Create in StudioAPI Data FormatTypical Use Case
Script VariableRight-click text cursor in script box -> < > Variable -> assign name and optional defaultPlain stringPersonalized avatar speech (e.g., recipient greeting, customized metrics)
Canvas Text VariableAdd text element on canvas -> enter name wrapped in double braces: {{variable_name}}Plain stringOn-screen lower-thirds, title slides, customized discount codes
Media Element VariableSelect image/video -> open inspector 3-dot menu -> + Add variablePublic HTTPS URL or Synthesia Asset IDCustomer company logo, profile avatar, customized screenshot
Background Media VariableDeselect canvas items -> Scene Background Settings -> + Add variablePublic HTTPS URL or Synthesia Asset IDCustomized background environment or product dashboard video
Avatar VariableSelect avatar -> inspector 3-dot menu -> + Add variableValid Stock or Custom Avatar IDDynamically toggling presenter identity or persona

Template Authoring Rules and Constraints

Once finalized, click Publish template. Navigate to Library > Templates, click the three-dot menu on your template, and click Copy ID to retrieve your templateId (a standard UUID).


Step 3: Triggering Video Generation via REST API

To initiate video rendering, dispatch an HTTP POST to https://api.synthesia.io/v2/videos/fromTemplate.

Request Payload Specification

{
  "templateId": "b18f8832-7a54-469a-9e1e-289d0b674b88",
  "title": "Welcome Onboarding - Acme Corp",
  "description": "Automated onboarding video generated for Jane Doe",
  "visibility": "private",
  "test": false,
  "callbackId": "usr_99824_onboarding",
  "templateData": {
    "recipient_name": "Jane Doe",
    "company_name": "Acme Corporation",
    "account_tier": "Enterprise Plan",
    "company_logo": "https://cdn.example.com/logos/acme-corp.png"
  }
}

Key Parameter Rationale

Python Integration Example

import os
import requests

SYNTHESIA_API_KEY = os.environ.get("SYNTHESIA_API_KEY")
ENDPOINT = "https://api.synthesia.io/v2/videos/fromTemplate"

def generate_personalized_video(user_id: str, name: str, company: str, logo_url: str) -> dict:
    headers = {
        "Authorization": SYNTHESIA_API_KEY,
        "Content-Type": "application/json"
    }
    
    payload = {
        "templateId": "b18f8832-7a54-469a-9e1e-289d0b674b88",
        "title": f"Welcome {name} to our Platform",
        "visibility": "private",
        "test": os.environ.get("ENVIRONMENT") != "production",
        "callbackId": f"user:{user_id}",
        "templateData": {
            "recipient_name": name,
            "company_name": company,
            "company_logo": logo_url
        }
    }
    
    response = requests.post(ENDPOINT, json=payload, headers=headers, timeout=15)
    
    if response.status_code == 201:
        video_record = response.json()
        print(f"Video synthesis initiated: ID={video_record.get('id')}, Status={video_record.get('status')}")
        return video_record
    elif response.status_code == 429:
        raise RuntimeError("Synthesia rate limit exceeded. Backoff required.")
    else:
        raise RuntimeError(f"Synthesia API Error {response.status_code}: {response.text}")

Step 4: Configuring and Securing Webhooks

Rather than polling GET /v2/videos/{id}, configure a webhook endpoint to receive notifications the moment video rendering finishes.

Registering the Webhook Subscription

You can register your webhook endpoint programmatically using the API:

curl -X POST https://api.synthesia.io/v2/webhooks \
  -H "Authorization: YOUR_SYNTHESIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://api.yourdomain.com/v1/webhooks/synthesia",
    "events": [
      "video.completed",
      "video.failed"
    ]
  }'

Synthesia responds with an HTTP 201 Created containing a sensitive secret attribute:

{
  "id": "wh_42a8b9f0-21d3-455b-b9cd-908123abc456",
  "url": "https://api.yourdomain.com/v1/webhooks/synthesia",
  "secret": "whsec_7f9b0c8d1e2f3a4b5c6d7e8f9a0b1c2d",
  "status": null
}

Security Warning: Store the returned secret immediately in your environment secrets vault (e.g., AWS Secrets Manager or HashiCorp Vault). Synthesia will not display this secret again. If compromised, delete the webhook subscription and register a new one.

Webhook Delivery SLAs and Retry Rules


Step 5: Webhook Signature Verification and Ingestion Handler

Every incoming webhook request contains two critical authentication headers:

  1. Synthesia-Timestamp: The UNIX epoch timestamp of when the request was dispatched.
  2. Synthesia-Signature: A hexadecimal HMAC-SHA256 signature calculated over the combined timestamp and raw request body.

Verification Algorithm

  1. Extract Synthesia-Timestamp and Synthesia-Signature.
  2. Construct the message string: f"{timestamp}.{raw_body_bytes.decode('utf-8')}".
  3. Compute an HMAC-SHA256 hash of the message string using your webhook_secret.
  4. Perform a timing-attack safe comparison using hmac.compare_digest.

Production Webhook Ingestion Implementation (FastAPI / Python)

import hmac
import hashlib
import os
from fastapi import FastAPI, Request, HTTPException, status, Header, BackgroundTasks

app = FastAPI()
WEBHOOK_SECRET = os.environ.get("SYNTHESIA_WEBHOOK_SECRET")

def process_video_asset(payload: dict):
    """
    Background job: Runs out-of-band to prevent blocking the 6-second webhook SLA.
    """
    video_data = payload.get("data", {})
    video_id = video_data.get("id")
    callback_id = video_data.get("callbackId")
    download_url = video_data.get("download")
    status_str = video_data.get("status")

    if status_str == "complete" and download_url:
        print(f"Processing download for Video {video_id} (Linked to {callback_id})")
        # 1. Stream download_url to local buffer or temp storage
        # 2. Upload asset to company S3 / R2 bucket
        # 3. Update database record: status = 'COMPLETED', s3_url = final_s3_url
        # 4. Notify end user via email or in-app notification
    elif status_str in ("error", "rejected"):
        print(f"Video synthesis failed for {video_id}: Moderation or rendering fault.")
        # Mark internal record as failed and alert operations

@app.post("/v1/webhooks/synthesia", status_code=status.HTTP_200_OK)
async def handle_synthesia_webhook(
    request: Request,
    background_tasks: BackgroundTasks,
    synthesia_signature: str = Header(None, alias="Synthesia-Signature"),
    synthesia_timestamp: str = Header(None, alias="Synthesia-Timestamp")
):
    if not synthesia_signature or not synthesia_timestamp:
        raise HTTPException(status_code=400, detail="Missing signature headers")

    raw_body = await request.body()
    body_text = raw_body.decode("utf-8")

    # Construct verification message
    message = f"{synthesia_timestamp}.{body_text}".encode("utf-8")
    expected_signature = hmac.new(
        WEBHOOK_SECRET.encode("utf-8"),
        message,
        hashlib.sha256
    ).hexdigest()

    # Timing-safe signature comparison
    if not hmac.compare_digest(expected_signature, synthesia_signature):
        raise HTTPException(status_code=401, detail="Invalid webhook signature")

    payload = await request.json()
    event_type = payload.get("event")

    if event_type in ("video.completed", "video.failed"):
        # Enqueue background task and return HTTP 200 immediately
        background_tasks.add_task(process_video_asset, payload)
        return {"status": "enqueued"}

    return {"status": "ignored"}

Step 6: Handling Video Assets and Expirations

When the video.completed event fires, the payload contains key metadata:

{
  "event": "video.completed",
  "data": {
    "id": "4b68481e-128a-4d22-bf12-42173167a5bb",
    "status": "complete",
    "callbackId": "user:usr_99824_onboarding",
    "duration": "00:00:42",
    "title": "Welcome Jane Doe to our Platform",
    "download": "https://downloads.synthesia.io/v2/videos/4b68481e-128a.../video.mp4?expires=1710003600&signature=...",
    "thumbnail": {
      "image": "https://downloads.synthesia.io/v2/videos/4b68481e-128a.../thumbnail.jpg",
      "gif": "https://downloads.synthesia.io/v2/videos/4b68481e-128a.../thumbnail.gif"
    },
    "captions": {
      "srt": "https://downloads.synthesia.io/v2/videos/4b68481e-128a.../captions.srt",
      "vtt": "https://downloads.synthesia.io/v2/videos/4b68481e-128a.../captions.vtt"
    }
  }
}

Critical Storage Guidance

  1. Presigned Download URLs are Ephemeral: The URL provided in the download property is time-limited. Your system must not embed this direct Synthesia download link in client-facing web apps or emails. It will expire.
  2. Download and Persist Immediately: Stream the MP4 payload to your organization's object storage (e.g., Amazon S3 bucket with CloudFront distribution).
  3. Capture Captions and Thumbnails: Store the accompanying .vtt caption file and animated .gif preview to enrich client player experiences and accessibility.

Comparing Generation Paradigms: Template vs. Raw Scene API

Synthesia provides two distinct ways to trigger rendering: POST /v2/videos/fromTemplate and POST /v2/videos. Understanding the trade-offs is essential for sound pipeline architecture.

Evaluation DimensionTemplate-Driven (/fromTemplate)Raw Scene API (/v2/videos)
Recommended By365Finds RecommendedSpecialized Edge Cases Only
Design ControlFull Studio canvas: animations, layouts, multi-layer assets, audioBasic: background color/image, avatar scale, horizontal alignment
Payload ComplexityMinimal (templateId + simple JSON key-value map)High (nested JSON array of scenes, scripts, camera angles, backgrounds)
Separation of ConcernsNon-technical designers edit templates; developers inject dataDevelopers must hardcode styling, positions, and scene sequencing in code
Branding ConsistencyHigh (Studio enforces Brand Kits, typography, transition timing)Low (prone to visual inconsistencies across developer revisions)
Ideal Use CasesCustomer onboarding, personalized sales outreach, dynamic trainingHeadless green-screen avatar overlays, automated dynamic news clips

At 365Finds, our assessment is that using raw programmatic scene construction (POST /v2/videos) for multi-scene customer-facing videos is an engineering antipattern. It forces developers to manage styling and visual composition inside JSON blobs, which slows down iteration and prevents creative teams from maintaining brand consistency. Reserve raw video synthesis for dynamic green-screen pipelines where avatar video streams are composited downstream in tools like FFmpeg.


Rate Limits, Production Quotas, and Failure Recovery

Enterprise pipeline stability requires accounting for Synthesia's platform limits and moderation guardrails.

Synthesia API Rate Limits

Synthesia applies tier-based rate limiting:

When you exceed these thresholds, the API returns an HTTP 429 Too Many Requests.

Production Best Practices

  1. Implement Leaky Bucket / Token Bucket Throttling: If generating thousands of personalized videos for a major campaign, queue requests in Redis (using BullMQ, Celery, or Sidekiq) and throttle dispatch rates to no more than 1–2 requests per second.
  2. Exponential Backoff with Jitter: Wrap API call clients with automated retries for transient HTTP 429 and 500 status codes.
  3. Account for Content Moderation Failures: Every synthesized script undergoes automated content filtering. If a dynamic user variable injects disallowed terminology or sensitive personal data, Synthesia flags the video, moves status to rejected, and suppresses the download link. Ensure your webhook processor handles video.failed and status: "rejected" gracefully by notifying your support team or falling back to a generic default video.
  4. Leverage test: true in CI/CD: Run end-to-end integration tests using "test": true to validate JSON mapping, webhook delivery, and S3 ingestion without consuming your monthly rendering quota.

References