To generate images with the VidMage image generation API, your application sends a text prompt to VidMage, saves the returned task ID, polls the task until it finishes, and downloads the image. This guide puts that whole flow into one reusable Python function, using VidMage's Text to Image endpoint as the example.
NOTE: The Text to Image endpoint currently costs 5 credits per image, taken from the same balance you use on the VidMage website. You will also need an active VidMage subscription and an API key before you start.
What the Python Example Does
VidMage returns a task ID after accepting the request. The Python function then checks progress through separate requests while it waits for the image to finish. The example wraps that flow in one function, generate_image(), which:
- Accepts a prompt and an aspect ratio from your application.
- Saves the request and a unique idempotency key to a private job file before it sends anything.
- Submits the task once with your API key and saves the task ID right away.
- Checks the same task every five seconds until VidMage reports that it's complete.
- Downloads the image, checks that it opens, and returns its file path, format, and size to your code.
Other VidMage image APIs follow a similar submit, check, and download pattern, but their routes, fields, settings, and prices can differ. Check each one in the VidMage API documentation before you adapt this code, because changing the endpoint name alone won't make it work with another API.
This example starts from a text prompt, so there's no file to upload. If you choose an API that accepts a reference image, VidMage's file uploads guide shows how to prepare the upload, send the file to its temporary upload URL, and pass the returned file URL in that API's input field before you submit the task.
What You Need Before You Call the AI Image API
- An active VidMage subscription: AI Image API access is for subscribers only. Without a plan, VidMage returns the submission with a 403 NEED_SUBSCRIBE message. See the authentication guide.
- A VidMage API key: You create it in the Developer Console under API keys. VidMage shows the full key only once, so keep it somewhere private, like a password manager.
- At least 5 credits: API calls and website tasks share one credit balance. Check the billing guide for better clarity on the cost and usage.
- Python 3.10 or newer: The setup command installs the two libraries the code uses:
- requests sends the API calls
- Pillow checks the downloaded image.
You don't need a website or front end. You can test the function as a standalone script, then call it from a background worker in your application.
How to Generate Images With the VidMage API in Python
Step 1: Sign in to VidMage, open the Developer Console, and click API keys in the left menu. Check that the key you plan to use says Active under Status. The console only shows the first few characters of each key, so you need the full key you saved when you created it. Store that key on your server as an environment variable named VIDMAGE_API_KEY, the same way you store any other secret.

Step 2: Create an empty folder for the project and save the code below in it as vidmage_image.py. This one file holds the reusable generate_image() function your app imports, plus a short block at the bottom that runs the example on its own.
"""Reusable VidMage image example. Use one worker per private job file."""
import getpass
import json
import os
import time
import uuid
from pathlib import Path
import requests
from PIL import Image
CAPABILITY = "text-to-image"
BASE = f"https://vidmage.ai/api/v1/{CAPABILITY}"
INPUTS = {
"prompt": "A red paper kite above a golden wheat field at sunrise, "
"soft watercolor illustration, open sky, no text",
"aspectRatio": "4:3",
}
RATIOS = ("auto", "1:1", "16:9", "9:16", "4:3", "3:4", "3:2",
"2:3", "5:4", "4:5", "21:9")
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_image(inputs, job_path, output_base, *, 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", "aspectRatio"}
or not isinstance(inputs["prompt"], str) or not inputs["prompt"].strip()
or inputs["aspectRatio"] not in RATIOS):
raise ValueError("Supply a nonempty prompt and a supported aspectRatio string.")
path, output_base = Path(job_path), Path(output_base)
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("result") and Path(job["result"]["file_path"]).is_file():
return job["result"]
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, http_status=response.status_code,
request_id=response.headers.get("X-Request-Id"),
retry_after=response.headers.get("Retry-After"))
if action == "submit":
job["submit_response"] = payload
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" # Save the original body and key BEFORE sending.
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("imageUrl") or reply.get("imageUrl") 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_base.parent.mkdir(parents=True, exist_ok=True)
partial = Path(str(output_base) + ".part")
try:
with requests.get(url, stream=True, timeout=(10, 60)) as response:
response.raise_for_status() # No VidMage 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 Image.open(partial, formats=("PNG", "JPEG", "WEBP")) as picture:
picture.load() # Check that the downloaded image actually decodes.
image_format, size = picture.format, list(picture.size)
extension = {"PNG": ".png", "JPEG": ".jpg", "WEBP": ".webp"}[image_format]
output = Path(str(output_base) + extension)
partial.replace(output)
except requests.RequestException:
raise RuntimeError("Download failed. Resume this task; do not submit another.") from None
except OSError:
raise RuntimeError("Image could not be saved or decoded. Keep this task ID.") from None
finally:
partial.unlink(missing_ok=True)
result = {"task_id": job["task_id"], "status": "completed",
"file_path": str(output.resolve()), "format": image_format, "size": size}
job.update(phase="completed", result=result)
save_job(path, job)
on_progress(f"Saved image: {output.name} ({output.stat().st_size:,} bytes)")
return result
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("Text to Image estimate: 5 credits. Reuse the job file to resume.")
try:
result = generate_image(INPUTS, "private/image-job.json", "red-kite")
print(json.dumps(result, indent=2))
except (RuntimeError, ValueError, OSError) as error:
print(f"Stopped: {error}")
raise SystemExit(1)
In the same folder, save a file named requirements.txt with these two lines:
requests>=2.32.3,<3
Pillow>=11,<14
The block under if __name__ == "__main__": at the bottom is only a local demo. If VIDMAGE_API_KEY is not set, it asks for your key without showing it on screen, prints the inputs, and calls generate_image(). The function itself always reads the key from the environment, which is how your server will supply it.
Step 3: Set your prompt and aspect ratio in INPUTS near the top of the file. In this example, you can see a red paper kite above a wheat field with a preferred 4:3 aspect ratio. The demo then passes INPUTS to generate_image() with two paths:
- private/image-job.json for the job record
- red-kite for the finished image.
Change these values when you want a different image.
VidMage currently accepts these aspectRatio values: auto, 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 5:4, 4:5, and 21:9.
The ratio tells VidMage the shape you'd like, and the provider picks the exact pixels. The API treats aspectRatio as optional and uses 9:16 if you leave it out.
If you'd like to try a prompt or check the cost before you run any code, the AI Text to Image API page has a Playground with the same fields. Its Submit button starts a real, paid task, so you don't need to click it here.

Step 4: Open a terminal in the project folder, create a virtual environment, install the two libraries, and run the file:
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python vidmage_image.py
On Windows, use .venv\Scripts\python.exe in place of .venv/bin/python.
If you have not set VIDMAGE_API_KEY, paste your full API key at the prompt. Nothing appears while you paste. Each run with a new job file submits a paid generation, so run it once and let it finish. The script prints the task ID as soon as it saves it, then prints the status each time it checks the task.

Your output can look slightly different. For example, the Submit: HTTP 200 line above came from the logging that recorded this run, not from vidmage_image.py. You can also follow the task in the Developer Console, where Task history lists the text-to-image task with its credits and billing status.
Step 5: Use the result that generate_image() returns. When VidMage reports COMPLETED, the code downloads the image, checks that it opens, saves it with the matching file extension, and returns a result like this:
{
"task_id": "2118182499683127298",
"status": "completed",
"file_path": ".../red-kite.png",
"format": "PNG",
"size": [1184, 864]
}
size is the width and height in pixels. file_path points to a file on your server, not a public link. To show the image in a web app, have your server serve that file, or copy it to your own storage and return that URL.


How the Code Tracks One Image From Submit to File
- Saving the job: save_job() writes a temporary file before replacing the job record, which helps protect against incomplete writes. On macOS and Linux, it sets owner-only file permissions. On Windows, it protects the job folder using its security settings.
- Before it submits: generate_image() checks the inputs, then saves them with a new idempotency key and marks the job as submitting. That record exists before VidMage ever receives the request.
- Submitting: The code sends your key in the Authorization header and the saved key in the Idempotency-Key header. It saves the task ID the moment VidMage returns it.
- Checking progress: The code asks about the same task ID every five seconds. VidMage can put the status inside the data or at the top of the reply, so the code reads both. It stops on FAILED or ERROR, and it stops checking after max_wait seconds (300 by default). That limit only covers the checking loop, so a slow network call can stretch the total time a little.
- Downloading: The code uses a separate request without your VidMage key, because the image link doesn't need it. The file arrives as a .part file, Pillow checks that it decodes, and only then does the code give it its final name.
- Handling errors: A failed API call stops the function with a short message. The job file retains the submission response and the latest API response, along with the latest HTTP status, X-Request-Id, and any Retry-After value. A connection failure may leave no new response to save. Your API key is never stored in the job file.
The job file keeps full replies from VidMage, and those can include the signed image link. Treat the file as private and never publish it.
Add Image Generation to Your Application
Import the function and pass it the inputs from your app, a job path, and an output path without an extension:
from vidmage_image import generate_image
result = generate_image(
{"prompt": "A quiet mountain lake at dawn, watercolor, no text", "aspectRatio": "16:9"},
"private/jobs/customer-request-42.json",
"generated/customer-request-42",
)
image_path = result["file_path"]
Give each new image request its own job path, and keep the same path for that request, even when you retry it. If you pass a job file that belongs to different inputs, the function stops with “This job belongs to different inputs or another endpoint.” Your server should choose these paths, not your users.
Checking a task can take a while, so run the function in a background worker instead of inside a browser request. Use one worker per job file. If several workers can pick up the same job, store the record in a database with a lock. You can also pass your own on_progress function in place of print to send status updates to your logs or your app.
How to Resume a Task Without Paying Twice
A timeout does not mean VidMage failed to make your image. VidMage may have started the task before your connection dropped, so sending a brand new request could charge you twice. The saved job file is what prevents that.
- The job file already has a task ID: Call generate_image() again with the same inputs and job path. It skips submission and keeps checking the same task. This covers "Local wait ended," a dropped connection while checking, and a failed download.
- The image is already saved: Calling the function again returns the saved result without making any API requests.
- VidMage returns 429 RATE_LIMITED: The function stops and saves any Retry-After value as retry_after in the job file. Follow that delay before continuing. If a task ID is already saved, call the function again with the same job file to resume checking it. If submission stopped before an ID was saved, follow the recovery steps below. The code does not retry automatically.
- Submission stopped before a task ID was saved: The function won't resend the request by itself. It stops with "Submission needs recovery." Check Task history, or ask VidMage for your recent tasks with GET https://vidmage.ai/api/v1/tasks/recent?limit=10 and your Bearer key. Find the exact text-to-image task that matches this request instead of picking the newest one, then add its ID to the original job file and resume:
import json
from pathlib import Path
from vidmage_image import INPUTS, generate_image, save_job
job_path = Path("private/image-job.json")
job = json.loads(job_path.read_text())
job["task_id"] = "CONFIRMED_EXISTING_TASK_ID"
save_job(job_path, job)
result = generate_image(INPUTS, job_path, "red-kite")
If the task doesn't appear yet, that doesn't prove the submission failed. Wait a minute and check again. If an error reply includes a recovery action, follow it first. Retry only when that guidance says it's safe, and send the same request body with the same idempotency key. Never delete the job file or create a new key to force a retry. A new job file, and with it a new idempotency key, is only for a genuinely new generation request, even if that request happens to use the same prompt. VidMage's task lifecycle guide covers recovery in more detail.

Troubleshooting the VidMage Text to Image API
Problem | What to try |
|---|---|
"Set VIDMAGE_API_KEY in the server environment." | The function couldn't find your key. Set the environment variable on your server, or run the file directly so the demo asks for the key. |
HTTP 401: NEED_API_KEY | VidMage didn't receive a valid key. Paste the full key, not the shortened value the console shows, and confirm it still says Active. If you revoked it, create a new key. |
HTTP 403: NEED_SUBSCRIBE | API access needs an active subscription. Renew or start a plan, and your existing keys work again. |
HTTP 402: NEED_PURCHASE_CREDITS | Your shared balance has fewer than 5 credits. Add credits before you try again. |
"Submission needs recovery" after a 401, 402, or 403 | Fix the key, subscription, or credit issue, then inspect the saved response and follow VidMage’s recovery guidance. If you recover a matching task ID, add it to the existing job file and resume. An empty Task history alone does not confirm that starting a new job is safe; contact support if the outcome remains unclear. |
HTTP 400: VALIDATION_ERROR, or "Supply a nonempty prompt and a supported aspectRatio string." | Use a nonempty prompt and a supported aspectRatio string, such as "4:3". If local validation stops the first run before a job file is created, correct the inputs and run it again. If a submit request was already sent, resolve its saved outcome before creating a new job for corrected inputs. |
HTTP 409: IDEMPOTENCY_CONFLICT | VidMage saw the saved key with a different request body. Go back to the original inputs, or use a new job file for a genuinely new request. |
Generation does not start, or "Local wait ended." | The task may still be running. Call the function again with the same inputs and job path. Don't submit a new request just because the image is taking longer than you expected. |
"Task stopped: failed." | Look at refunded in the saved response and the billing status in Task history. VidMage refunds automatically only when both the failure and the refund are certain. If an error says BILLING_OUTCOME_UNKNOWN or REFUND_OUTCOME_UNKNOWN, don't resubmit. Keep the job file and follow the error guide. |
"Download failed" or "Image could not be saved or decoded." | Call the function again with the same job file. It checks the same task again and downloads a new copy, with no new submission. |
If you contact VidMage support, share the capability name (text-to-image), the HTTP status, the errorType, your task ID, and the request_id value from the job file, which holds the X-Request-Id of the last call. Never share your API key or the job file itself.
Try it in VidMage
Open the tool and follow the steps above.

