This guide shows you how to generate AI video with the VidMage API using Python. You will pass in a prompt and settings, submit a generation task, save its ID, check its progress, and download the finished MP4.
In order to help you understand how to generate AI video with the VidMage API, we will use VidMage’s Grok Video Generator for the worked example. The same overall workflow applies to other VidMage video generators, but you will need to adapt the endpoint, supported settings, and response handling to the generator you choose. This example uses your VidMage API key, and you don’t need a separate Grok account or xAI API key.
NOTE: Live API access needs an active VidMage subscription, and API tasks draw from the same credit balance as the website.
What the Python Example Does
VidMage runs each generation as a task. Your code submits the request once and receives a task ID without keeping that submission request open while the video renders. The Python function then checks progress through separate requests until the task finishes or the local wait limit is reached. The example wraps this workflow in one function, generate_video(), which:
1. Accepts a prompt and the supported settings from your application.
2. Saves the request and a new idempotency key to a private job file.
3. Submits the task once with your API key and saves the task ID right away.
4. Checks progress every five seconds until VidMage reports that the task is complete.
5. Downloads the MP4 and returns its local file path to your code.
This request turns text into video, so the code has no upload step. If you later build a workflow that starts from an image, VidMage's file uploads guide shows how to upload the file and pass its URL in the submit request.
What You Need Before Your First API Request
• Subscription: An active VidMage subscription. API keys stop working when it's inactive and start again after you renew.
• API key: One key from the Developer Console. The same key works for the REST API and for MCP clients.
• Python: Python 3.10 or newer. The install step adds the one library the code uses: requests.
• Credits: Enough credits for the clip you request. The example in this guide costs 60 credits.
You don't need a website or front end. The same module runs from a script, a server route, or a background worker, so you can test it on its own now and drop it into a larger app later.
How to Generate AI Video With the VidMage API in Python
Step 1: Sign in to VidMage, open your account page, and click Open console on the API & MCP card to reach the Developer Console. Select API keys in the sidebar, click Create API key, and copy the key while VidMage shows it in full. Store it on your server as an environment variable named VIDMAGE_API_KEY, the same way you store any other secret. VidMage's authentication guide asks you to keep keys out of page source, public repositories, logs, and chat messages, so never paste the key into browser code or into the Python file below.

Step 2: Create an empty project folder and save the complete example below as vidmage_video.py. INPUTS at the top hold the prompt and settings. You can run this file on its own or import generate_video() into your application. The code keeps one private job record so a restart can continue checking the same task.
"""One-file VidMage example. Use one worker per private job file."""
import getpass
import json
import os
import time
import uuid
from pathlib import Path
import requests
CAPABILITY = "grok-video-generator"
BASE = f"https://vidmage.ai/api/v1/{CAPABILITY}"
INPUTS = {
"prompt": "A small paper boat drifts across a sunlit puddle, "
"gentle camera tracking, natural reflections, no text",
"duration": "6",
"aspectRatio": "16:9",
"resolution": "720p",
}
def save_job(path, job):
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + ".tmp")
with temporary.open("w", encoding="utf-8") as stream:
os.chmod(temporary, 0o600)
json.dump(job, stream, indent=2)
stream.flush()
os.fsync(stream.fileno())
temporary.replace(path)
def generate_video(inputs, job_path, output_path, *, max_wait=300, on_progress=print):
key = os.environ.get("VIDMAGE_API_KEY")
if not key:
raise ValueError("Set VIDMAGE_API_KEY in the server environment.")
if (set(inputs) != {"prompt", "duration", "aspectRatio", "resolution"}
or not isinstance(inputs["prompt"], str)
or not 5 <= len(inputs["prompt"].strip()) <= 800
or inputs["duration"] not in ("6", "10")
or inputs["aspectRatio"] not in ("16:9", "9:16", "1:1")
or inputs["resolution"] not in ("480p", "720p")):
raise ValueError("Check the prompt and all four supported input fields.")
path, output = Path(job_path), Path(output_path)
job = json.loads(path.read_text()) if path.exists() else {
"capability": CAPABILITY, "input": dict(inputs),
"idempotency_key": str(uuid.uuid4()), "phase": "prepared"}
if job["capability"] != CAPABILITY or job["input"] != inputs:
raise ValueError("This job belongs to different inputs or another endpoint.")
if job.get("download_path") and Path(job["download_path"]).is_file():
return {"task_id": job["task_id"], "status": "completed",
"file_path": job["download_path"]}
def call(action, body):
headers = {"Authorization": f"Bearer {key}"}
if action == "submit":
headers["Idempotency-Key"] = job["idempotency_key"]
try:
response = requests.post(BASE + "/" + action, json=body,
headers=headers, timeout=(10, 60),
allow_redirects=False)
except requests.RequestException:
raise RuntimeError(f"{action} connection failed. Keep this job; recover it.") from None
try:
payload = response.json()
except ValueError:
payload = {"errorType": "NON_JSON_RESPONSE"}
if not isinstance(payload, dict):
payload = {"errorType": "UNEXPECTED_RESPONSE"}
job.update(last_response=payload,
request_id=response.headers.get("X-Request-Id"),
retry_after=response.headers.get("Retry-After"))
save_job(path, job)
if not 200 <= response.status_code < 300 or payload.get("success") is not True:
raise RuntimeError(f"HTTP {response.status_code}: {payload.get('errorType')}; "
f"Retry-After: {job['retry_after']}. Inspect the private job.")
return payload
if not job.get("task_id"):
if job["phase"] != "prepared":
raise RuntimeError("Submission needs recovery. Do not create another job.")
job["phase"] = "submitting" # Persist BEFORE sending, including the stable key.
save_job(path, job)
reply = call("submit", job["input"])
data = reply.get("data") if isinstance(reply.get("data"), dict) else {}
job["task_id"] = reply.get("taskId") or data.get("taskId")
save_job(path, job)
if not job["task_id"]:
raise RuntimeError("No task ID returned. Keep this job and recover it.")
on_progress(f"Saved task ID: {job['task_id']}")
deadline = time.monotonic() + max_wait
while time.monotonic() < deadline:
reply = call("query", {"taskId": job["task_id"]})
data = reply.get("data") if isinstance(reply.get("data"), dict) else {}
status = str(data.get("status") or reply.get("status") or "unknown").lower()
on_progress(f"Task {job['task_id']}: {status.upper()}")
if status in ("failed", "error", "needs_input"):
raise RuntimeError(f"Task stopped: {status}. Check the saved response and billing.")
if status in ("completed", "success", "succeeded"):
url = data.get("videoUrl") or reply.get("videoUrl") or reply.get("result")
if not isinstance(url, str) or not url.startswith("https://"):
raise RuntimeError("Result URL missing. Query this same task again.")
break
time.sleep(min(5, max(0, deadline - time.monotonic())))
else:
raise TimeoutError("Local wait ended. Resume with the same inputs and job path.")
output.parent.mkdir(parents=True, exist_ok=True)
partial = output.with_name(output.name + ".part")
try:
with requests.get(url, stream=True, timeout=(10, 60)) as response:
response.raise_for_status() # No VidMage API key is sent to the media URL.
with partial.open("wb") as stream:
for chunk in response.iter_content(1024 * 1024):
stream.write(chunk)
with partial.open("rb") as stream:
if stream.read(12)[4:8] != b"ftyp":
raise RuntimeError("Download is not an MP4. Keep the task ID.")
partial.replace(output)
except requests.RequestException:
raise RuntimeError("Download failed. Resume this task; do not submit another.") from None
finally:
partial.unlink(missing_ok=True)
job.update(phase="completed", download_path=str(output.resolve()))
save_job(path, job)
on_progress(f"Saved MP4: {output.name} ({output.stat().st_size:,} bytes)")
return {"task_id": job["task_id"], "status": "completed",
"file_path": job["download_path"]}
if __name__ == "__main__":
if not os.environ.get("VIDMAGE_API_KEY"):
os.environ["VIDMAGE_API_KEY"] = getpass.getpass("VidMage API key (hidden): ")
print(json.dumps(INPUTS, indent=2))
print(f"Example estimate: {int(INPUTS['duration']) * 10} credits.")
try:
result = generate_video(INPUTS, "private/video-job.json", "paper-boat.mp4")
print(json.dumps(result, indent=2))
except (RuntimeError, ValueError, OSError) as error:
print(f"Stopped: {error}")
raise SystemExit(1)
Step 3: Review the prompt and settings in INPUTS. The table below lists the supported values for this example. Save a file named requirements.txt in the same folder with this one line:
requests>=2.32.3,<3
In text-to-video mode, the Grok Video Generator accepts these values. This example supplies all four fields explicitly. Send each value as a string, including the duration.
Field | What it does | Supported values |
|---|---|---|
prompt | Describes the video you want (required) | 5 to 800 characters |
duration | Sets the clip length in seconds | "6" (default) or "10" |
aspectRatio | Sets the frame shape | "16:9" (default), "9:16", or "1:1" |
resolution | Sets the output quality | "480p" or "720p" (default) |
Both resolutions currently cost 10 credits per second, so a 6-second clip costs 60 credits and a 10-second clip costs 100. The example prints that estimate before it submits anything. Other VidMage video endpoints use different field names and limits, so check the model reference if you switch to another one.
To adapt this example, check the chosen generator’s documentation and update the endpoint, input validation, result fields, and credit estimate as needed. Changing CAPABILITY alone is not enough.
If you want to try other values before you put them in INPUTS, the VidMage Playground can show you the fields and the credit cost, and it can show a cURL version of the request if you prefer to test that way. Keep in mind that Submit in the Playground starts a real task and uses credits.
Step 4: Open a terminal in the project folder, install requests in a virtual environment, and start the example. These are the only commands you type; the Python code makes every API call.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python vidmage_video.py
On Windows, create the environment with py -m venv .venv. In Command Prompt, activate it with .venv\Scripts\activate.bat; in PowerShell, use .venv\Scripts\Activate.ps1. If VIDMAGE_API_KEY is not set, the example asks for the key with a hidden prompt, keeping it off your screen and out of shell history. That prompt is only for the local run; server code reads the key from its environment. The script prints your settings and the credit estimate, saves the task ID, and prints progress as it checks the task.

Step 5: Wait for the status to change to COMPLETED. The code then downloads the MP4, saves it as paper-boat.mp4, and returns a small dictionary with task_id, status, and file_path. Your application can store that path, move the file to its own storage, or send it to the user.

Open the MP4 and check that it matches your prompt. The paper boat request above returned a clip of about 6 seconds at 1290 x 714 pixels and 24 frames per second. Your own file can differ slightly from the requested 16:9 shape, so check its real dimensions before you place it in a fixed layout.

How the Code Tracks One Task From Submit to MP4
The main function follows the request from submission to download. The save_job() helper writes its recovery record, and the small call() helper inside generate_video() sends authenticated API requests and saves their responses.
- Save the request: The code checks the four inputs and stores them with the endpoint and a unique idempotency key. Reusing a job file with different inputs or another endpoint raises an error.
- Submit once: Before sending the request, the code marks the job as submitting. It then saves the returned task ID. If the response is lost, a rerun stops for recovery instead of silently submitting again.
- Check progress: The code queries the saved task at five-second intervals until completion or its local wait limit. API errors stop the example and leave the response, tracing ID, and any Retry-After value in the private job file. After a rate limit, wait for that delay before resuming.
- Save the video: The code downloads without sending the API key, writes a temporary .part file, checks the MP4 header, and moves the file into place. It returns the task ID, status, and local path. If the saved file already exists on a later call, the function returns it without an API request.
How to Call generate_video() From Your Own App
Your application imports generate_video() from the same file. Give each generation its own job file and output file, named by an ID your server creates, such as a database row ID. Never build these paths from text a user typed.
from pathlib import Path
from vidmage_video import generate_video
def create_video(job_id, prompt):
inputs = {"prompt": prompt, "duration": "6", "aspectRatio": "16:9", "resolution": "720p"}
return generate_video(inputs,
Path("private/jobs") / f"{job_id}.json",
Path("videos") / f"{job_id}.mp4")
A generation doesn't finish instantly, so run this function in a background worker or task queue rather than inside a web request that the browser waits on. Your front end can show a "processing" state and check your own database for the finished file. A few more details help when you move the code into an app:
• The returned keys (task_id, status, file_path) come from this Python function. The VidMage API itself returns taskId and videoUrl.
• file_path points to a file on your server, not a public link. Serve or upload the file the way your app already handles media.
• Pass on_progress to send status lines to your logger instead of printing them, and max_wait to change how long one call keeps checking (300 seconds by default).
• Let only one worker handle a given job file at a time. For many workers, keep the same task record in your database with proper locking.
• Keep the private folder out of public downloads and repositories. Job files hold the task ID and idempotency key, and can hold a signed video link.
How to Resume a Task Without Paying Twice
One job file tracks one generation request. Most problems after a successful submit don't need a new task, so the code picks up the same one:
• The local wait runs out: Reaching the code’s local wait limit does not cancel the task or tell you its current status. Run the same code again with the same inputs and job path to check whether the task is still running, has completed, or has failed.
• The download fails: The code keeps the task ID. Run it again, and it queries the same task for its result URL before retrying the download. It does not submit another generation.
• The submit response never arrives: VidMage may still have accepted the task, so the code stops and asks you to recover it. Check Task history in the Developer Console or call GET https://vidmage.ai/api/v1/tasks/recent?limit=10. When you find the matching task, add its ID to the job file as "task_id" and run the code again to continue tracking it.
• VidMage created no task: If you confirm that VidMage created no task and the error's recovery action allows a retry, change "phase" to "prepared" in the same job file and run it again. The retry reuses the saved request and idempotency key, which tells VidMage it's the same request.
Never delete a job file to "start over" while a task might exist, and create a new job file only when you want a genuinely new video. VidMage refunds confirmed failures automatically only when the refund outcome is certain, so check the task in Task history before you submit a replacement. Download your video soon after it completes, since VidMage doesn't publish how long result links stay available, and treat the signed link like a private file link. VidMage's task lifecycle guide covers recovery in more detail.
How to Fix Common VidMage Video API Errors
When something goes wrong, the example prints Stopped: followed by the reason. The table covers the messages you are most likely to see, and VidMage's error guide lists every API code.
Message | What to try |
|---|---|
Set VIDMAGE_API_KEY in the server environment | Add the key to the environment of the process that runs the code, or run vidmage_video.py locally and paste the key at the hidden prompt. |
HTTP 401 with NEED_API_KEY, AUTHENTICATION_REQUIRED, or API_KEY_INVALID_OR_REVOKED | Check that the key still shows Active in the Developer Console and that you copied it without extra spaces. If you revoked it, create a new key. |
HTTP 402 with NEED_PURCHASE_CREDITS | Your balance doesn't cover the request. Add credits, or choose "6" instead of "10" for the duration. |
HTTP 403 with NEED_SUBSCRIBE | Your subscription is inactive. Renew it, and your existing keys start working again. |
Check the prompt and all four supported input fields | This is a local validation error, so this attempt has not submitted an API request. Supply all four fields and match the supported-values table. |
This job belongs to different inputs or another endpoint | You changed INPUTS or the endpoint but kept the same job file. Restore the original values to resume that task. Use a new job path only for a deliberately new generation. |
submit connection failed, Submission needs recovery, or HTTP 409 with IDEMPOTENCY_IN_PROGRESS | VidMage may have accepted the task or may still be handling it. Keep the same job file and follow the recovery steps above before trying again. |
Local wait ended or query connection failed | This error does not cancel the task or establish its current status. Run the code again with the same inputs and job path to check the same task. |
Task stopped: failed or error | Inspect the saved response and check the task’s billing or refund status in Task history. Resolve any uncertain outcome before submitting a corrected request with a new job file. |
Download failed or Download is not an MP4 | Run the code again with the same inputs and job path. It queries the same task for its result URL and retries the download without creating another generation. |
BILLING_OUTCOME_UNKNOWN or REFUND_OUTCOME_UNKNOWN | Don't resubmit or create a new idempotency key. Follow the recovery action in the response, and keep the task ID, idempotency key, and request ID for VidMage support. Never send support your API key. |
HTTP 429 with RATE_LIMITED | The example stops and saves Retry-After. Wait for the indicated seconds or HTTP date before resuming the same task. It does not automatically retry this error. |
A 401, 402, or 403 error at submit also marks the job for recovery, so the code won’t resend it automatically. After fixing the cause, follow the API’s recovery instructions. A task’s absence from the visible Task history alone does not prove that no task was created. Use the “VidMage created no task” retry procedure only after confirming that no task was created and that the recovery instructions allow a retry.
Try it in VidMage
Open the tool and follow the steps above.

