how-tos

MAGI-2 API Guide: First Request in cURL, Python and Node.js

Poyo.ai Team
9 min read
Share:

MAGI-2 API guide: first request in cURL, Python and Node.js

This MAGI-2 API guide takes you from an API key to a finished MP4. Every request uses the model ID magi-2 on https://api.poyo.ai, and the same body works from cURL, Python and Node.js. You can test prompts first in the MAGI-2 playground; the field reference is in the MAGI-2 API docs.

New to the model? Start with the MAGI-2 API overview.

How a MAGI-2 API call works

  1. POST /api/generate/submit with model and input. The response contains data.task_id and status: "not_started".
  2. Poll GET /api/generate/status/{task_id} until status is finished or failed, or pass callback_url and wait for a POST.
  3. Read the MP4 from data.files[] where file_type is video.

Create a key at poyo.ai/dashboard/api-key and export it as POYO_API_KEY. Keep it on the server.

Text to video with cURL

curl https://api.poyo.ai/api/generate/submit \
  -H "Authorization: Bearer $POYO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "magi-2",
    "input": {
      "prompt": "On a ferry deck at sunset, two old friends lean on the railing. The woman says: \"I never thought we would make this trip.\" The man laughs and replies: \"Neither did I.\" Seagulls call overhead and the engine hums below.",
      "duration": 8,
      "aspect_ratio": "16:9"
    }
  }'

Then check the task with the returned ID:

curl https://api.poyo.ai/api/generate/status/YOUR_TASK_ID \
  -H "Authorization: Bearer $POYO_API_KEY"

resolution defaults to 1080p and generate_audio to true, so this request returns a 1920×1080 MP4 with sound. An 8-second request like this one was charged 128 credits ($0.64) in PoYo's launch-day test on November 28, 2026, and finished within about 3.5 minutes (polled).

Python with bounded polling

The loop checks the HTTP status and the code field in the body, because some validation errors come back as HTTP 200 with code: 400. It stops after 20 minutes; if that happens, poll the same task_id later rather than submitting again, which would start a second billed task.

import os
import time
import requests

BASE = "https://api.poyo.ai"
session = requests.Session()
session.headers["Authorization"] = "Bearer " + os.environ["POYO_API_KEY"]

def checked(resp):
    resp.raise_for_status()
    body = resp.json()
    if body.get("code") != 200:
        raise RuntimeError(f"PoYo error {body.get('code')}: {body.get('error')}")
    return body["data"]

task = checked(session.post(f"{BASE}/api/generate/submit", json={
    "model": "magi-2",
    "input": {
        "prompt": "A rainy railway crossing at night. The barrier lowers, bells ring, "
                  "and a freight train rushes past. Rain hisses on the road. No dialogue.",
        "duration": 6,
        "aspect_ratio": "16:9",
    },
}, timeout=60))
task_id = task["task_id"]
print("task", task_id)

deadline = time.monotonic() + 20 * 60
while time.monotonic() < deadline:
    data = checked(session.get(f"{BASE}/api/generate/status/{task_id}", timeout=60))
    if data["status"] == "failed":
        raise RuntimeError(data.get("error_message") or "generation failed")
    if data["status"] == "finished":
        video = next(f["file_url"] for f in data["files"] if f.get("file_type") == "video")
        print(video, "credits:", data.get("credits_amount"))
        break
    time.sleep(10)
else:
    raise TimeoutError(f"still running, poll again later: {task_id}")

Node.js with fetch

Node 18 and later ship fetch, so no SDK is needed.

const BASE = "https://api.poyo.ai";
const headers = {
  Authorization: `Bearer ${process.env.POYO_API_KEY}`,
  "Content-Type": "application/json",
};

async function call(path, init = {}) {
  const res = await fetch(BASE + path, { headers, ...init });
  const body = await res.json();
  if (!res.ok || body.code !== 200) {
    throw new Error(`PoYo error ${body.code}: ${JSON.stringify(body.error)}`);
  }
  return body.data;
}

const task = await call("/api/generate/submit", {
  method: "POST",
  body: JSON.stringify({
    model: "magi-2",
    input: {
      prompt: "A cyclist rides along a coastal road at golden hour, waves breaking below, wind rushing past.",
      image_urls: ["https://example.com/cyclist-first-frame.jpg"],
      duration: 5,
    },
  }),
});

const deadline = Date.now() + 20 * 60 * 1000;
while (Date.now() < deadline) {
  const data = await call(`/api/generate/status/${task.task_id}`);
  if (data.status === "failed") throw new Error(data.error_message || "failed");
  if (data.status === "finished") {
    console.log(data.files.find((f) => f.file_type === "video").file_url);
    break;
  }
  await new Promise((r) => setTimeout(r, 10_000));
}

Save it as magi2.mjs so top-level await works.

Request bodies for every MAGI-2 API input mode

First frame, or first and last frames

Send one image to set the opening frame, or two to set the opening and closing frames. The video follows the first frame's aspect ratio, so leave aspect_ratio out or send auto.

{
  "model": "magi-2",
  "input": {
    "prompt": "The cyclist from the first frame rides toward the lighthouse and stops at the end of the road. Wind and distant waves.",
    "image_urls": [
      "https://example.com/first-frame.jpg",
      "https://example.com/last-frame.jpg"
    ],
    "duration": 6,
    "aspect_ratio": "auto"
  }
}

In PoYo's launch-day test, a 5-second first-frame request (one image in image_urls) was charged 80 credits ($0.40) and finished within about 3 minutes (polled).

Reference image and reference audio

References carry a character, a location or a piece of music into a new scene. Describe in the prompt what each one is for.

{
  "model": "magi-2",
  "input": {
    "prompt": "The elderly street musician from the reference image walks along a sunlit seaside boardwalk, playing the saxophone melody from the reference audio. Seagulls glide overhead. He stops, turns to the camera and says: \"Morning light suits this tune.\"",
    "reference_image_urls": [
      "https://storage.poyo.ai/models/magi-2/examples/reference-character-6586977013a0.jpg"
    ],
    "reference_audio_urls": [
      "https://storage.poyo.ai/models/magi-2/examples/reference-audio-5bf2add370f4.mp3"
    ],
    "duration": 8,
    "aspect_ratio": "16:9"
  }
}

Reference video

Use reference_video_urls for motion, camera work or a character in motion. It can be combined with image and audio references in the same task.

{
  "model": "magi-2",
  "input": {
    "prompt": "Follow the camera move from the reference video: a slow dolly through a night market. Vendors call out, oil sizzles in woks, a scooter passes.",
    "reference_video_urls": ["https://example.com/dolly-reference.mp4"],
    "duration": 10,
    "aspect_ratio": "9:16"
  }
}

Reference audio on its own is also valid, for example to set the rhythm of a clip from a music excerpt.

Validation rules worth enforcing client-side

RuleWhy it matters
prompt 1–15,000 charactersLonger prompts are rejected
duration integer 4–30No fractional seconds
image_urls and reference_* not in the same taskEach task uses one mode
image_urls 1–2 JPG, PNG or WEBPThird image is rejected
Up to 10 reference images, 5 videos, 5 audio clipsPer task
Each reference video or audio clip 2–30 s, 30 s total per typeMeasure before upload
aspect_ratio auto or empty with image_urlsFrames set the ratio
seed 0–2147483647Reuse with the same inputs for similar results
No fields outside the schemaExtra keys fail validation

All media URLs must be public and directly downloadable. If you use signed URLs, give them enough lifetime to cover the time the task waits in the queue.

Errors worth handling

codeMeaningWhat to do
400Invalid parametersFix the body; do not retry as-is
401Missing or invalid keyCheck the Authorization header
402Insufficient creditsTop up, then resubmit
429Rate limitBack off and retry the submit
500 / 502 / 503Server or upstream errorRetry with backoff

A task can also end as failed with error_message set; PoYo refunds failed tasks automatically.

Callbacks instead of polling

Add a top-level callback_url (HTTPS, public) next to model. When the task finishes or fails, PoYo POSTs the task data, the same shape as the status response without the code/data wrapper, and signs it with X-Webhook-Timestamp and X-Webhook-Signature (HMAC-SHA256). Failed deliveries are retried up to 5 times; polling still works as a fallback. Details are in the video webhook docs.

Writing the prompt for an API request

The prompt field carries everything: the scene, the action, the camera and the sound. A few rules from the docs and PoYo's launch tests make first requests more predictable:

  • Quote spoken lines. The docs say a line in quotes is spoken by the character in the generated audio. Name the speaker before the line.
  • Describe sound explicitly. Seagulls, engine hum, rain on asphalt: list what should be heard, or write "no dialogue" when you only want effects and ambience.
  • Use the length you need. Prompts can run up to 15,000 characters, enough for a shot list with time ranges. Sand AI says MAGI-2 supports timeline and shot-cut control in the prompt.
  • Match duration to content. Two short lines of dialogue fit in 8 seconds. A 30-second shot list needs duration: 30.
  • Fix seed while you iterate. Reusing a seed with the same inputs gives similar results, so you can change one prompt detail at a time.

A production checklist

Before you move MAGI-2 API calls from a script into your product:

  1. Store the task_id before polling. If your worker restarts, resume polling the stored ID instead of submitting again.
  2. Validate on your side first. Check duration, counts and the frame/reference mode rule before the request leaves your server, so users get a clear error instead of a failed task.
  3. Host media where PoYo can fetch it. Public HTTPS URLs that return the file directly, not a preview page.
  4. Copy the result to your own storage. Download the MP4 from file_url once the task finishes and serve it from your storage or CDN.
  5. Log credits_amount. Compare it with your estimate (duration × 16) to catch requests that differ from what you intended.
  6. Prefer callbacks at scale. With many parallel tasks, a signed callback is cheaper to run than thousands of status polls; keep polling as the fallback.

How the first MAGI-2 API bill is calculated

credits = duration × 16
USD     = credits × 0.005

Only output seconds count. References, aspect ratio and generate_audio do not change the rate, so a 5-second clip is 80 credits ($0.40) and a 30-second clip is 480 credits ($2.40). credits_amount on the finished task shows what was charged. For more examples and a comparison with other PoYo video models, see MAGI-2 API pricing; for prompting audio, see MAGI-2 API video with sound.

Frequently asked questions

How do I call the MAGI-2 API from Python? POST the JSON body to https://api.poyo.ai/api/generate/submit with requests, then poll /api/generate/status/{task_id} as in the loop above.

Is there an official MAGI-2 API SDK for Node.js? You do not need one. Plain fetch with a Bearer header works, as shown above.

Can I send first frames and reference images in one MAGI-2 API request? No. Use image_urls for frames or the reference_* fields for references, one mode per task.

Why did my MAGI-2 API request return HTTP 200 but no task? Check code in the body. Validation errors can arrive with HTTP 200 and code: 400.

How long should I poll a MAGI-2 API task? In PoYo's launch-day test, 5–8 second clips finished within about 3–3.5 minutes (polled). Poll every 10 seconds or so and keep the task_id if you time out.

Share: