Pika H3 Flex · Developers

Pika H3 Flex API Guide: Setup and Your First Video

The Pika API lets your app, script or AI agent generate H3 Flex videos with synchronized audio. This guide goes from zero to a downloaded MP4: create a key, authenticate, send a server-side request, choose a generation mode, poll (or use webhooks), check billing, download the result and handle errors safely. It includes working Python and Node.js examples.

  • X-API-Key authentication
  • Async jobs: submit → poll
  • Prepaid, per-second billing
  • Idempotent retries
H3 Flex "farm tracking shot" showcase · Video credit: Pika (pika.art)
Setup

Set Up Your Pika API Account

  1. 1
    Create an account

    Sign in at dev.pika.art/login. Signing in creates your organization.

  2. 2
    Create an API key

    Generate one at dev.pika.art/keys, where you can also rotate and revoke keys.

  3. 3
    Add funds

    Generation is prepaid. Top up at dev.pika.art/billing, or a submit fails with insufficient_balance. The membership is $10 a month, returned as $10 of API credits.

  4. 4
    Store the key server-side

    Save it as an environment variable named PIKA_API_KEY. Never put it in browser code, URLs or source control.

NeedWhere
Sign indev.pika.art/login
API keysdev.pika.art/keys
Add fundsdev.pika.art/billing
Webhooksdev.pika.art/webhooks
Model catalogdev.pika.art/models
Pricingdev.pika.art/pricing
OpenAPI specdev.pika.art/openapi.json
API base URLhttps://api.dev.pika.art
Supportapi@pika.art

From Pika's developer docs index at dev.pika.art/llms.txt. Pika also offers an agent onboarding prompt for coding agents such as Claude Code, Codex or Cursor.

Authentication

How Authentication Works

Every call to https://api.dev.pika.art sends your key in a header. Pika accepts either:

  • X-API-Key: YOUR_KEY (used in Pika's model docs)
  • Authorization: Bearer YOUR_KEY

The x-goog-api-key header is not accepted. The public catalog at api.dev.pika.art/catalog/apis is the only listed endpoint that needs no key.

🔐 Keep calls server-side Call the Pika API from your backend, serverless function or job worker, never directly from a browser or mobile app, because the key would be exposed. Your frontend calls your server, and your server calls Pika.
# Test your key: check your balance (free)
curl https://api.dev.pika.art/billing/balance \
  -H "X-API-Key: $PIKA_API_KEY"

# Response (micro-USD: 1 USD = 1,000,000)
{ "balance_micro_usd": 10000000, ... }

Postpaid organisations compare against postpaid.cycle.remaining_micro_usd instead.

Generation Modes

H3 Flex Endpoints and Generation Modes

All six run as async jobs. Submit to POST https://api.dev.pika.art/v1/media/pika/pika-h3-flex/{mode}.

ModeKey inputsPrice
text-to-videoprompt, duration 3 to 15, resolution, aspect_ratio$0.01 to $0.08 / s
image-to-videoprompt + first frame, last frame, or both$0.01 to $0.08 / s
reference-to-videoprompt + references (up to 9 images, 3 videos, 3 audio)$0.03 to $0.10 / s, plus reference video seconds
draft-to-videodraft_job_id or video + resolution (1080p/2k/4k)Pay the difference
prompt-rewriterprompt, mode (fl2va / ref2va), optional refs$0.02 / request
audio-stemsrequest_id or input_url (up to 120 s)$0.001 / stem-second
Common parameterValuesDefault
durationWhole seconds, 3 to 155
resolution480p, 768p (native) · 1080p, 2k, 4k (upscaled)768p
aspect_ratioauto, 21:9, 16:9, 3:2, 4:3, 5:4, 1:1, 4:5, 3:4, 2:3, 9:16, 9:21auto with rewrite on
rewritetrue / falsetrue
seedInteger, or omit for random (result reports the seed)Random
output_modevideo or audio-stems (adds a separation fee)video
webhook_urlOptional top-level URL for this job's completion eventNone

From Pika's model specs for text to video, image to video, reference to video, draft to video, prompt rewriter and audio stems. The seed's minimum value is listed differently in two specs, so omitting it for a random seed is the safest option.

Text to video: knitted game world
Product film: lip gloss
Reference to video: motion transfer

Example outputs © Pika, from the Pika H3 Flex research post.

Server-Side Request

Your First H3 Flex Video, Step by Step

A 5-second 768p text-to-video job costs $0.10. Here's the full flow: check balance, submit, poll, download.

  1. 1
    Check your balance

    GET /billing/balance is free and confirms the key can pay.

  2. 2
    Submit the job

    POST your prompt with an Idempotency-Key header. The response is a job with status queued. Store its id.

  3. 3
    Poll until done

    GET /v1/media/jobs/{id} until the status is completed, failed or cancelled. Or receive a webhook instead.

  4. 4
    Download the MP4

    Read output.video.url, or call GET /v1/media/jobs/{id}/content, and save the file to your own storage.

  5. 5
    Record the charge

    Log spend only when billing.state is settled, using charge_micro_usd keyed by job ID.

curl -X POST \
  https://api.dev.pika.art/v1/media/pika/pika-h3-flex/text-to-video \
  -H "X-API-Key: $PIKA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "prompt": "A red fox trots through fresh snow at dawn, slow tracking shot. Sound: crunching snow, distant birds. No music. No subtitles.",
    "duration": 5,
    "resolution": "768p",
    "aspect_ratio": "16:9",
    "rewrite": false
  }'

# → { "id": "media_...", "status": "queued", ... }
Copy & Adapt

Python and Node.js Examples

Minimal server-side scripts for the full flow. Adapt the error handling and storage for production.

Python (requests)

import os, time, uuid, requests

API = "https://api.dev.pika.art"
H = {"X-API-Key": os.environ["PIKA_API_KEY"]}

# 1. Balance check
bal = requests.get(f"{API}/billing/balance", headers=H).json()
print("Balance (USD):", bal.get("balance_micro_usd", 0) / 1e6)

# 2. Submit
body = {
    "prompt": "A red fox trots through fresh snow at dawn, "
              "slow tracking shot. Sound: crunching snow. No subtitles.",
    "duration": 5, "resolution": "768p", "aspect_ratio": "16:9",
}
r = requests.post(
    f"{API}/v1/media/pika/pika-h3-flex/text-to-video",
    headers={**H, "Idempotency-Key": str(uuid.uuid4())},
    json=body,
)
r.raise_for_status()
job = r.json()
job_id = job["id"]

# 3. Poll
while job["status"] not in ("completed", "failed", "cancelled"):
    time.sleep(5)
    job = requests.get(f"{API}/v1/media/jobs/{job_id}", headers=H).json()

if job["status"] != "completed":
    raise SystemExit(f"Job ended: {job['status']} {job.get('error')}")

# 4. Download
url = job["output"]["video"]["url"]
with open("first-h3-flex.mp4", "wb") as f:
    f.write(requests.get(url).content)

# 5. Billing
print("Billing:", job.get("billing"))

Node.js (fetch, Node 18+)

import { randomUUID } from "node:crypto";
import { writeFile } from "node:fs/promises";

const API = "https://api.dev.pika.art";
const H = { "X-API-Key": process.env.PIKA_API_KEY };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

// Submit
let res = await fetch(
  `${API}/v1/media/pika/pika-h3-flex/text-to-video`, {
  method: "POST",
  headers: { ...H, "Content-Type": "application/json",
             "Idempotency-Key": randomUUID() },
  body: JSON.stringify({
    prompt: "A red fox trots through fresh snow at dawn, " +
            "slow tracking shot. Sound: crunching snow. No subtitles.",
    duration: 5, resolution: "768p", aspect_ratio: "16:9",
  }),
});
if (!res.ok) throw new Error(`Submit failed: ${res.status}`);
let job = await res.json();

// Poll
const done = ["completed", "failed", "cancelled"];
while (!done.includes(job.status)) {
  await sleep(5000);
  job = await (await fetch(
    `${API}/v1/media/jobs/${job.id}`, { headers: H })).json();
}
if (job.status !== "completed")
  throw new Error(`Job ${job.status}: ${JSON.stringify(job.error)}`);

// Download
const mp4 = await fetch(job.output.video.url);
await writeFile("first-h3-flex.mp4",
  Buffer.from(await mp4.arrayBuffer()));
console.log("Saved. Billing:", job.billing);

Field names follow Pika's published job schema (id, status, output.video.url, billing). Confirm against openapi.json before production. These examples are ours, not official Pika SDK code. Pika's docs don't list an official SDK.

Inputs

Uploading Images, Video and Audio

Inputs are passed as URLs. If your file is public, use its URL directly. For local files, use Pika's presigned upload flow:

  1. 1
    Request an upload URL

    POST /v1/media/uploads with content_type and size_bytes.

  2. 2
    PUT the file

    Upload the bytes to upload_url using the returned headers exactly as given, within 5 minutes.

  3. 3
    Use the returned url

    Pass that permanent URL as your image, video or reference input.

POST /v1/media/pika/pika-h3-flex/reference-to-video
{
  "prompt": "References: @Image1 is the character. @Video1 supplies only the dance motion. @Image1 dances in a record shop. Audio: funk groove. No subtitles.",
  "duration": 8,
  "resolution": "768p",
  "aspect_ratio": "9:16",
  "references": [
    { "type": "image", "url": "https://…/character.png", "role": "identity" },
    { "type": "video", "url": "https://…/dance.mp4" }
  ]
}

Pika's reference-to-video page shows both a references array and separate image_urls/video_urls/audio_urls fields. Confirm which your account accepts. Limits: images up to 9 (PNG, JPEG, WebP), videos and audio up to 3 each (2 to 15 s, 15 s combined), each original file up to 50 MiB. See H3 Flex references.

Polling & Webhooks

Polling vs Webhooks

🔁

Polling

Call GET /v1/media/jobs/{id} every few seconds. Statuses: queued → running → completed, failed or cancelled. If you're at your concurrency limit, the job simply waits in queued.

📬

Webhooks

Add webhook_url to one submit, or register an endpoint for all jobs at dev.pika.art/webhooks. Deliveries follow the Standard Webhooks signing scheme and retry for about 55 hours.

✅

Webhook safety

Verify every signature and deduplicate on the webhook-id header. Only an owner or admin can read the signing secret on the Webhooks page, not an API key. Past deliveries: GET /v1/webhooks/deliveries.

Full receiver details in Pika's webhook specification.

Billing

How API Billing Works

  • Prepaid balance: add funds first. Website credit packs from pika.art can't be used on the API.
  • Per second of output: H3 Flex video endpoints bill per output second at the chosen resolution. Reference to video also bills reference video seconds.
  • Only successful jobs are charged.
  • Micro-USD units: balances and charges use micro-USD (1 USD = 1,000,000), as balance_micro_usd and charge_micro_usd.
  • Billing state: record spend only when billing.state is settled. If it's pending, re-check after 1, 2, then 5 seconds. If it's unavailable, wait at least 30 seconds. A null billing value means no charge was recorded, not that the job was free.
Sample jobCost
5 s text to video, 768p$0.10
15 s image to video, 768p$0.30
12 s text to video, 2K$0.48
15 s text to video, 4K$1.20
5 s reference to video, 768p$0.30
Prompt rewrite$0.02

Full breakdown: H3 Flex pricing.

Downloads

Downloading and Storing Results

  • Where: a completed job carries the MP4 link in output.video.url. GET /v1/media/jobs/{id}/content returns { "url": "..." }, or a 409 if the job isn't finished yet.
  • Save it promptly: Pika's docs don't state how long output URLs last, so copy finished files to your own storage (S3, GCS, R2…) right away.
  • Delete when done: DELETE /v1/media/jobs/{id} erases the job's stored media and its captured request (prompt and parameters).
  • Need 4K? Generate at 768p, then finish your keeper with draft-to-video. See the 4K guide.
  • Need stems? Run audio-stems on the completed job. See the audio guide.
Pika H3 Flex banner
Pika H3 Flex official banner · Image credit: Pika (Hugging Face)
Error Handling

Errors, Retries and Idempotency

Pika returns HTTP errors for bad requests and a failed job envelope for problems found at submit time. Branch on error.code.

ErrorWhat it meansWhat to do
HTTP 422Validation failed; the message names the fieldFix the field (duration, resolution, references…) and resubmit
invalid_inputInputs rejected (format, size, limits)Check file types, sizes and reference limits
insufficient_balanceNot enough prepaid fundsTop up at dev.pika.art/billing; check balance before submitting
content_moderationPrompt or media blocked by policyRevise the content; see Pika's Acceptable Use Policy
HTTP 429 / rate_limitedPer-minute or per-day limit hitWait for Retry-After, then resubmit with a fresh key
provider_errorUpstream or unknown failureRetry with backoff and a fresh Idempotency-Key
timed_outThe job took too longRetry, or try a shorter duration or lower resolution
HTTP 409Idempotency-Key reused with a different body, or content requested too earlyUse a new key for new requests; wait for completed before fetching content
🔑

One key per attempt

Send a unique Idempotency-Key with each new submit. Reusing a key returns the existing job, even a failed one, so retries need a fresh key.

⏳

Back off

Use exponential backoff with jitter for 429 and provider errors, and always honour Retry-After.

💰

Pre-check spend

Call the free balance endpoint before large batches, and don't submit if the balance can't cover the job.

🧾

Settle before logging

Write spend to your ledger only when billing.state is settled, keyed by job ID.

Error codes and retry rules from Pika's H3 Flex model specs and the developer docs index. Pika doesn't publish the exact rate-limit values. Enterprise plans offer higher concurrency.

FAQ

Pika H3 Flex API FAQ

How do I get a Pika H3 Flex API key?+
Sign in at dev.pika.art, create a key at dev.pika.art/keys, add prepaid funds at dev.pika.art/billing, and store the key server-side as PIKA_API_KEY.
How do I authenticate?+
Send your key in an X-API-Key header, or as Authorization: Bearer. Keep all calls server-side so the key is never exposed in a browser.
Is the H3 Flex API synchronous?+
No. Every endpoint is async. A submit returns a queued job, which you poll at /v1/media/jobs/{id} or get notified about by webhook.
How much does my first video cost?+
A 5-second 768p text-to-video job costs $0.10 ($0.02 per second). Only successful generations are charged.
Can I use my pika.art credits on the API?+
No. The API uses its own prepaid balance. Pika says website top-up credits work only on pika.art and Pika MCP.
How long are output URLs valid?+
Pika's docs don't state an expiry, so download finished videos to your own storage promptly. You can delete a job's stored media with DELETE /v1/media/jobs/{id}.
How should I retry failed requests?+
Retry with a fresh Idempotency-Key (reusing one returns the same failed job), honour Retry-After on 429s, and use exponential backoff for provider errors.