The VidMage video face swap API puts a new face on one person in a clip and follows that person from the first frame to the last. Your server uploads the video and a photo of the new face, shows the user each person VidMage can track, sends one paid task for the person they pick, and saves the finished MP4.
You never mask or edit frames yourself. VidMage measures the clip and charges 1 credit per second, rounded up, so a 3-second clip costs 3 credits. To follow along, you need an active VidMage subscription, an API key, and Python 3.11 or newer.
Where the Python Calls Fit in Your App
Your app uses the three methods below from the VideoSwap class in video_swap.py. Each swap has its own private folder, so the next call can pick up where the previous one left off.
Your app calls | When | What comes back |
|---|---|---|
prepare(video, photo) | As soon as the user sends the clip and the face photo | A list of tracked faces, each with VidMage's index and a small preview image |
submit(index) | After the user clicks one of those previews | The task ID of the one paid swap |
result() | In a background worker, as often as it needs | The path to the finished MP4 on your server |
The pause between prepare() and submit() is what makes video face swap different from a plain generation request. A clip can show several people, so the code stops and lets a person decide who gets the new face before any credits go out.
Inside a web app, those three calls usually sit in two request handlers and one worker:
from video_swap import VideoSwap
# First server action, after receiving the two files.
swap = VideoSwap(job_folder)
choices = swap.prepare(target_video_path, portrait_path)
# Example return: [{"index": 0, "file": "track-0.jpg"}]
# Second server action, after the user clicks a thumbnail.
swap = VideoSwap(job_folder)
task_id = swap.submit(selected_track_index)
# A background worker can reopen this job in another process.
video_path = VideoSwap(job_folder).result()
The variable names belong to your app. Each call opens the job folder fresh, so one process or three can handle the same swap. The folder remembers the uploads, tracked faces, the idempotency key, and the task ID, so a crash or restart never costs you a second swap.
What the VidMage Video Face Swap API Needs From Your App
- An API key that lives on your server: Keys work only with an active subscription. Create one under API keys in the Developer Console, then load it from your secret store or the VIDMAGE_API_KEY environment variable.
- Credits for the length of the clip: The API spends the same balance as the VidMage website. VidMage currently accepts clips up to 300 seconds long.
- An MP4 target clip: This is the scene you keep. A face that stays clear, well lit, and mostly toward the camera swaps more cleanly than one in shadow, behind a hand or microphone, or turning fast. Billing runs per second, so a short cut of a long video is a cheap way to see how the footage behaves.
- A reference photo with one face: A sharp PNG or JPEG of the new face, ideally front-facing in even light. This example lets VidMage find the only face in the photo, so crop a group shot down to one person before you use it.
- Python 3.11 or newer: The code checks file contents with hashlib.file_digest, which first shipped in Python 3.11. It also uses the Requests and Pillow libraries.
- The rights to both files: Only use footage and faces you own or have permission to use.
If you'd like to look at the request fields before you write any code, the Playground on the AI Video Face Swap API page lists all four of them. Its Submit button runs a real task, so it spends credits too.
Run Your First Video Face Swap With the VidMage API
Step 1: Make a project folder and save the following code in it as video_swap.py. The VideoSwap class is the part your app imports. The block at the very bottom, under if __name__ == "__main__":, turns the file into a small local demo, with a gallery page and a Terminal prompt standing in for your app's face picker.
"""One private job folder per swap. Serialize access to each folder in your app."""
import getpass
import hashlib
import json
import os
import sys
import time
import uuid
from pathlib import Path
from tempfile import NamedTemporaryFile
import requests
from PIL import Image
API = "https://vidmage.ai/api/v1"
TOOL = "video-face-swap"
def request(method, url, **kwargs):
if not isinstance(url, str) or not url.startswith("https://"):
raise ValueError("Missing HTTPS URL. Check the saved job.")
try:
return requests.request(method, url, timeout=(10, 60), **kwargs)
except requests.RequestException:
raise RuntimeError("Connection interrupted. Keep this job and check its last step.") from None
def download(url, path):
partial = path.with_suffix(".part")
try:
with request("GET", url, stream=True) as response:
if response.status_code != 200:
raise RuntimeError(f"Media download returned HTTP {response.status_code}.")
with partial.open("wb") as out:
for block in response.iter_content(256 * 1024):
out.write(block)
if path.suffix == ".mp4":
with partial.open("rb") as stream:
if stream.read(8)[4:] != b"ftyp":
raise ValueError("Expected an MP4 file. Keep the task ID.")
else:
with Image.open(partial) as im:
im.load()
im.thumbnail((320, 320))
im.convert("RGB").save(partial, format="JPEG")
partial.replace(path)
except requests.RequestException:
raise RuntimeError("Download interrupted. Resume with the same job.") from None
finally:
partial.unlink(missing_ok=True)
class VideoSwap:
def __init__(self, folder):
self.folder = Path(folder)
self.folder.mkdir(mode=0o700, parents=True, exist_ok=True)
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, **fields):
self.job.update(fields)
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, key=None):
headers = {"Authorization": f"Bearer {self.key}"}
if key:
headers["Idempotency-Key"] = key
reply = request("POST", API + route, json=body, headers=headers, allow_redirects=False)
try:
data = reply.json()
except ValueError:
data = {}
if not isinstance(data, dict):
data = {}
if not reply.ok or data.get("success") is not True or reply.is_redirect:
self.save(error={"route": route, "http": reply.status_code, "response": data,
"trace": reply.headers.get("X-Request-Id"),
"retry_after": reply.headers.get("Retry-After")})
raise RuntimeError(f"{route}: HTTP {reply.status_code}, {data.get('errorType')}. See private job.")
return data
def upload(self, field, path, mime):
ticket = self.api("/files/upload", {"capability": TOOL, "parameter": field, "fileName": path.name,
"contentType": mime, "fileSize": path.stat().st_size})
with path.open("rb") as stream:
put = request("PUT", ticket["uploadUrl"], data=stream, headers=ticket["headers"], allow_redirects=False)
if not 200 <= put.status_code < 300:
raise RuntimeError(f"Storage returned HTTP {put.status_code}. Stop before submitting.")
self.save(**{field: ticket["fileUrl"]})
print(f"Uploaded {path.name} for {field}.")
def prepare(self, video, portrait):
"""Return private preview filenames with VidMage's tracked-face indexes."""
video, portrait = Path(video), Path(portrait)
with video.open("rb") as stream:
if stream.read(8)[4:] != b"ftyp":
raise ValueError("This example takes an MP4 clip.")
with Image.open(portrait, formats=("JPEG", "PNG")) as im:
mime = Image.MIME[im.format]
im.verify()
hashes = []
for path in (video, portrait):
with path.open("rb") as stream:
hashes.append(hashlib.file_digest(stream, "sha256").hexdigest())
if self.job.get("inputs", hashes) != hashes:
raise ValueError("Use a different job folder for different input files.")
self.save(inputs=hashes)
for field, path, kind in (("targetVideoUrl", video, "video/mp4"), ("referenceFaceImageUrl", portrait, mime)):
if field not in self.job:
self.upload(field, path, kind)
faces = self.job.get("faces")
if faces and all((self.folder / f["file"]).is_file() for f in faces):
return faces
lookup = {"targetUrl": self.job["targetVideoUrl"]}
if self.job.get("analysis_id"):
lookup = {"analysisId": self.job["analysis_id"]}
deadline = time.monotonic() + 300
while time.monotonic() < deadline:
reply = self.api("/face-analysis", {"capability": TOOL, **lookup})
self.save(analysis_id=reply["analysisId"])
if reply["status"] != "RUNNING":
break
lookup = {"analysisId": reply["analysisId"]}
time.sleep(5)
else:
raise TimeoutError("Resume preparation with the same files and job.")
if reply["status"] != "COMPLETED" or not reply.get("faces"):
raise RuntimeError("No usable tracked faces. The swap has not been submitted.")
faces = []
for face in reply["faces"]:
index = face["index"]
if type(index) is not int or index < 0 or any(f["index"] == index for f in faces):
raise ValueError("Invalid tracked-face index from analysis.")
name = f"track-{index}.jpg"
download(face["previewUrl"], self.folder / name)
faces.append({"index": index, "file": name})
self.save(faces=faces)
return faces
def submit(self, index):
if type(index) is not int or index not in [f["index"] for f in self.job.get("faces", [])]:
raise ValueError("Choose a tracked-face index shown for this clip.")
if self.job.get("selected", index) != index:
raise ValueError("This job already records a different face choice.")
if self.job.get("task_id"):
return self.job["task_id"]
if self.job.get("idempotency_key"):
raise RuntimeError("Recover the original submission before trying again.")
body = {field: self.job[field] for field in ("targetVideoUrl", "referenceFaceImageUrl")}
body["targetFaceIndex"] = index # Reference portrait contains exactly one face.
self.save(selected=index, body=body, idempotency_key=str(uuid.uuid4()))
reply = self.api("/video-face-swap/submit", body, self.job["idempotency_key"])
task_id = reply.get("taskId") or (reply.get("data") or {}).get("taskId")
self.save(task_id=task_id, submit_reply=reply)
if not task_id:
raise RuntimeError("No task ID returned. Recover the original submission.")
return task_id
def result(self, max_wait=300):
task_id = self.job.get("task_id")
if not task_id:
raise ValueError("Recover the task ID before requesting the result.")
path = self.folder / "swapped.mp4"
if self.job.get("downloaded") and path.is_file():
return path
deadline = time.monotonic() + max_wait
while time.monotonic() < deadline:
reply = self.api("/video-face-swap/query", {"taskId": task_id})
self.save(query_reply=reply)
data = reply.get("data") or {}
status = str(data.get("status") or reply.get("status") or "").upper()
print(f"Task {task_id}: {status}")
if status in ("COMPLETED", "SUCCESS", "SUCCEEDED"):
download(data.get("videoUrl") or reply.get("videoUrl") or reply.get("result"), path)
self.save(downloaded=True)
return path
if not status or status in ("FAILED", "ERROR", "NEEDS_INPUT"):
raise RuntimeError(f"Check the saved task and recovery instructions ({status or 'missing status'}).")
time.sleep(5)
raise TimeoutError("Local wait ended. Call result() again for this same job.")
if __name__ == "__main__":
if len(sys.argv) != 4:
sys.exit("Usage: python video_swap.py TARGET.mp4 PORTRAIT.png JOB_FOLDER")
if not os.environ.get("VIDMAGE_API_KEY"):
os.environ["VIDMAGE_API_KEY"] = getpass.getpass("VidMage API key (hidden): ")
swap = VideoSwap(sys.argv[3])
if not swap.job.get("task_id"):
if swap.job.get("idempotency_key"):
sys.exit("Recover the original submission before trying again.")
choices = swap.prepare(sys.argv[1], sys.argv[2])
gallery = swap.folder / "tracks.html"
gallery.write_text("<title>Choose a tracked face</title><h1>Choose a tracked face</h1>" + "".join(
f'<figure><img src="{f["file"]}" width="160"><figcaption>Track {f["index"]}</figcaption></figure>'
for f in choices), encoding="utf-8")
print("Open the local gallery:", gallery)
picked = int(input("Enter the track number to submit one paid swap: "))
print("Saved task ID:", swap.submit(picked))
print("Saved video:", swap.result())
Next to it, save a file called requirements.txt with these two lines:
requests>=2.32.3,<3
Pillow>=11,<14
Step 2: Copy your clip and reference photo into the project folder, then open Terminal there. In the last command below, replace target.mp4 and reference.png with your filenames. Put quotes around any filename that contains spaces.
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python video_swap.py target.mp4 reference.png private/cafe-swap
On Windows, type .venv\Scripts\python.exe wherever you see .venv/bin/python.
- The first argument is the clip
- The second is the face photo
- The third, private/cafe-swap, names the job folder for this one swap.
When VIDMAGE_API_KEY is not set, the demo asks for your key with a hidden prompt, so nothing appears on screen as you paste.
The sample files are a 3-second café clip of a man sitting at a table and a park photo of a woman walking two dogs. She's the only person in the photo, so it works as a reference without any cropping.
The script uploads the clip first and the photo second. Each upload takes two requests
- It asks VidMage for an upload slot for a specific request field.
- The other sends the file to the temporary storage link VidMage hands back.
A finished upload only works in the field it was made for, so the clip goes up as targetVideoUrl and the photo as referenceFaceImageUrl. Terminal confirms each one with a line such as Uploaded target.mp4 for targetVideoUrl.

Step 3: Open the tracks.html page whose path the script prints, then choose the person to replace. While you wait, the code asks VidMage to scan the clip, checks the same scan every 5 seconds, and saves a small preview of each person VidMage can follow. The café clip has one person, so the page shows a single preview labeled Track 0.

Go back to Terminal and type the track number at the prompt that reads Enter the track number to submit one paid swap: Check the preview before you press Enter. Entering a valid track number submits the paid swap. In this run, VidMage recorded the charge while the task was running. The code only accepts a number that appears on the page, and your choice covers the whole clip.

Step 4: Let the script follow the task to the end. Before it sends anything, submit() writes the request body and a brand new idempotency key to the job folder. Then it sends one paid request and prints the task ID VidMage returns. From there, result() asks about that same task every 5 seconds and prints its status each time, such as RUNNING, until VidMage reports COMPLETED.
NOTE: Don't read the first reply as a free swap. It says PENDING with creditsConsumed: 0 and usageDeferred: true, which means VidMage records the charge while the task runs. Every check asks about the task you already sent, so result() can run as often as you need without starting a second one.

Step 5: Once the task completes, the code downloads the video from data.videoUrl and checks its file header before saving it. The demo then prints the path: private/cafe-swap/swapped.mp4. The download link doesn't need your API key, so the code leaves it out of that request.

As you can see in the image above, the table, the coffee cup, the shirt, and the café behind him stay exactly as they were. Only the face changes, and the new face holds at the start, middle, and end of the clip. The output can run a hair shorter than the source.

In your app, result() returns a pathlib.Path on your server. Stream that file to the signed-in user, or copy it to your own storage and send them the link. To see the charge on your account, open Task history in the Developer Console.
How Your App Presents Face Choices and Sends the Index
The face picker is the one piece of UI a video swap needs. The prepare() gives your server a short list, and for the café clip it holds a single entry, like this:
[{"index": 0, "file": "track-0.jpg"}]
- Show one thumbnail per tracked face: For this clip, the app displays track-0.jpg and gives the thumbnail the value 0. Keep each preview paired with its VidMage index, even if you change the display order. Only the user who owns the job should be able to open its previews.
- Send the index the user picked: In an offline test, the two thumbnails had indexes 8 and 2. Clicking the second one sent 2 along with the app’s job ID. The server converted the value to an integer and called submit(2). The code checked that the clip contained track 2 before sending targetFaceIndex: 2 to VidMage.
- Include the target index even for a single face: The café example sent targetFaceIndex: 0. If VidMage finds several tracked faces and the request leaves out that field, the task can stop with NEEDS_INPUT.
- Handle the reference photo separately: This example uses a portrait with one face, so it omits referenceFaceIndex. If you use a group photo, crop it to the person you want or supply that person’s index from the reference photo. The track number from the video applies only to the video.
What VidMage Receives at Each Stage
Each Python method maps to a small set of VidMage requests. This table shows what the code sends and the details worth knowing at each stage.
Request | What the code sends | Worth knowing |
|---|---|---|
POST /api/v1/files/upload, once per file | The video-face-swap capability, the field name, the file name, the real content type, and the exact byte count | VidMage returns a temporary uploadUrl, a set of storage headers, and a fileUrl. The code PUTs the file with only those headers and never sends your API key to storage. See file uploads. |
POST /api/v1/face-analysis | The capability and the clip's fileUrl as targetUrl, then the returned analysisId on every later check | The scan is free. The analysisId names the scan, and it isn't a task ID. |
POST /api/v1/video-face-swap/submit | targetVideoUrl, referenceFaceImageUrl, and targetFaceIndex, with your Bearer key and an Idempotency-Key header | This is the paid call. The code saves the body and key before it sends and saves the taskId the moment it arrives. |
POST /api/v1/video-face-swap/query | The saved taskId | The code reads the status from data.status or the top level of the reply. By default, result() checks progress for about five minutes before returning control to your app. If that wait expires, call result() again to follow the same task. |
VidMage works out the price from the uploaded video itself, so don't add a videoDuration field to the upload or the submit request. The video face swap docs list the current rate of 1 credit per second, rounded up to whole credits. For example, a 3.4-second clip costs 4 credits.
Picking Up an Interrupted Swap
The job folder is what stops a dropped connection from turning into a second charge. What you do next depends on where the swap stopped.
- Before the paid request: If an upload or the face scan stopped, run prepare() again with the same files and the same folder. Nothing has been billed yet. A file that never reached storage has no saved fileUrl, so the code uploads it again, and a scan that outran the 5-minute local wait picks up from its saved analysisId. If VidMage finds no usable faces, the code stops without submitting. Pick a clearer clip and use a new folder, because a folder only accepts the files it started with.
- After the task ID was saved: Call VideoSwap(job_folder).result() again. It checks the same task and never submits a new one. That covers a local wait that ran out, a connection that dropped while checking, and a download that failed partway. If the MP4 is already saved, result() returns it without calling VidMage at all.
- During the paid request, with no task ID saved: The request may have reached VidMage, so the code refuses to send it again and stops with "Recover the original submission before trying again." Keep job.json, with its key and body. Look for the matching task in Task history, or ask for your recent tasks with GET https://vidmage.ai/api/v1/tasks/recent?limit=10 and your API key. An empty list doesn't prove the task never started, so check the recovery value in the saved error or contact support. Once you've confirmed the exact task, a trusted operator on your server can attach it to the job:
# Only after identifying this job’s exact accepted task in VidMage.
swap = VideoSwap(job_folder)
swap.save(task_id=confirmed_task_id)
video_path = swap.result()
- A clear rejection at submit: A 401, 402, or 403 means a key, subscription, or credit problem. Fix the account issue and keep the original job folder. If you find a matching task, resume it with its task ID. If the outcome is unclear, follow the recovery instructions in the saved response or contact VidMage before starting a new swap.
- An expired upload: A confirmed UPLOAD_EXPIRED means the media links went stale.If VidMage already accepted the swap, resume it with its task ID. If you’ve confirmed that the submission was rejected because an upload expired, use a new job folder to upload the files again.
- A rate limit while checking: On HTTP 429, the code saves VidMage's Retry-After value in job.json and stops. Wait that long, then call result() again.
- NEEDS_INPUT, FAILED, or no status at all: The code stops and keeps the task ID. Check the task's billing in Task history and follow VidMage's recovery instructions before you send anything new. If a reply reports an unknown billing or submission outcome, don't resubmit.
VidMage Video Face Swap API Quick Facts
Item | VidMage details |
|---|---|
Endpoints | POST /api/v1/video-face-swap/submit and POST /api/v1/video-face-swap/query |
Required fields | targetVideoUrl, from a VidMage upload, and referenceFaceImageUrl |
Optional fields | targetFaceIndex and referenceFaceIndex, whole numbers that start at 0 |
Cost | 1 credit per second of video, rounded up. Face analysis is free. |
Clip length | Up to 300 seconds, measured by VidMage |
Processing time | Not published. Longer clips can take longer. |
Result | A link in data.videoUrl, which the example saves as swapped.mp4 |
Faces per task | One tracked person. VidMage offers a separate multi face swap API for up to four faces in one task. |
Sample swap | A 3-second 720 × 900 clip with one track, one submission, 3 credits, and a 2.96-second MP4 |
Try it in VidMage
Open the tool and follow the steps above.

