To swap faces in photos with the VidMage photo face swap API, your application uploads two photos, shows the user the faces VidMage found, submits one task with the chosen face numbers, and saves the finished image when the task completes. The target photo supplies the scene, and the reference photo supplies the face. This guide puts that whole flow into one reusable Python file that you can run on its own or call from your app.
NOTE: Each photo swap currently costs 1 credit. VidMage keeps the scene, pose, and clothes from your target photo and only changes the face you pick.
What You Need Before You Swap Faces With the API
- A VidMage subscription and API key: API keys only work with an active subscription. If you don’t have a key yet, you can create one in the Developer Console.
- At least 1 credit: Your website and API activity share one credit balance, so a swap you run on the website also comes out of the same pool.
- Two photos you have permission to use: The target photo is the scene you want to keep. The reference photo shows the face you want to put in. A clear, front-facing face with good light gives VidMage the easiest job, and a reference photo with just one person keeps things simple.
You don’t need a website or front end. Check VidMage’s developer docs for the accepted file types and upload limits before you build this into an app.
How the Python Example Turns Two Photos Into One Swap
The file photo_swap.py holds a small class called PhotoSwap. It keeps one private job folder per swap and gives your app three methods to call in order:
- prepare(target, reference): It uploads both photos, asks VidMage to find the faces in each one, and saves a small preview of every face. It returns one list of face choices for each photo.
- submit(target_index, reference_index): It checks the two faces the user picked, saves the request and a unique idempotency key, sends one paid face swap task, and saves the task ID.
- result(): It checks that same task until it finishes, downloads the image, and returns the path to the saved file. It never submits a new task.
How to Swap Faces in Photos With the VidMage API in Python
Step 1: Open the Developer Console and click API keys. Use any key marked Active, or click Create API key to make a new one. Store that key on your server as an environment variable named VIDMAGE_API_KEY, and keep it out of browser code, public repositories, and logs.

Step 2: Create an empty folder for the project and save the code below in it as photo_swap.py. This one file holds the reusable PhotoSwap class that your app imports, plus a short block at the bottom that runs the example on its own.
"""One private directory per swap; run one worker at a time for that directory."""
import getpass
import hashlib
import io
import json
import os
import sys
import time
import uuid
from pathlib import Path
from tempfile import NamedTemporaryFile
import requests
from PIL import Image
BASE = "https://vidmage.ai/api/v1"
FIELDS = {"target": "targetImageUrl", "reference": "referenceFaceImageUrl"}
EXT = {"JPEG": ".jpg", "PNG": ".png", "WEBP": ".webp"}
def transfer(method, url, **kwargs):
if not isinstance(url, str) or not url.startswith("https://"):
raise ValueError("Missing HTTPS URL. Inspect the saved job.")
try:
return requests.request(method, url, timeout=(10, 60), **kwargs)
except requests.RequestException:
raise RuntimeError("Connection interrupted. Keep the job and check its last step.") from None
def get_image(url, stem):
reply = transfer("GET", url)
if reply.status_code != 200:
raise RuntimeError(f"Image download: HTTP {reply.status_code}. Keep the job.")
raw = reply.content
with Image.open(io.BytesIO(raw), formats=tuple(EXT)) as im:
im.load()
path = stem.with_suffix(EXT[im.format])
part = path.with_suffix(".part")
part.write_bytes(raw)
part.replace(path)
return path
class PhotoSwap:
def __init__(self, folder):
self.folder = Path(folder).resolve()
self.folder.mkdir(parents=True, exist_ok=True, mode=0o700)
self.path = self.folder / "job.json"
self.job = json.loads(self.path.read_text()) if self.path.exists() else {}
self.key = os.environ.get("VIDMAGE_API_KEY")
if not self.key:
raise ValueError("Set VIDMAGE_API_KEY on the server.")
def save(self):
with NamedTemporaryFile(mode="w", dir=self.folder, delete=False) as tmp:
json.dump(self.job, tmp)
tmp.flush()
os.fsync(tmp.fileno())
Path(tmp.name).replace(self.path)
def api(self, route, body, idem=None):
headers = {"Authorization": f"Bearer {self.key}"}
if idem:
headers["Idempotency-Key"] = idem
reply = transfer("POST", BASE + route, json=body, headers=headers, allow_redirects=False)
try:
data = reply.json()
except ValueError:
data = {}
if not isinstance(data, dict):
data = {}
if not 200 <= reply.status_code < 300 or data.get("success") is not True:
self.job["error"] = {"route": route, "http": reply.status_code, "response": data,
"trace": reply.headers.get("X-Request-Id"),
"retry_after": reply.headers.get("Retry-After")}
self.save()
raise RuntimeError(f"{route}: HTTP {reply.status_code}, {data.get('errorType')}. See private job.")
return data
def upload(self, raw, name, parameter):
with Image.open(io.BytesIO(raw), formats=tuple(EXT)) as im:
im.load()
mime = Image.MIME[im.format]
ticket = self.api("/files/upload", {"capability": "face-swap", "parameter": parameter,
"fileName": name, "contentType": mime, "fileSize": len(raw)})
put = transfer("PUT", ticket["uploadUrl"], data=raw, headers=ticket["headers"],
allow_redirects=False) # Never add the account key to storage headers.
if not 200 <= put.status_code < 300:
raise RuntimeError(f"Storage returned HTTP {put.status_code}; stop before submission.")
print(f"Uploaded {name}: {parameter} ({len(raw):,} bytes)")
return ticket["fileUrl"]
def prepare(self, target, reference):
"""Analyze each photo as a target; return indexed local previews for each picker."""
photos = {role: Path(p) for role, p in zip(FIELDS, (target, reference))}
blobs = {role: path.read_bytes() for role, path in photos.items()}
ids = {role: hashlib.sha256(raw).hexdigest() for role, raw in blobs.items()}
if self.job.get("inputs", ids) != ids:
raise ValueError("Different photos: use a separate job for a new swap.")
self.job["inputs"] = ids
choices = {}
for role, raw in blobs.items():
item = self.job.setdefault(role, {})
item["source"] = str(photos[role].resolve())
if "analysis_url" not in item:
# The analysis helper accepts a target-bound URL, including for our second gallery.
item["analysis_url"] = self.upload(raw, photos[role].name, "targetImageUrl")
self.save()
if not item.get("faces") or any(not (self.folder / f["file"]).is_file() for f in item["faces"]):
def analyze(**fields):
return self.api("/face-analysis", {"capability": "face-swap", **fields})
step = (analyze(analysisId=item["analysis_id"]) if item.get("analysis_id")
else analyze(targetUrl=item["analysis_url"]))
item["analysis_id"] = step["analysisId"]
self.save()
until = time.monotonic() + 300
while step["status"] == "RUNNING":
if time.monotonic() >= until:
raise TimeoutError("Resume prepare() with the same photos and folder.")
time.sleep(5)
step = analyze(analysisId=item["analysis_id"])
faces = step.get("faces") or []
if step["status"] != "COMPLETED" or not faces:
raise RuntimeError(f"No usable {role} previews. Stop before submitting.")
indexes = [f["index"] for f in faces]
if any(type(i) is not int or i < 0 for i in indexes) or len(set(indexes)) != len(indexes):
raise ValueError("Invalid or duplicate preview indexes.")
item["faces"] = [{"index": f["index"], "file": get_image(f["previewUrl"],
self.folder / f"{role}-{f['index']}").name} for f in faces]
self.save()
choices[role] = item["faces"]
return choices
def submit(self, target_index, reference_index):
"""An app calls this only after a user selects from each set of previews."""
selection = {"target": target_index, "reference": reference_index}
for role, index in selection.items():
if type(index) is not int or index not in [f["index"] for f in self.job[role]["faces"]]:
raise ValueError(f"Choose an index shown for the {role} photo.")
if self.job.get("selection", selection) != selection:
raise ValueError("The saved request has different face choices.")
if self.job.get("task_id"):
return self.job["task_id"]
if "idempotency_key" in self.job:
raise RuntimeError("Prior submission has no saved task ID. Recover it before any retry.")
ref = self.job["reference"]
if len(ref["faces"]) == 1:
file = Path(ref["source"]) # Keep original quality for a single-face reference.
raw = file.read_bytes()
if hashlib.sha256(raw).hexdigest() != self.job["inputs"]["reference"]:
raise ValueError("Reference photo changed since analysis.")
else:
chosen = next(f for f in ref["faces"] if f["index"] == reference_index)
file = self.folder / chosen["file"] # Send only the selected face crop.
raw = file.read_bytes()
reference_url = self.upload(raw, file.name, "referenceFaceImageUrl")
body = {"targetImageUrl": self.job["target"]["analysis_url"], "referenceFaceImageUrl": reference_url,
"targetFaceIndex": target_index, "referenceFaceIndex": 0} # Single face in submitted reference.
print(f"Selected gallery indexes: target={target_index}, reference={reference_index}")
print(f"Submission fields: targetFaceIndex={target_index}, referenceFaceIndex=0")
self.job.update(body=body, selection=selection, idempotency_key=str(uuid.uuid4()))
self.save() # Persist exact URLs, indexes and key BEFORE the billable POST.
reply = self.api("/face-swap/submit", body, self.job["idempotency_key"])
self.job.update(submit_reply=reply, task_id=reply.get("taskId"))
self.save()
if not self.job["task_id"]:
raise RuntimeError("Missing task ID. Keep the job and recover the submission.")
print(f"Saved task ID: {self.job['task_id']}")
return self.job["task_id"]
def result(self, max_wait=300):
"""Resume by task ID; this method never submits. Returns a local image path."""
if self.job.get("file") and (self.folder / self.job["file"]).is_file():
return self.folder / self.job["file"]
task_id = self.job.get("task_id")
if not task_id:
raise ValueError("No saved task ID. Recover the submission first.")
until = time.monotonic() + max_wait
while time.monotonic() < until:
reply = self.api("/face-swap/query", {"taskId": task_id})
self.job["query_reply"] = reply
self.save()
data = reply.get("data") or {}
status = str(data.get("status") or reply.get("status")).upper()
print(f"Task {task_id}: {status}")
if status in ("COMPLETED", "SUCCESS", "SUCCEEDED"):
file = get_image(data.get("imageUrl") or reply.get("imageUrl"), self.folder / "swapped")
self.job["file"] = file.name
self.save()
return file
if status in ("FAILED", "ERROR", "NEEDS_INPUT"):
raise RuntimeError(f"Task needs attention: {status}. Keep the same ID.")
time.sleep(5)
raise TimeoutError("Local wait ended. Call result() again with the same job.")
if __name__ == "__main__":
if len(sys.argv) != 4:
sys.exit("Usage: python photo_swap.py TARGET_PHOTO REFERENCE_PHOTO JOB_FOLDER")
if not os.environ.get("VIDMAGE_API_KEY"):
os.environ["VIDMAGE_API_KEY"] = getpass.getpass("VidMage API key (hidden): ")
swap = PhotoSwap(sys.argv[3])
choices = swap.prepare(sys.argv[1], sys.argv[2])
if not swap.job.get("task_id"):
if "idempotency_key" in swap.job:
sys.exit("Keep this job and recover the original submission before trying again.")
gallery = swap.folder / "faces.html"
gallery.write_text("<title>Choose the faces for this swap</title>" + "".join(
f"<h2>{role.title()} photo</h2>" + "".join(
f'<figure><img width="160" src="{f["file"]}"><figcaption>Index {f["index"]}</figcaption></figure>'
for f in faces) for role, faces in choices.items()), encoding="utf-8")
print("Open this private gallery to see every face:", gallery)
selected = [int(input(f"Choose {role} index { [f['index'] for f in choices[role]] }: "))
for role in ("target", "reference")]
swap.submit(*selected)
print("Saved image:", swap.result())
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. Then it prepares both photos, writes a small gallery page of the faces it found, asks you for the two face numbers, and prints the path of the saved image. The PhotoSwap class itself always reads the key from the environment, which is how your server will supply it.
Step 3: Copy your target photo and your reference photo into the project folder. For example, here the target.png shows a man at a café table, and reference.png shows a woman walking two dogs.
NOTE: In face swapping, the order plays a very crucial role. The first photo you pass is always the target, and the second is always the reference.

If you want to check the request fields or the cost before you run any code, the AI Photo Face Swap API page has a Playground with the same four fields. Its Submit button starts a real, paid task, so you don’t need to click it here.
Step 4: Open Terminal in the project folder, create a virtual environment, install the two libraries, and run the file with your two photos and a job folder:
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python photo_swap.py target.png reference.png private/cafe-swap
IMPORTANT: On Windows, use .venv\Scripts\python.exe in place of .venv/bin/python.
The last argument, private/cafe-swap, is the private folder for this one swap. If you have not set VIDMAGE_API_KEY, paste your full API key at the prompt. The script uploads both photos and asks VidMage to find the faces in each one, which takes a moment.

When the face analysis finishes, the script saves a preview of each face in the job folder and prints the path to a page called faces.html.
Step 5: Open faces.html in your browser. Each face appears under Target photo or Reference photo, with its index number underneath. With the sample photos, VidMage finds one face in each photo, so both groups show Index 0.

Back in Terminal, type the target face number at the first prompt and the reference face number at the second. The script only accepts a number shown for that photo. Entering the second number starts a paid swap, so check both choices first. The script prints the numbers it’s sending, saves the task ID, and then checks the task every five seconds.


Don’t read creditsConsumed: 0 in the submit reply as a free task. The usageDeferred: true flag means VidMage records the charge while the task runs, and the later checks show the 1 credit the swap used.
Step 6: When the task says COMPLETED, the script downloads the image, checks that it opens, names it by its real file type, and prints its path, such as private/cafe-swap/swapped.jpg. Compare it with your target photo to check that the right face changed.

How Your App Shows Face Choices and Passes the Indexes
In your own app, prepare() and submit() run in two separate requests, with the user’s choice in between:
from photo_swap import PhotoSwap
# First server handler: authenticated user supplied these two files.
# The server assigns a private folder to this user's request.
swap = PhotoSwap(job_folder)
choices = swap.prepare(target_path, reference_path)
# Render each returned {index, file} in its own target/reference group.
# Use an authorized image-serving route for each preview; do not serve job.json.
# Second handler: the user clicked one thumbnail in each group.
swap = PhotoSwap(job_folder)
task_id = swap.submit(selected_target_index, selected_reference_index)
# A background worker can resume later, even in another process:
saved_image = PhotoSwap(job_folder).result()
The variables in this snippet belong to your app, not to VidMage. prepare() returns a list of faces for each photo. Each entry holds the face’s index from VidMage and the file name of its preview. For the sample photos, it returns:
{
"target": [{"index": 0, "file": "target-0.jpg"}],
"reference": [{"index": 0, "file": "reference-0.jpg"}]
}
Here’s how to turn that into a face picker:
- Show Two Separate Groups: Render one group of thumbnails for the target photo and one for the reference photo, as buttons or radio controls. The user picks one face in each group.
- Use VidMage’s Index As The Value: Use the index VidMage returns for each face, even if your app displays the thumbnails in a different order. So the value on each control is the index VidMage gave that face, never its position on the page.
- Serve The Previews Privately: The previews sit in the job folder. Serve them through a route that checks the signed-in user, and never serve job.json.
- Send Back Only Two Numbers: The browser returns the two indexes along with your app’s own job ID. Your server loads the job folder that belongs to that user, converts the two values to integers, and calls submit(). If either number is invalid, submit() tells you which photo needs a different index. It stops before uploading the selected reference or submitting the paid swap.
- Run The Slow Parts In The Background: Face analysis and the status checks take time. Run prepare() and result() in a background worker, show the pickers when the previews are ready, and use one worker per job folder.
result() returns a pathlib.Path to a file on your server. Stream its bytes in your app’s response, or copy it to your own storage and give the user that link. Your server should choose every path and job folder, so never let the browser send a file path or an upload URL.
How the Selected Faces Reach the Paid Request
VidMage picks faces by number, and the numbers start at 0. Here’s how the two choices turn into the request:
- Target face: The code sends the number the user picked, unchanged, as targetFaceIndex.
- Reference photo with one face: The code uploads the original reference photo at full quality and sends referenceFaceIndex: 0. This is the path the sample photos take.
- Reference photo with several faces: The code uploads the preview of the face the user picked as the reference. That preview holds just one face, so the request sends referenceFaceIndex: 0, and the user’s choice decides which preview goes up. A preview is a small crop, so it can carry less detail than a clear portrait.
If VidMage returns no usable previews for a photo, the script identifies whether it was the target or the reference and stops before submitting the paid swap. Sending both indexes tells VidMage which faces the user chose. If the task still returns NEEDS_INPUT, keep its task ID and follow the recovery steps below.
Before the paid request goes out, submit() saves the exact request body, both choices, and a unique idempotency key in job.json. Then it sends one POST /api/v1/face-swap/submit with that key in the Idempotency-Key header and saves the task ID as soon as it comes back. The request body has this shape, with the two private file URLs left out:
{
"targetImageUrl": "[fileUrl from upload 1]",
"referenceFaceImageUrl": "[fileUrl from upload 3]",
"targetFaceIndex": 0,
"referenceFaceIndex": 0
}
result() then sends POST /api/v1/face-swap/query with the saved task ID every five seconds for up to five minutes. It reads the status from data.status or the top level of the reply, stops on FAILED, ERROR, or NEEDS_INPUT, and reads data.imageUrl once the task is COMPLETED. The download uses a separate request without your key, and Pillow checks that the image opens before the file gets its final name.
How to Resume a Swap Without Paying Twice
A timeout doesn’t mean the swap failed. VidMage may have accepted the task before your connection dropped, so sending a brand new request could charge you twice. The saved job folder is what prevents that.
- The job already has a task ID: Call PhotoSwap(job_folder).result() again. It checks the same task and never submits a new one, and it doesn’t need the photos or any new uploads. This covers “Local wait ended,” a dropped connection while checking, and a failed download. Running the demo again with the same three arguments does the same thing.
- The image is already saved: result() returns the saved file without making any API requests.

The local JPEG is 1122 × 1402 pixels and matches the verified download. Calling the saved job again returned the same file without an HTTP request.
- The submit stopped before a task ID was saved: submit() won’t send the request again. It stops with “Prior submission has no saved task ID. Recover it before any retry.” 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 face-swap task that matches this request instead of picking the newest one, then add its ID to the same job and resume:
from photo_swap import PhotoSwap
swap = PhotoSwap("private/cafe-swap")
swap.job["task_id"] = "PASTE_THE_MATCHING_TASK_ID"
swap.save()
print(swap.result())
If the task does not show up, that alone doesn’t prove the submission failed. Look at the saved error in job.json for a recovery value and follow it.
- GET_RECENT_TASKS means check recent tasks again
- QUERY_TASK_ID_OR_CONTACT_SUPPORT means query the task ID you have or contact support
- CONTACT_SUPPORT_WITH_IDEMPOTENCY_KEY_AND_BUSINESS_ID means send those details to support.
Never delete job.json or make a new idempotency key to force a retry.
- The submit got a 401, 402, 403, or 429: Fix the problem, then check recent tasks and the saved recovery value. If you find the matching task, save its ID in the original job folder and call result (). If you cannot tell whether VidMage accepted the swap, keep that folder and follow the recovery instructions in the response or contact support. Start a new job only after you have confirmed the first swap was rejected. If the response says UPLOAD_EXPIRED, the new job must upload the photos again.
- VidMage returns 429 while checking a task: The code saves the Retry-After value in job.json. Wait that long, then call result() again for the same job.
- The task returns NEEDS_INPUT or FAILED: Keep the task ID and check Task history for the billing status. Don’t send another paid request just to change a face number. A different choice is a new swap, so it needs a new job folder and costs another credit.
If any reply says BILLING_OUTCOME_UNKNOWN, SUBMISSION_OUTCOME_UNKNOWN, or REFUND_OUTCOME_UNKNOWN, stop and don’t resubmit. Contact VidMage support with the trace value from the saved error (the X-Request-Id), your task ID if you have one, and your idempotency key. VidMage’s task lifecycle guide and error reference guides cover recovery in more detail.
Face Swap API Troubleshooting
Problem | What to try |
|---|---|
“Set VIDMAGE_API_KEY on the server.” | The class 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 with NEED_API_KEY or API_KEY_INVALID_OR_REVOKED | Paste the full key, not the shortened value the console shows, and check that it still says Active. If you revoked it, create a new key in API keys. |
HTTP 403 NEED_SUBSCRIBE | Activate or renew your VidMage subscription. Your existing keys start working again after renewal. |
“/face-swap/submit: HTTP 402, NEED_PURCHASE_CREDITS” | Add credits. The job then stops for recovery, so follow the 401, 402, 403, or 429 steps in the resume section above. |
HTTP 400 VALIDATION_ERROR on an upload | Check the file path and that the file is a real JPEG, PNG, or WebP image. The code sends the actual file type and size, so a renamed or damaged file can fail here. |
“Storage returned HTTP …; stop before submission.” | The photo didn’t reach its upload link. Run the same command again with the same job folder. Nothing was submitted. |
“No usable target previews. Stop before submitting.” | VidMage didn’t find a face. Use a clear, well-lit face that looks toward the camera, in a new job folder. |
“Different photos: use a separate job for a new swap.” | That job folder belongs to other photos. Use a new folder for the new photos. |
“Choose an index shown for the reference photo.” | Type one of the numbers listed for that photo in faces.html. |
“The saved request has different face choices.” | This job already sent other face numbers. A different choice is a new swap in a new job folder. |
“Prior submission has no saved task ID. Recover it before any retry.” | Follow the recovery steps in the resume section. Don’t delete job.json. |
“Resume prepare() with the same photos and folder.” | Face analysis took longer than five minutes. Run the same command again, and it picks up the same analysis. |
“Local wait ended. Call result() again with the same job.” | The task is still running. Call result() again later. It only checks the same task. |
“Task needs attention: NEEDS_INPUT. Keep the same ID.” | Stop checking and keep job.json. Contact VidMage support with the task ID, and choose the faces with prepare() before your next task. |
“Task needs attention: FAILED. Keep the same ID.” | Check Task history for the billing status before you submit a corrected swap in a new job folder. |
“Image download: HTTP …” or “Connection interrupted.” | If the job has a task ID, call result () again with the same folder. If the connection dropped during photo preparation, rerun the demo with the same photos and folder. If it dropped during the paid submission and no task ID was saved, follow the recovery steps above. |
The wrong face changed | Open faces.html and pick the right number in a new job folder. A new swap is a new task, so it costs another credit. |
If you contact VidMage support, share the capability name (face-swap), the HTTP status, the errorType, your task ID, and the trace value from the saved error. Never share your API key or job.json itself.
Try it in VidMage
Open the tool and follow the steps above.

