Skip to content
Guides

How to Build a Face Swap App for Video by API

How to build a face swap app for video on an API: direct uploads, consent in the product, the edit and its webhook, storage, and pricing above cost.

Updated 7 min read

A face swap app for video needs three pieces of its own: a way for users to send a clip and their face photos, a record that every face was shared with consent, and a server that submits the edit and collects the result. The swap itself can come from an API. On Frameport, Frameport Replace 1 swaps the people in a clip, up to four at once, for the faces you send, and leaves the motion, the mouth movements, the background and the audio as they were; it costs $0.12 per second of clip at 768p, charged only when the edit succeeds.

Below: the parts of the app, uploads, consent, the edit and its webhook, privacy, and pricing that covers each swap.

What a face swap app needs

PartIts job
The client, web or mobilePicks the clip and the faces, asks for consent, shows the price, the progress and the result. Never holds the API key
Your bucket (S3, R2…)Keeps the uploads and the results, served through your own signed links
A media workerMeasures each clip with ffprobe and converts it to 24 fps H.264 when needed
Your serverUsers, credits, consent records, quotes, submits and the webhook
The APIThe swap: holds its price, renders it, and charges only a success

A swap moves through them in order: the user uploads the files to your bucket, the worker measures the clip, the user ticks the consent box and sees the price in your credits, your server reserves them and submits the edit, and a webhook brings the result back to store and show. There is no GPU or model to host.

Uploads and limits

Let files go from the browser straight to your bucket, so the browser never sees the API key: your server hands out a presigned upload per file, then gives the API a presigned download link when it submits. That route has no upload quota, and you decide how long files live. The other route, POST /v1/uploads from your server, suits low volume: a workspace may send 10 uploads a minute and keep 100 at a time, each for 24 hours.

app.py: setup, and uploads straight to your bucket
import hashlib
import hmac
import json
import os
import time
import uuid

import boto3
import requests
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, Response
from pydantic import BaseModel, Field

from myapp import current_user, db, notify  # your auth, your database, your emails or pushes

API = "https://frameport.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FRAMEPORT_API_KEY']}"}
BUCKET = "my-swap-app"
EDIT = requests.get(f"{API}/models/fp-replace-1", timeout=30).json()["edit"]  # the clip limits, read once
MAX_BYTES = {"video/mp4": EDIT["max_bytes"], "video/quicktime": EDIT["max_bytes"],
             "image/png": 10_000_000, "image/jpeg": 10_000_000, "image/webp": 10_000_000}

s3 = boto3.client("s3")
app = FastAPI()


@app.post("/uploads")
def sign_upload(content_type: str, request: Request):
    user = current_user(request)
    if content_type not in MAX_BYTES:
        raise HTTPException(400, "Send an MP4 or MOV clip, and PNG, JPEG or WebP faces.")
    key = f"uploads/{user.id}/{uuid.uuid4()}"
    db.add_upload(user.id, key, content_type)
    # The browser posts the file here; the bucket itself refuses a wrong type or size
    return s3.generate_presigned_post(BUCKET, key, ExpiresIn=600, Fields={"Content-Type": content_type},
                                      Conditions=[{"Content-Type": content_type},
                                                  ["content-length-range", 1, MAX_BYTES[content_type]]])

On a store without presigned POST, presign a PUT instead and check the size once the file lands. The worker then reads each clip from the bucket, measures it with ffprobe and converts it with ffmpeg when needed, like the prepare function of the face swap video Python script. Check the limits in the client too, so a user learns at once that a clip is too long:

  • The clip: 2 to 10 seconds, MP4 or MOV, up to 64 MB, at 24 frames per second. A longer scene goes in pieces.
  • The faces: one per person, up to four, PNG, JPEG or WebP, up to 10 MB each, sharp and turned toward the camera.
  • The targets: with two faces or more, one short description per face ("the man in the green cap"), up to 200 characters each.
  • The links you pass: https on a public host name, no credentials in the address, 2,048 characters at most. Presigned links qualify, though one carrying a long session token can run past that length.

The acceptable use policy covers everything your users make through your keys, and you answer for it. A video face swap app should build the rules into the flow:

  • Ask on every swap. A box left unticked until the user ticks it: "Every face I upload is mine, or I have permission from the person shown." The server refuses a swap without it.
  • Keep the record. Store who ticked it, when, and for which files, next to the job id, so a complaint can be traced.
  • Say what is never allowed, in your own terms of use: real, identifiable people without their consent, anything involving minors, impersonation, fraud and harassment. Everything made must be fiction.
  • Offer a way out. A report button on every shared result, a quick delete for the person who appears in it, and someone who reads the reports.
  • Label the output. Mark results as AI-edited in the caption or the file. Some places require it for altered media of people; check the rules where your users live.

When the API refuses a request on policy grounds, it answers 400 content_policy and charges nothing. Show your user a plain message, not a retry button.

The edit request and the webhook

When the user confirms, your server prices the clip with the seconds the worker measured, reserves that amount from the user's credits, saves the consent record, and submits the edit with a presigned link to each file:

app.py: start a swap
class Swap(BaseModel):
    clip: str                                                       # bucket keys from /uploads
    faces: list[str] = Field(min_length=1, max_length=EDIT["max_faces"])  # left to right
    targets: list[str] = []
    resolution: str = "768p"
    consent: bool = False


def link(key):
    """A presigned https link the API can download for the next 15 minutes."""
    return s3.generate_presigned_url("get_object", Params={"Bucket": BUCKET, "Key": key}, ExpiresIn=900)


@app.post("/swaps", status_code=202)
def start_swap(swap: Swap, request: Request):
    user = current_user(request)
    if not swap.consent:
        raise HTTPException(400, "Confirm that every face is yours or shared with permission.")
    if len(swap.faces) > 1 and len(swap.targets) != len(swap.faces):
        raise HTTPException(400, "Say who each face replaces, in the same order.")
    clip = db.upload(user.id, swap.clip)  # with the seconds the worker measured
    if clip is None or any(db.upload(user.id, face) is None for face in swap.faces):
        raise HTTPException(404, "No such upload.")

    quote = requests.post(f"{API}/generations/quote", headers=HEADERS, timeout=30, json={
        "model": "fp-replace-1", "seconds": clip.seconds, "resolution": swap.resolution}).json()
    if quote.get("error"):
        raise HTTPException(400, quote["error"]["message"])

    job = str(uuid.uuid4())
    if not db.reserve(user.id, job, quote["price_usd"]):
        raise HTTPException(402, "Not enough credits for this clip.")
    db.save_consent(user.id, job, [swap.clip, *swap.faces], time.time())

    body = {"model": "fp-replace-1", "video": link(swap.clip), "faces": [link(face) for face in swap.faces],
            "resolution": swap.resolution, **({"targets": swap.targets} if swap.targets else {})}
    res = requests.post(f"{API}/videos/edits", json=body, timeout=120,
                        headers={**HEADERS, "Idempotency-Key": f"swap-{job}"})
    gen = res.json()
    if gen.get("error"):
        db.release(user.id, job)  # refused before it ran: nothing was charged
        if res.status_code == 400:
            raise HTTPException(400, gen["error"]["message"])  # the clip, a face or the policy: the user can act
        raise HTTPException(503, "Swaps are busy right now. Try again in a minute.")  # your balance or limits
    db.attach(job, gen["id"])
    return {"job": job}

The submit waits while the API downloads the files and measures the clip, hence the long timeout. At that moment your balance must cover the quote's reserved_usd, the price of the longest clip the model takes, before the hold drops to your clip's price; a shortfall is a 402, shown to the user as a busy message because the balance is yours. The Idempotency-Key makes a retried submit return the first edit.

Add an endpoint under Webhooks in the dashboard, and the API calls it when each edit succeeds or fails, with the whole generation in data:

app.py: the webhook
SECRET = os.environ["WEBHOOK_SECRET"].encode()


def verified(raw, header):
    parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
    if "t" not in parts or "v1" not in parts or abs(time.time() - int(parts["t"])) > 300:
        return False
    expected = hmac.new(SECRET, parts["t"].encode() + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"])


def keep_result(job, gen):
    with requests.get(f"{API}/generations/{gen['id']}/content", headers=HEADERS, stream=True, timeout=300) as res:
        res.raise_for_status()
        s3.upload_fileobj(res.raw, BUCKET, f"results/{job.id}.mp4", ExtraArgs={"ContentType": "video/mp4"})
    db.settle(job.id, gen["cost_usd"])  # the exact charge
    notify(job.user_id, job.id)


@app.post("/hooks/generations", status_code=204)
async def generation_hook(request: Request, tasks: BackgroundTasks):
    raw = await request.body()
    if not verified(raw, request.headers.get("Frameport-Signature", "")):
        raise HTTPException(400, "Bad signature")
    event = json.loads(raw)
    job = db.claim_job(event["data"]["id"])  # pending → settling, once; None for a repeat or a stranger
    if job is not None:
        if event["type"] == "generation.succeeded":
            tasks.add_task(keep_result, job, event["data"])  # after the answer: copying can take a while
        else:
            db.release(job.user_id, job.id)
    return Response(status_code=204)

Answer within 10 seconds: a delivery without a 2xx is sent again after 1, 5 and 15 minutes. One endpoint receives every generation of the workspace, Studio runs included, which is why the handler ignores ids it does not know. Keep a slow sweep that reads any job still pending after a while, in case a delivery never arrives.

Privacy and the content filter

A private face swap app depends mostly on what you keep. On the API's side, an output's signed link opens for about an hour, a key from any other workspace gets 404 on your files, and files are not kept forever, which is why the webhook copies each result to your bucket. On yours, add a lifecycle rule that deletes uploads once their job ends, and let users delete their results.

Every workspace starts with its content filter on. It reads the note and every target of an edit, and a refusal is 400 content_filtered, nothing charged. Only an owner or admin who is 18 or older can turn it off, in Settings › Content filter in the dashboard; no API route changes it, and GET /v1/account tells your code where it stands with content_filter. With the filter off, Frameport Replace 1 renders without a content filter, but the acceptable use policy still applies to every face. The uncensored face swap video API guide covers that setup.

Pricing your app

What each swap costs you is set by the clip's seconds and the resolution, whatever the number of faces:

ClipAt 768pAt 1080p
3 s$0.36$0.75
5 s$0.60$1.25
10 s$1.20$2.50

Sell credits per second, with 1080p costing more, as it costs you more. Bill your users the way the API bills you, in whole seconds rounded up, so the two never drift apart. A sharper file can be an extra: Frameport Upscale 1 takes a finished swap by its file id and returns it at up to 2K, for $0.50 on a 10-second clip. On top of the API, count storage, bandwidth, payment fees, support, and any free swaps you give away, which cost you their full price. Failed swaps cost you nothing, so charge your users nothing for them either.

The API has no subscription: a balance topped up from $10 pays for every swap, and each one shows its exact price before it runs. Per-user budgets and the wider architecture are in how to build an AI video app, and every field of the edit is in the face swap video API guide and the edits reference. Budget it with face swap API pricing, or compare providers in the best face swap API for video.

FAQ

How does a face swap app work?

The user sends a clip and a photo of each face. The app's server passes both to an edit model, which replaces the people in the clip with those faces while keeping the motion, the background and the audio, then stores the result and shows it to the user.

How much does it cost to run a face swap app?

Per second of clip, per swap that succeeds: $0.12 a second at 768p and $0.25 at 1080p, whatever the number of faces. Add your own storage, bandwidth and payment costs.

Is there a free video face swap app?

Swaps that fail are free, and so are the account, the key and quotes; each successful swap is paid from a prepaid balance. To swap faces online without writing code, the Frameport Studio runs the same model, as shown in face swap video without code.

Can I build a private or unrestricted face swap app?

Yes, within the acceptable use policy. Keep files in your own bucket and delete them when their job ends; an owner or admin of the workspace can turn off its content filter in Settings. The rules on consent, minors and impersonation apply either way.

Do users need consent to swap someone's face?

Yes. A face must be the user's own, belong to someone who agreed to this use, or be a generated character. Ask on every swap, keep the record, and act on reports.

Can a face swap app handle long videos?

Yes, in pieces: cut the scene into clips of up to 10 seconds, swap each with the same faces and targets, and join the results with ffmpeg.

Guides5 min read

How to Swap Faces in a Video With Python

A face swap video Python script: check and convert the clip with ffmpeg, upload the faces, price and submit the edit, wait, then save the new clip.

Start building.

Your API key is free. Top up from $10 when you are ready.