MAGI-2 API Tutorial: Generate Video with Python and cURL

YYunus Emre Özdiyar 8 min
MAGI-2 API page on imageat showing 4 to 30 second 1080p video generation with audio and API pricing

Learn how to use the MAGI-2 API for 1080p text-to-video, image-to-video, first-and-last-frame, and reference-guided video with audio.

On this page
  1. MAGI-2 API at a Glance
  2. 1. Create and Protect an API Key
  3. 2. Make a Text-to-Video Request with cURL
  4. 3. Poll Until the Video Is Ready
  5. 4. Use the MAGI-2 API with Python
  6. 5. Switch Generation Modes with Request Fields
  7. Image-to-video
  8. First-and-last-frame video
  9. Reference-to-video
  10. 6. Understand Cost Before You Queue a Batch
  11. 7. Production Checklist
  12. Common MAGI-2 API Errors
  13. 401 Unauthorized
  14. Invalid media URL
  15. Unsupported duration or aspect ratio
  16. Job appears stuck
  17. Frequently Asked Questions
  18. What is the MAGI-2 API model ID on imageat?
  19. Does MAGI-2 support image-to-video through the API?
  20. Does the API generate audio?
  21. Can I use video and audio references together?
  22. Is the MAGI-2 API free?
  23. Start Building with MAGI-2

The MAGI-2 API on imageat generates 4–30 second 1080p MP4 videos with synchronized audio. One endpoint supports text-to-video, image-to-video, first-and-last-frame control, and reference-guided generation. Use the model ID magi2, submit a job to POST /v1/videos, then poll its taskId until the output URL is ready.

This tutorial focuses on implementation. For a browser playground, live schema, and current model controls, open the MAGI-2 API model page. For architecture, creative features, and prompting context, read the separate MAGI-2 video generator guide.

MAGI-2 API at a Glance

The current imageat implementation exposes the following production controls:

  • Model ID: magi2
  • Create endpoint: POST https://api.imageat.com/v1/videos
  • Status endpoint: GET https://api.imageat.com/v1/videos/status?taskId=...
  • Duration: any whole second from 4 to 30 seconds; default 5 seconds
  • Output: 1080p MP4 with generated audio
  • Text/reference aspect ratios: 16:9, 9:16, 1:1, 4:3, 3:4, and 21:9
  • Image-to-video: one public image URL as the first frame
  • First/last frame: two public image URLs for a planned transition
  • References: up to 10 images, 5 videos, and 5 audio files
  • Prompt limit: up to 15,000 characters
  • Current API rate: $0.16 per generated second; failed generations are not charged

Video and audio references must each be 2–30 seconds long. The combined duration is limited to 30 seconds for video references and 30 seconds for audio references. Reference files do not add a separate fee. Check current API pricing before hard-coding estimates.

API generation is a paid hosted operation. You can write and test integration code locally without charge, but a real MAGI-2 request consumes website credits or prepaid API balance according to the current billing rules.

1. Create and Protect an API Key

Create a key from the imageat API keys page. Production keys begin with iat_live_; sandbox keys begin with iat_test_. Send the key as a Bearer token:

Authorization: Bearer YOUR_IMAGEAT_API_KEY

Keep the key on your server. Do not embed it in browser JavaScript, a mobile app bundle, a public repository, or an example screenshot. Store it in an environment variable instead:

export IMAGEAT_API_KEY="iat_live_..."

The examples below use https://api.imageat.com as the API base URL shown in the full imageat API documentation.

2. Make a Text-to-Video Request with cURL

A minimal request needs the model, prompt, duration, and aspect ratio. MAGI-2 generates audio in the same pass, so describe the intended dialogue, ambience, effects, and whether music should be absent.

curl -X POST "https://api.imageat.com/v1/videos" \
-H "Authorization: Bearer ${IMAGEAT_API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"model": "magi2",
"prompt": "At blue hour, a red fox pauses on a fallen birch in a misty forest, then trots toward the camera. Slow dolly-in, stable subject scale, natural forest ambience, soft footsteps, no music.",
"duration": "8s",
"aspectRatio": "16:9"
}'

Save both taskId and generationId from the accepted response. Video creation is asynchronous: the first response identifies the job rather than returning a finished MP4 immediately.

Do not send resolution or generateAudio as selection controls for MAGI-2. The current route always produces 1080p output with audio, so those fields are ignored.

3. Poll Until the Video Is Ready

Poll the status endpoint every 10–15 seconds. Avoid a tight loop: long 1080p generations may take several minutes, and aggressive polling adds unnecessary traffic.

curl "https://api.imageat.com/v1/videos/status?taskId=YOUR_TASK_ID" \
-H "Authorization: Bearer ${IMAGEAT_API_KEY}"

A completed response includes the final CDN URL:

{
"status": "completed",
"url": "https://cdn.imageat.com/generated/video.mp4"
}

Treat the returned CDN URL as the final MP4 output. Copy it to storage you control if your product requires a particular retention policy, stable asset ownership, or downstream processing.

For event-driven systems, pass a webhook_url when creating the job instead of relying only on polling. Your endpoint should acknowledge notifications quickly, verify the job against your own stored taskId, and make processing idempotent so a repeated notification cannot duplicate work.

4. Use the MAGI-2 API with Python

The following example uses only Python's standard library. It submits a job, persists the identifiers in memory, polls with a timeout, and returns the completed MP4 URL.

import json
import os
import time
import urllib.parse
import urllib.request

API_BASE = "https://api.imageat.com/v1"
API_KEY = os.environ["IMAGEAT_API_KEY"]


def api_request(url, method="GET", payload=None):
data = json.dumps(payload).encode() if payload is not None else None
request = urllib.request.Request(
url,
data=data,
method=method,
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(request, timeout=60) as response:
return json.load(response)


def create_magi2_video(prompt, duration="8s", aspect_ratio="16:9"):
return api_request(
f"{API_BASE}/videos",
method="POST",
payload={
"model": "magi2",
"prompt": prompt,
"duration": duration,
"aspectRatio": aspect_ratio,
},
)


def wait_for_video(task_id, timeout_seconds=1200):
deadline = time.time() + timeout_seconds
while time.time() < deadline:
query = urllib.parse.urlencode({"taskId": task_id})
result = api_request(f"{API_BASE}/videos/status?{query}")
status = result.get("status")

if status == "completed":
return result["url"]
if status in {"failed", "cancelled"}:
raise RuntimeError(f"MAGI-2 job ended with status: {status}")

time.sleep(12)

raise TimeoutError("MAGI-2 generation did not finish before timeout")


job = create_magi2_video(
"A ceramic robot opens a greenhouse at sunrise. Gentle handheld camera, "
"leaves moving in a light breeze, glass door click, birds outside, no music."
)

print("taskId:", job["taskId"])
print("generationId:", job.get("generationId"))
print("video:", wait_for_video(job["taskId"]))

In production, store the task and generation IDs before the first poll. If the process restarts, a worker should be able to resume the same job instead of paying for a duplicate request.

5. Switch Generation Modes with Request Fields

MAGI-2 uses the same endpoint for four workflows. The fields determine the mode in this priority order: first-and-last-frame, references, imageUrl, then text-only.

Image-to-video

Use imageUrl to make a public image the first frame. The output follows the source image's shape, so aspectRatio does not override it.

{
"model": "magi2",
"prompt": "The cyclist pushes off and rides toward the distant bridge. Slow side tracking shot, realistic wheel motion, morning traffic ambience.",
"imageUrl": "https://assets.example.com/cyclist-first-frame.jpg",
"duration": "6s"
}

For more details about this mode, see the dedicated MAGI-2 image-to-video API page.

First-and-last-frame video

Use firstFrameUrl and lastFrameUrl when the shot must begin and end at approved compositions.

{
"model": "magi2",
"prompt": "The camera cranes from the table-level opening frame to the wide rooftop closing frame. Keep the red package recognizable throughout. City ambience and soft fabric movement, no narration.",
"firstFrameUrl": "https://assets.example.com/opening.jpg",
"lastFrameUrl": "https://assets.example.com/closing.jpg",
"duration": "10s"
}

Treat the final frame as a destination, not a guarantee that every intermediate frame will behave like manually animated keyframes. Review object identity, trajectory, and the final transition before shipping.

Reference-to-video

Reference mode can combine identity, product, environment, motion, camera, voice, and sound evidence in one request.

{
"model": "magi2",
"prompt": "The woman from image 1 walks through a neon night market. Match the forward camera move from the reference video and use the audio reference only for vocal tone. Street ambience, no music.",
"referenceImageUrls": [
"https://assets.example.com/approved-character.jpg"
],
"referenceVideoUrls": [
"https://assets.example.com/camera-move.mp4"
],
"referenceAudioUrls": [
"https://assets.example.com/voice-reference.wav"
],
"duration": "10s",
"aspectRatio": "9:16"
}

Name each reference's role in the prompt. “Image 1 defines the product shape; video 1 defines camera motion” is clearer than uploading several assets without explaining what each one controls. The MAGI-2 reference-to-video API page contains the live mode-specific schema.

Only upload files you own or have permission to use. Do not use reference audio to clone a person's voice without authorization.

6. Understand Cost Before You Queue a Batch

The current API rate is $0.16 per requested second at 1080p with sound, regardless of whether the request starts from text, an image, frames, or references.

  • 4 seconds: $0.64
  • 5 seconds: $0.80
  • 10 seconds: $1.60
  • 30 seconds: $4.80

In the imageat studio, the current rate is 3 credits per second. API requests first use eligible website credits; after those run out, usage is billed against prepaid USD API balance under the current billing rules. Failed generations are not charged.

Duration is the main cost control for MAGI-2. Prototype camera direction and prompt wording with a short clip before requesting a 20–30 second take. This is cheaper and makes failures easier to diagnose.

7. Production Checklist

Before putting MAGI-2 behind a public feature:

  1. Validate duration as a whole-second value from 4s to 30s.
  2. Allow only the documented aspect ratios for text and reference modes.
  3. Confirm every reference URL is public, HTTPS, and available long enough for the worker to fetch it.
  4. Store taskId, generationId, user ID, request hash, and billing context before polling.
  5. Use idempotency in your queue so retries do not create duplicate paid jobs.
  6. Poll every 10–15 seconds or use a webhook.
  7. Set a realistic timeout and handle failed or cancelled states explicitly.
  8. Download approved results to controlled storage when retention matters.
  9. Moderate user prompts and uploads before generation.
  10. Check the video generation API and live docs before shipping fields that may change.

Common MAGI-2 API Errors

401 Unauthorized

The key is missing, malformed, revoked, or sent from the wrong environment. Confirm the Authorization: Bearer YOUR_API_KEY header and rotate any key that was exposed.

Invalid media URL

The worker cannot read a private dashboard URL, a localhost address, or a signed URL that expires too early. Use public HTTPS storage with a safe expiry window.

Unsupported duration or aspect ratio

Send 4s–30s as a whole-second string. Use one of the six documented ratios only for text and reference requests; image-to-video follows the source frame.

Job appears stuck

Do not create a replacement immediately. Keep polling the saved taskId within your timeout window. A 1080p clip can take several minutes, especially for a longer requested duration.

Frequently Asked Questions

What is the MAGI-2 API model ID on imageat?

Use magi2 in requests to POST /v1/videos.

Does MAGI-2 support image-to-video through the API?

Yes. Pass a public image URL in imageUrl. You can also provide firstFrameUrl and lastFrameUrl for a planned start-to-end transition.

Does the API generate audio?

Yes. MAGI-2 output includes synchronized audio. Describe dialogue, ambience, effects, and music intent in the prompt. The route always generates audio, so generateAudio is ignored.

Can I use video and audio references together?

Yes. The current route accepts up to 10 image references, 5 video references, and 5 audio references. Video and audio references must each be 2–30 seconds, with a 30-second combined limit per media category.

Is the MAGI-2 API free?

No. Writing integration code locally is free, but actual generation is a paid hosted API operation. The current rate is $0.16 per generated second, subject to the live pricing page.

Start Building with MAGI-2

Begin with an 8-second text request, save the returned IDs, and confirm your polling or webhook path before adding references. Once that lifecycle is reliable, introduce one reference type at a time so you can identify which input controls identity, motion, camera, or sound.

Use the MAGI-2 API playground and integration guide to test the current schema, then keep the full API documentation as the operational source of truth for authentication, responses, billing, and error handling.

MAGI-2 API page on imageat showing 4 to 30 second 1080p video generation with audio and API pricingPin it for laterSave this guide to your Pinterest board

Share

Try it yourself
on imageat

Everything in this guide runs in the browser. Start with a free account and pay per generation.

Discover more

View all