AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How to Integrate the Hedra API to Automate Character Avatar Video Generation

Ana Flávia Magalhães · 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

For software engineers, marketing automation teams, and game developers, creating talking character videos through a web UI is an operational bottleneck. Manually uploading reference portraits, attaching voice tracks, selecting framing ratios, and waiting for interactive downloads fails as soon as production scales to hundreds of personalized ad creatives, localized announcements, or dynamic NPC dialogues.

Hedra provides a headless, programmatic foundation through its modern v3 REST API. By targeting the /v3/models/hedra-avatar endpoint, developers can turn static character portraits and raw audio files into lip-synced, expressive video clips within automated pipelines.

At 365Finds, our assessment is direct: Hedra v3 is currently one of the most developer-friendly, cost-effective engines for long-form, audio-driven character animation. Its separated prepaid API wallet avoids brittle subscription credit limits, while its native support for up to 10-minute (600 seconds) audio durations and multi-speaker coordinate targeting outperforms traditional short-clip avatar engines. However, automating it successfully requires strict adherence to its binary file-handle lifecycle, async job polling contracts, and credential isolation.

This guide provides an end-to-end blueprint for integrating the Hedra v3 API using Python and cURL—from binary asset ingestion to async polling and artifact delivery.


1. Architectural Overview & v3 Prerequisites

Before sending generation requests, teams migrating from legacy setups or integrating for the first time must configure three core architectural components:

The v3 Endpoint Architecture

Hedra deprecated legacy v2 endpoints (/web-app/public) in favor of a unified model job runtime under https://api.hedra.com/v3. Media generation operates as an asynchronous state machine:

StageEndpointMethodFunction
Asset Ingestion/v3/filesPOSTUploads binary image and audio files; issues short-lived presigned handles.
Job Submission/v3/models/hedra-avatarPOSTQueues the avatar generation task with aspect ratio, resolution, and asset handles.
Status Polling/v3/jobs/{job_id}/statusGETLightweight polling for state transitions (IN_QUEUE, IN_PROGRESS, COMPLETED, FAILED).
Output Fetch/v3/jobs/{job_id}GETRetrieves full execution metadata, signed download URLs, and server-issued asset_id references.

Authentication & Prepaid Billing

API keys are generated in the Hedra Developer Console and follow the format <key_id>:<secret>. Direct HTTP requests accept either:

Unlike Hedra Studio—which bills against recurring subscription credits—the Hedra v3 API is metered in USD against a dedicated prepaid API wallet. If your wallet balance drops below the estimated inference fee, the API refuses execution immediately with HTTP 402 INSUFFICIENT_BALANCE.


2. Ingesting Media Assets (POST /v3/files)

Hedra models do not accept arbitrary external image or audio URLs. All raw binary assets must first pass through Hedra's staging bucket via POST /v3/files.

Upload Contract & File Constraints

cURL File Upload Example

curl --fail-with-body -X POST "https://api.hedra.com/v3/files" \
  -H "Authorization: Key $HEDRA_API_KEY" \
  -F "file=@portrait.png"

Response:

{
  "url": "https://storage.hedra.com/staging/upload_abc123...?signature=xyz",
  "content_type": "image/png",
  "expires_at": "2026-10-26T19:30:00Z"
}

Repeat this step for the driving voice clip (speech.mp3) to obtain both resource handles before triggering generation.


3. Submitting the Avatar Generation Job

Once you hold valid upload handles, dispatch the generation job to POST /v3/models/hedra-avatar.

Schema Parameters

Submission Request (cURL)

curl --fail-with-body -X POST "https://api.hedra.com/v3/models/hedra-avatar" \
  -H "Authorization: Key $HEDRA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "start_image": {
        "source": "url",
        "url": "https://storage.hedra.com/staging/upload_image_handle"
      },
      "audio": {
        "source": "url",
        "url": "https://storage.hedra.com/staging/upload_audio_handle"
      },
      "prompt": "News anchor speaking calmly, professional lighting",
      "aspect_ratio": "16:9",
      "resolution": "720p"
    }
  }'

The endpoint returns HTTP 202 Accepted with an initial acknowledgment envelope:

{
  "job_id": "job_94a73df0-18e2-411a-b6d8-99e2f41cb101",
  "model": "hedra-avatar",
  "status": "IN_QUEUE",
  "status_url": "/v3/jobs/job_94a73df0-18e2-411a-b6d8-99e2f41cb101/status",
  "result_url": "/v3/jobs/job_94a73df0-18e2-411a-b6d8-99e2f41cb101",
  "estimated_completion_at": "2026-10-26T18:08:15Z"
}

4. Asynchronous Polling, Result Retrieval, and Safe Downloads

Rendering AI avatars requires heavy neural inference and cannot complete synchronously. Pipelines must implement an async polling worker or subscribe to webhooks.

Polling Mechanics

  1. Poll Status Endpoint: Query GET /v3/jobs/{job_id}/status every 3 to 5 seconds.
  2. State Evaluation:
    • IN_QUEUE / IN_PROGRESS: Sleep and continue polling.
    • COMPLETED: Break out of the loop and fetch final results.
    • FAILED: Stop execution; inspect the structured error envelope.
  3. Rate Limits: Standard Hedra API keys allow 60 requests per 60 seconds. Aggressive tight loops will trigger HTTP 429 RESOURCE_EXHAUSTED with a Retry-After header.

Fetching Output & Asset Chaining

Once marked COMPLETED, request GET /v3/jobs/{job_id}:

{
  "job_id": "job_94a73df0-18e2-411a-b6d8-99e2f41cb101",
  "status": "COMPLETED",
  "outputs": [
    {
      "status": "COMPLETED",
      "asset_id": "asset_48c7f912-70b3-4f99-8cfb-e390c58a8a31",
      "url": "https://storage.hedra.com/deliveries/avatar_output.mp4?signature=...",
      "content_type": "video/mp4",
      "width": 1280,
      "height": 720,
      "duration_ms": 14200,
      "fps": 25
    }
  ],
  "cost": 0.071,
  "currency": "USD"
}

The Credential Isolation Rule During Download

[!IMPORTANT] Download the video file by streaming outputs[0].url without passing your Hedra API credentials. Storage hosts (AWS S3/GCS buckets) reject requests containing foreign Authorization headers.

Furthermore, signed download URLs are ephemeral. Automated pipelines must stream the binary output directly into an internal storage cluster (e.g., MinIO, S3, or a local file server) rather than storing the Hedra presigned link.

If you intend to chain this generation into another model (for example, applying video restyling), preserve the server-issued asset_id.


5. End-to-End Production Script (Python)

Below is a production-grade Python script utilizing httpx that handles asset uploading, job creation, robust polling, and disk streaming.

#!/usr/bin/env python3
"""
Complete Hedra v3 Avatar Video Generation Pipeline.
Author: 365Finds Research Engineering
"""

import os
import sys
import time
from pathlib import Path
from typing import Dict, Any, Optional
import httpx

HEDRA_BASE_URL = "https://api.hedra.com/v3"
API_KEY = os.environ.get("HEDRA_API_KEY")

if not API_KEY:
    print("Error: HEDRA_API_KEY environment variable is required.", file=sys.stderr)
    sys.exit(1)

HEADERS = {
    "Authorization": f"Key {API_KEY}",
    "User-Agent": "365Finds-AutomationPipeline/1.0"
}


def upload_asset(client: httpx.Client, file_path: Path) -> str:
    """Uploads a local media file to Hedra staging and returns the upload handle URL."""
    if not file_path.is_file():
        raise FileNotFoundError(f"Source file not found: {file_path}")

    print(f"[*] Uploading {file_path.name} ({file_path.stat().st_size} bytes)...")
    with file_path.open("rb") as f:
        files = {"file": (file_path.name, f)}
        resp = client.post(f"{HEDRA_BASE_URL}/files", headers=HEADERS, files=files, timeout=60.0)

    if resp.status_code != 201:
        raise RuntimeError(f"Upload failed [{resp.status_code}]: {resp.text}")

    data = resp.json()
    upload_url = data.get("url")
    print(f"[+] Uploaded successfully. Expires at: {data.get('expires_at')}")
    return upload_url


def submit_avatar_job(
    client: httpx.Client,
    image_url: str,
    audio_url: str,
    prompt: str = "A spokesperson talking clearly to the audience",
    aspect_ratio: str = "16:9",
    resolution: str = "720p",
    idempotency_key: Optional[str] = None
) -> str:
    """Dispatches an avatar generation job and returns the job ID."""
    payload: Dict[str, Any] = {
        "input": {
            "start_image": {"source": "url", "url": image_url},
            "audio": {"source": "url", "url": audio_url},
            "prompt": prompt,
            "aspect_ratio": aspect_ratio,
            "resolution": resolution
        }
    }
    if idempotency_key:
        payload["idempotency_key"] = idempotency_key

    print("[*] Submitting job to /v3/models/hedra-avatar...")
    resp = client.post(
        f"{HEDRA_BASE_URL}/models/hedra-avatar",
        headers={**HEADERS, "Content-Type": "application/json"},
        json=payload,
        timeout=30.0
    )

    if resp.status_code != 202:
        raise RuntimeError(f"Job dispatch failed [{resp.status_code}]: {resp.text}")

    ack = resp.json()
    job_id = ack["job_id"]
    print(f"[+] Job accepted. ID: {job_id}")
    return job_id


def poll_and_download(client: httpx.Client, job_id: str, dest_path: Path, timeout_seconds: int = 600):
    """Polls status until completion, then streams the video output to disk."""
    deadline = time.monotonic() + timeout_seconds
    status_url = f"{HEDRA_BASE_URL}/jobs/{job_id}/status"

    print(f"[*] Polling job status (timeout: {timeout_seconds}s)...")
    while time.monotonic() < deadline:
        resp = client.get(status_url, headers=HEADERS, timeout=15.0)
        if resp.status_code == 429:
            retry_after = int(resp.headers.get("Retry-After", 10))
            print(f"[!] Rate limited. Backing off for {retry_after}s...")
            time.sleep(retry_after)
            continue
        resp.raise_for_status()

        status_data = resp.json()
        current_status = status_data.get("status")
        print(f"    - Current state: {current_status}")

        if current_status == "COMPLETED":
            break
        elif current_status == "FAILED":
            raise RuntimeError(f"Generation job failed: {status_data}")

        time.sleep(5)
    else:
        raise TimeoutError(f"Job {job_id} exceeded deadline. Resume polling later; do not resubmit.")

    # Retrieve output details
    result_resp = client.get(f"{HEDRA_BASE_URL}/jobs/{job_id}", headers=HEADERS, timeout=30.0)
    result_resp.raise_for_status()
    result = result_resp.json()

    outputs = result.get("outputs", [])
    if not outputs or outputs[0].get("status") != "COMPLETED":
        raise RuntimeError("Job completed without downloadable video output.")

    download_url = outputs[0]["url"]
    asset_id = outputs[0].get("asset_id")
    print(f"[+] Output ready! Server asset ID: {asset_id}")

    # Download without sending Hedra Authorization headers
    print(f"[*] Streaming video artifact to {dest_path}...")
    with httpx.stream("GET", download_url, timeout=120.0, follow_redirects=True) as stream_resp:
        stream_resp.raise_for_status()
        with dest_path.open("wb") as out_file:
            for chunk in stream_resp.iter_bytes(chunk_size=65536):
                out_file.write(chunk)

    print(f"[SUCCESS] Saved character video ({dest_path.stat().st_size} bytes) -> {dest_path}")


def main():
    portrait = Path("assets/character.png")
    audio = Path("assets/narration.mp3")
    output = Path("output/rendered_avatar.mp4")
    output.parent.mkdir(parents=True, exist_ok=True)

    with httpx.Client() as client:
        # Step 1: Upload assets
        img_handle = upload_asset(client, portrait)
        audio_handle = upload_asset(client, audio)

        # Step 2: Trigger generation
        job_id = submit_avatar_job(
            client=client,
            image_url=img_handle,
            audio_url=audio_handle,
            prompt="Professional educator looking attentively into lens",
            aspect_ratio="16:9",
            resolution="720p"
        )

        # Step 3 & 4: Poll and stream output
        poll_and_download(client, job_id, output)


if __name__ == "__main__":
    main()

6. Error Handling & Edge Cases in High-Scale Automation

Building resilient automation pipelines requires anticipating Hedra-specific error codes and system constraints:

HTTP StatusError Code (code)Cause & Pipeline Strategy
400INVALID_ARGUMENTPayload validation failure (e.g. aspect ratio typo, expired file handle, audio duration outside 0.5s–600s). Check error.details for offending field paths; do not retry without code modification.
401UNAUTHORIZEDMalformed or expired API key. Ensure the credential contains both <key_id>:<secret>.
402INSUFFICIENT_BALANCEAPI prepaid wallet is depleted. Inspect error.billing.funding_url and suspend job queue until wallet balance is recharged.
422MODERATION_FAILEDReference portrait or audio failed safety checks. Halt retry loops and flag asset for human editorial review.
429RESOURCE_EXHAUSTEDExceeded 60 requests/min throttle. Honor Retry-After response header and implement exponential jitter backoff.
500INTERNALTransient backend inference disruption. Retry with an idempotency_key after backoff.

Upgrading to Webhooks for High Concurrency

If your architecture handles dozens of concurrent generations, continuous polling against /v3/jobs/{job_id}/status will rapidly saturate your per-minute request quota. In production environments, 365Finds recommends providing a callback URL via the webhook field in the submission body.

Hedra signs all webhook deliveries with Ed25519 cryptography. Developers must verify the X-Hedra-Webhook-Signature against the public key retrieved from GET /v3/webhooks/public-key and deduplicate on X-Hedra-Webhook-Id before updating internal workflow states.


7. Strategic Assessment & 365Finds Institutional Judgment

When engineering character video automation, technical leads must choose between API engines with divergent operational profiles:

  1. Hedra v3 vs. Turnkey SaaS Studios (e.g., HeyGen, Synthesia): Turnkey platforms cater to non-technical designers via heavy browser interfaces, charging rigid subscription tiers per minute. Hedra v3 provides an unopinionated, infrastructure-first primitive. If you need dynamic character rendering generated on-the-fly from live LLM dialogue or parameterized programmatic templates, Hedra delivers superior cost efficiency and pipeline agility.
  2. Hedra v3 vs. Open-Source Self-Hosting (e.g., SadTalker, LivePortrait): Self-hosting requires dedicated GPU instances (e.g., A100/H100 clusters), model sharding, custom autoscaling, and driver maintenance. For teams generating under several thousand hours of video monthly, Hedra's managed infrastructure eliminates cold-start overhead and operational maintenance at an affordable per-second rate.
  3. Primary Limitation to Consider: Hedra specializes in audio-driven facial and upper-torso performance. If your production pipeline requires full-body cinematic action, complex physical character-object interaction, or multi-angle 3D camera sweeps, combine Hedra with specialized video generators (such as Sora 2, Kling 2.6, or LTX) rather than forcing hedra-avatar beyond its intended talking-head domain.

For software engineers automating digital human video at scale, integrating the Hedra v3 REST API provides the cleanest balance between generation speed, facial synchronization fidelity, and operational stability.


References