Skip to content
Guides

AI Video Generation API in Python: prompt to MP4

Use an AI video generation API from Python: quote the price, submit a clip, poll it or take a webhook, then download the MP4. Runnable code, real API.

Updated 5 min read

To generate a video from Python, you send a prompt to a video generation API, wait for the job to finish, then download the file. With Frameport that is one requests call to submit, a short loop or a webhook to wait, and one call to download, for any of the 13 video models on the same key.

This guide builds that script step by step: pick a model, quote the price, submit, poll or take a webhook, download, and handle the errors that matter. Each step is a function you can lift into your own code.

What you need

  • Python 3 and the requests package (pip install requests). The webhook part also uses Flask.
  • An API key: create an account, add funds under Billing (from $10), then create a key under API keys. It starts with fp_live_ and is shown once.
  • The key in an environment variable, so it never lands in your code.
export FRAMEPORT_API_KEY="fp_live_..."
pip install requests

All the code below shares these two lines:

import os
import requests

API = "https://frameport.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FRAMEPORT_API_KEY']}"}

1. Pick a model

GET /v1/models lists every model on sale with its prices and options, and needs no key. Read type and mode to know which endpoint a model takes, pricing for its price and options for the values a request may use.

List the video models
models = requests.get(f"{API}/models").json()["data"]

for model in models:
    if model["type"] == "video" and model["mode"] == "generate":
        lowest = min(model["pricing"]["per_second"].values())
        lengths = model["options"].get("durations")
        print(f"{model['id']:<22} from {lowest}/s  {lengths}")

This guide uses Seedance 2.5: clips of 4 to 30 seconds, from $0.12 per second, with sound. For the lowest price per second, Frameport Motion 1 starts at $0.02 per second at 480p and takes the same request. Read prices from the API rather than typing them into your code: they can change, and the API always has the current ones.

2. Quote the price

POST /v1/generations/quote takes the body you are about to send and answers with its price, what it would hold, and whether your balance covers it. Nothing is held or started, and quotes do not count against your rate limit.

Quote a request
def quote(body: dict) -> dict:
    res = requests.post(f"{API}/generations/quote", headers=HEADERS, json=body)
    res.raise_for_status()
    return res.json()


body = {"model": "seedance-2-5", "duration": 5, "resolution": "720p"}
q = quote(body)
print(q["breakdown"], "covered:", q["enough_balance"])
200 OK
{
  "object": "quote",
  "model": "seedance-2-5",
  "type": "video",
  "mode": "generate",
  "price_usd": 1.35,
  "reserved_usd": 1.35,
  "breakdown": "5 s at 720p × $0.27/s",
  "enough_balance": true
}

For code that builds requests from user input, add max_cost_usd to the body itself: a request that would cost more is refused with 400 max_cost_exceeded before anything is held. The quotes reference has the details.

3. Submit the clip

POST /v1/videos/generations holds the price on your balance and answers at once with 202 Accepted: the generation, its id and reserved_usd. Send an Idempotency-Key with it. If your script times out and sends the same request again, the API returns the first generation instead of starting, and charging, a second one.

Submit
import uuid


def submit(body: dict, key: str = "") -> dict:
    res = requests.post(
        f"{API}/videos/generations",
        headers={**HEADERS, "Idempotency-Key": key or str(uuid.uuid4())},
        json=body,
    )
    gen = res.json()
    if gen.get("error"):
        raise RuntimeError(f"{gen['error']['code']}: {gen['error']['message']}")
    return gen


gen = submit({
    **body,
    "prompt": "A paper boat drifts down a rain-soaked street at dusk, low tracking shot",
    "aspect_ratio": "16:9",
})
print(gen["id"], gen["status"], "held:", gen["reserved_usd"])

Keep the key with your own job record (an order id works): the same key with the same body is safe to send again for 24 hours. See idempotency for the cases it covers.

4. Poll until it settles

A generation moves from queued to running, then to succeeded or failed. Read it every few seconds; reads are not counted against your limits, but a tight loop helps no one.

Wait for the result
import time


def wait(gen: dict, every: float = 4, timeout: float = 1800) -> dict:
    deadline = time.monotonic() + timeout
    while gen["status"] in ("queued", "running"):
        if time.monotonic() > deadline:
            raise TimeoutError(f"{gen['id']} is still {gen['status']}")
        time.sleep(every)
        gen = requests.get(f"{API}/videos/generations/{gen['id']}", headers=HEADERS).json()
    return gen


gen = wait(gen)
if gen["status"] == "failed":
    # Nothing was charged: the hold went back to the balance
    raise SystemExit(gen["error"]["message"])
print("charged:", gen["cost_usd"])

On success, cost_usd is what was charged and each output carries a url. On failure, error says why and cost_usd is 0.

Or take a webhook

A service that runs many clips should not poll each one. Add an endpoint under Webhooks in the dashboard and pick generation.succeeded, generation.failed or both. Each delivery is a POST with the generation as GET returns it, signed with your endpoint's secret in the Frameport-Signature header.

A Flask receiver
import hashlib
import hmac
import json
import time

from flask import Flask, request

app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SECRET"]  # whsec_..., shown once when you add the endpoint


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


@app.post("/hooks/video")
def video_done():
    if not verify(request.get_data(), request.headers.get("Frameport-Signature", "")):
        return "", 400
    event = json.loads(request.get_data())
    gen = event["data"]
    print(event["type"], gen["id"], gen["status"])  # queue the download, answer fast
    return "", 204

Answer with a 2xx within 10 seconds and do the work afterwards. A delivery that fails is sent again after 1, 5 and 15 minutes, with the same id each time, so a receiver can skip one it has already handled. The webhooks reference covers retries and signatures.

The AI video API webhooks guide goes further into receiving and checking them.

5. Download the MP4

outputs[0].url is a signed link that opens without a key for about an hour. Stream it to disk instead of loading the whole clip into memory. When a link has expired, read the generation again for a fresh one.

Download
def download(gen: dict, path: str) -> None:
    with requests.get(gen["outputs"][0]["url"], stream=True) as res:
        res.raise_for_status()
        with open(path, "wb") as file:
            for chunk in res.iter_content(chunk_size=1 << 20):
                file.write(chunk)


download(gen, "boat.mp4")

With your key, GET /v1/generations/{id}/content streams the same file from the generation's id. Files are not kept forever: copy the ones you keep to your own storage (files).

Handle the errors that matter

Every error has the same shape, with a stable code to branch on and a request_id to send support. A request refused before it starts holds nothing.

StatusCodeWhat to do
400invalid_requestA field is off the model's grid: the message names it and lists what the model takes.
400max_cost_exceededThe request costs more than your max_cost_usd.
402insufficient_balanceAdd funds, or quote a shorter or lower-resolution clip.
429rate_limitedPast 60 requests a minute for the workspace: wait for Retry-After.
429concurrency_limit20 generations already running: submit the next one when one finishes.
503model_unavailableThe model is down for now: retry later, with the same Idempotency-Key.

A generation that fails after it was accepted is not an HTTP error: it shows status: "failed" with its reason, and you can submit it again. The full list is in the errors reference.

The whole script

The functions above, end to end:

make_clip.py
body = {
    "model": "seedance-2-5",
    "prompt": "A paper boat drifts down a rain-soaked street at dusk, low tracking shot",
    "duration": 5,
    "resolution": "720p",
    "aspect_ratio": "16:9",
}

q = quote(body)
if not q["enough_balance"]:
    raise SystemExit(f"Add funds first: this clip holds {q['reserved_usd']}")

gen = wait(submit(body))
if gen["status"] == "failed":
    raise SystemExit(gen["error"]["message"])

download(gen, "boat.mp4")
print("saved boat.mp4, charged", gen["cost_usd"])

The same request works for every video model: change model, then the options its page lists. The Seedance 2.5 API guide goes through that model's options and prices one by one.

Writing JavaScript instead? The same flow is in AI video generation API in Node.js. To hand the finished clip to people in a chat, see the Telegram bot AI video guide. To generate a typed client from the spec instead of writing requests by hand, see OpenAPI client generators.

FAQ

Do I need an SDK to call the API from Python?

No. It is HTTPS and JSON: requests, httpx or the standard library all work. Send the key as a Bearer token and read the JSON back.

How do I avoid paying twice when a request times out?

Send an Idempotency-Key header with each submit. The same key with the same body returns the first generation for 24 hours, so a retry never starts or charges a second clip.

What does a failed video cost?

Nothing. The price is held when you submit and charged only on success; when a clip fails, the hold goes back to your balance and cost_usd is 0.

How many videos can I generate at once?

Up to 20 generations can run at once in a workspace, and 60 requests that start work are accepted a minute. Queue the rest on your side and submit as clips finish.

Can I see the clips my script made?

Yes. GET /v1/generations lists them newest first, filtered by status, type or model, and the dashboard shows the same list. You can also open the same model in the Studio to try a prompt by hand before you script it.

Start building.

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