# MAGI-2 API Integration Guide

> From API key to a saved MP4 in five steps, plus the production details: media inputs, error handling, retries and credit control. Every example works as-is once you add your key.

- Web page: https://magi2.studio/docs/guide
- REST base URL: https://magi2.studio/v1
- MCP endpoint: https://magi2.studio/mcp
- All developer docs in one file: https://magi2.studio/docs/llms-full.txt

## 1. Create an API key

Create a key in the dashboard and keep it in an environment variable or secret manager on your server. Open API keys: https://magi2.studio/dashboard/api-keys (sign-in required)

```bash
export MAGI2_API_KEY="YOUR_API_KEY"
```

Use one key per app or environment. Each key keeps its own task history, so the API call logs stay easy to read, and you can revoke one key without breaking the others.

## 2. Pick a mode and write the request

There is no mode switch. The API reads which inputs you sent:

- **text-to-video** — send only a prompt.
- **image-to-video** — send first_frame_url (and optionally last_frame_url). The clip keeps the first frame's aspect ratio.
- **reference-to-video** — send a prompt plus image_urls, video_urls and/or audio_urls to keep a character, product, place, motion or voice consistent.

MAGI-2 responds best to prompts that read like a shot description: framing, subject, action, camera movement, light, then the sound you want to hear.

```json
{
  "prompt": "Medium shot. A street musician in a red coat plays violin under a bridge at night. Slow push-in, warm lamplight, light rain. Violin melody, distant traffic, rain on stone.",
  "duration": 8,
  "aspect_ratio": "16:9",
  "generate_audio": true
}
```

All request parameters: https://magi2.studio/docs.md

## 3. Submit the task

POST the JSON to /v1/generate. The call returns in seconds with a task_id; credits are charged at this point.

```bash
curl -X POST 'https://magi2.studio/v1/generate' \
  -H "Authorization: Bearer $MAGI2_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"prompt": "A street musician plays violin under a bridge at night, light rain", "duration": 8}'
```

A successful response:

```json
{
  "code": 200,
  "message": "success",
  "data": {
    "task_id": "n89a1b2c3d4e5f60718293a4b5c6d7e8f90magi2",
    "status": "IN_PROGRESS",
    "consumed_credits": 144
  }
}
```

**Important:** every successful submission is billed. If a request times out on your side, check /v1/tasks for a new task before sending it again, so you do not pay twice.

## 4. Poll the status

Call /v1/status with the task_id until status is SUCCESS or FAILED.

- Wait 15–30 seconds between calls. Most clips finish within a few minutes; long clips take longer.
- Stop polling after about 30 minutes and check the task later instead of creating a new one.
- FAILED tasks are refunded automatically; error_message explains why.

```bash
curl 'https://magi2.studio/v1/status?task_id=n89a1b2c3d4e5f60718293a4b5c6d7e8f90magi2' \
  -H "Authorization: Bearer $MAGI2_API_KEY"

# → data.status: IN_PROGRESS | SUCCESS | FAILED
# → data.response[0]: MP4 URL when SUCCESS
```

## 5. Save the video

When status is SUCCESS, response[0] is the MP4 URL. Download it and store it in your own storage or CDN; treat our URL as a delivery link, not permanent hosting.

```bash
curl -L -o magi2-n89a1b2c3d4e5f60718293a4b5c6d7e8f90magi2.mp4 'VIDEO_URL_FROM_RESPONSE'
```

## Complete example

Create, wait with back-off, and download, with the error cases handled.

### Python (magi2_video.py)

```python
import os
import time
import requests

BASE_URL = "https://magi2.studio/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['MAGI2_API_KEY']}"}


def create_task(payload: dict) -> str:
    r = requests.post(f"{BASE_URL}/generate", headers=HEADERS, json=payload, timeout=60)
    body = r.json()
    if body.get("code") != 200:
        # 400: fix the request. 401: check the key. 402: top up credits.
        raise RuntimeError(f"{r.status_code}: {body.get('message')}")
    print("charged", body["data"]["consumed_credits"], "credits")
    return body["data"]["task_id"]


def wait_for_video(task_id: str, timeout_s: int = 1800) -> str:
    deadline = time.time() + timeout_s
    delay = 15
    while time.time() < deadline:
        time.sleep(delay)
        try:
            r = requests.get(f"{BASE_URL}/status", headers=HEADERS,
                             params={"task_id": task_id}, timeout=60)
        except requests.RequestException:
            delay = min(delay * 2, 60)  # network hiccup: back off, keep polling
            continue
        if r.status_code >= 500:
            delay = min(delay * 2, 60)
            continue
        task = r.json()["data"]
        if task["status"] == "SUCCESS":
            return task["response"][0]
        if task["status"] == "FAILED":
            raise RuntimeError(f"generation failed (credits refunded): {task['error_message']}")
        delay = 20
    raise TimeoutError(f"task {task_id} still running; check it later with /v1/status")


def download(url: str, path: str) -> None:
    with requests.get(url, stream=True, timeout=300) as r:
        r.raise_for_status()
        with open(path, "wb") as f:
            for chunk in r.iter_content(chunk_size=1 << 20):
                f.write(chunk)


task_id = create_task({
    "prompt": "A street musician in a red coat plays violin under a bridge at night, light rain, slow push-in",
    "duration": 5,
    "aspect_ratio": "16:9",
})
video_url = wait_for_video(task_id)
download(video_url, f"{task_id}.mp4")
print("saved", f"{task_id}.mp4")
```

### Node.js (magi2-video.mjs)

```javascript
import { writeFile } from "node:fs/promises";

const BASE_URL = "https://magi2.studio/v1";
const headers = {
  Authorization: `Bearer ${process.env.MAGI2_API_KEY}`,
  "Content-Type": "application/json",
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function createTask(payload) {
  const res = await fetch(`${BASE_URL}/generate`, { method: "POST", headers, body: JSON.stringify(payload) });
  const body = await res.json();
  // 400: fix the request. 401: check the key. 402: top up credits.
  if (body.code !== 200) throw new Error(`${res.status}: ${body.message}`);
  console.log("charged", body.data.consumed_credits, "credits");
  return body.data.task_id;
}

async function waitForVideo(taskId, timeoutMs = 30 * 60_000) {
  const deadline = Date.now() + timeoutMs;
  let delay = 15_000;
  while (Date.now() < deadline) {
    await sleep(delay);
    let res;
    try {
      res = await fetch(`${BASE_URL}/status?task_id=${taskId}`, { headers });
    } catch {
      delay = Math.min(delay * 2, 60_000); // network hiccup: back off, keep polling
      continue;
    }
    if (res.status >= 500) { delay = Math.min(delay * 2, 60_000); continue; }
    const { data: task } = await res.json();
    if (task.status === "SUCCESS") return task.response[0];
    if (task.status === "FAILED") throw new Error(`generation failed (credits refunded): ${task.error_message}`);
    delay = 20_000;
  }
  throw new Error(`task ${taskId} still running; check it later with /v1/status`);
}

const taskId = await createTask({
  prompt: "A street musician in a red coat plays violin under a bridge at night, light rain, slow push-in",
  duration: 5,
  aspect_ratio: "16:9",
});
const videoUrl = await waitForVideo(taskId);
const video = Buffer.from(await (await fetch(videoUrl)).arrayBuffer());
await writeFile(`${taskId}.mp4`, video);
console.log("saved", `${taskId}.mp4`);
```

## Preparing images, videos and audio

- Every input is a public http(s) URL that downloads the file directly. Links behind a login, expiring too soon, or pointing to an HTML page will fail.
- Use common formats: JPG, PNG or WebP images, MP4 video, MP3 or WAV audio. Upload them to your own bucket or CDN first.
- Reference mode takes up to 10 images, 5 videos and 5 audio clips. Frames and references cannot be combined in one request.
- For image-to-video, crop the first frame to the shape you want: the output follows its aspect ratio.

## Handling errors

Read the HTTP status and the message field. Retry only when the problem is temporary.

| HTTP | What to do |
| --- | --- |
| 400 | Fix the request using the message (range, URL, or a frames/references mix). Do not retry unchanged. Nothing was charged. |
| 401 | Check the Authorization header and that the key was not revoked. |
| 402 | Not enough credits. Top up, then retry. |
| 404 | The task_id is wrong or was created with another key. |
| 5xx / timeout | Temporary. For /v1/status, back off and keep polling. For /v1/generate, look in /v1/tasks first; resubmit only if no task was created. |

## Controlling spend

- Cost is predictable: duration × 18 credits in every mode (10 seconds = 180 credits). Audio and reference inputs do not change the price.
- consumed_credits on each task is the amount charged; it drops to 0 when a failed task is refunded.
- The API and the browser studio share one balance. Test prompts at short durations before running long clips.

## Debug with API call logs

The dashboard lists every task per API key with the exact request, status, credits, error and video, and refreshes running tasks automatically. Open API call logs: https://magi2.studio/dashboard/logs (sign-in required)

## Production checklist

- [ ] The API key lives only on the server, in an environment variable or secret manager.
- [ ] You check code === 200 before reading data.
- [ ] You store task_id right after submitting, so a crash never leads to a paid duplicate.
- [ ] Polling waits 15–30 seconds and backs off on network or 5xx errors.
- [ ] Finished videos are copied to your own storage.
- [ ] Your UI shows error_message for failed tasks and tells users the credits were refunded.

Using an AI agent? Connect it through the MCP server: https://magi2.studio/docs/mcp.md

---

MAGI-2 is a video model published by Sand.ai. Magi2 Studio is an independent service that runs it through a third-party API provider; it is not operated by, affiliated with or endorsed by Sand.ai.
