{"slug": "how-to-generate-ai-video-from-code-veo-3-1-kling-and-seedance-with-one-api", "title": "How to generate AI video from code: Veo 3.1, Kling and Seedance with one API", "summary": "Alex, who runs the MartLLM API, published a complete Python client pattern for generating AI video from code, covering a price/start/poll/download job flow and demonstrating the same code against Google's Veo 3.1, Kuaishou's Kling and ByteDance's Seedance. The writeup emphasizes a validate step that quotes cost before any charge, idempotency keys to prevent double billing on retries, and polling every 5-10 seconds until a job reaches a final status.", "body_md": "*Disclosure: I'm Alex, and I run MartLLM, the API used in the examples. The job pattern (price, start, poll, download) is the same on most video APIs; swap the URLs and field names for your provider's.*\n\nText models answer in a second or two. Video models don't. A five-second clip takes a minute or more, so every serious video API treats it as a **job**: you start it, you check on it, and you download the file when it's done. If you write video code like chat code (one blocking request, wait for the bytes), you get timeouts, double charges on retries, and no idea what a clip will cost until the bill arrives.\n\nThis post builds a small, complete Python client for that flow, then runs the same code against three model families: Google's Veo 3.1, Kuaishou's Kling and ByteDance's Seedance. Prices are what the public catalog listed on 2026-11-28.\n\nThe endpoints, all under `https://api.martllm.com` with `Authorization: Bearer <key>`:\n\n| Step | Call | \n|---|---|\n| Price | `POST /v1/video/generations` with`\"validate\": true` | \n| Start | `POST /v1/video/generations` (HTTP 202, returns a job id) | \n| Poll | `GET /v1/video/generations/<job id>` (202 while running, 200 when it ends) | \n| Download | `GET /v1/media/artifacts/<job id>/0` | \n| Stop | `DELETE /v1/video/generations/<job id>` | \n\nThe full reference, with every field, is in the [video section of the media docs](https://martllm.com/docs/media).\n\nAdd `\"validate\": true` to the exact request you're about to send. It's checked as if it were real (model, length, resolution, source picture), nothing is made, nothing is charged, and you get back the listed cost and the most the job can be billed:\n\n```\ncurl https://api.martllm.com/v1/video/generations \\\n  -H \"Authorization: Bearer $MARTLLM_API_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"model\": \"google/veo-3.1-lite\",\n       \"prompt\": \"a paper boat drifting down a rain-soaked street at dusk, neon reflections\",\n       \"duration_seconds\": 8, \"resolution\": \"720p\", \"aspect_ratio\": \"16:9\", \"audio\": true,\n       \"validate\": true}'\n{ \"object\": \"quote\", \"model\": \"google/veo-3.1-lite\", \"kind\": \"video\",\n  \"valid\": true, \"cost_usd\": 0.34, \"unit\": \"second\", \"units\": 8,\n  \"max_cost_usd\": <the most this job can be billed> }\n```\n\nThe extra step is worth it because an invalid request fails here, before money moves. Each model only makes certain lengths, resolutions and shapes. Ask Veo 3.1 Lite for a 10-second clip and the error lists the lengths it does make (4, 6 or 8). A Seedance image-to-video model sent no picture gets `400 image_required`.\n\n```\ncurl https://api.martllm.com/v1/video/generations \\\n  -H \"Authorization: Bearer $MARTLLM_API_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Idempotency-Key: $(uuidgen)\" \\\n  -d '{\"model\": \"google/veo-3.1-lite\", \"prompt\": \"...\", \"duration_seconds\": 8,\n       \"resolution\": \"720p\", \"aspect_ratio\": \"16:9\", \"audio\": true}'\n```\n\nYou get HTTP 202 with a job:\n\n```\n{ \"id\": \"6f1c...\", \"object\": \"media.job\", \"kind\": \"video\", \"status\": \"queued\",\n  \"estimated_cost_usd\": 0.34, \"max_cost_usd\": <held while it runs>,\n  \"poll_url\": \"/v1/video/generations/6f1c...\", \"cancel_url\": \"/v1/video/generations/6f1c...\" }\n```\n\nTwo details matter in production:\n\n`Idempotency-Key`` max_cost_usd`\nA job has six statuses: `queued`, `running`, `succeeded`, `failed`, `canceled`, `expired`. The last four are final. `failed`, `canceled` and `expired` cost nothing. Poll every 5-10 seconds. Faster doesn't make the video arrive sooner.\n\n```\ncurl -H \"Authorization: Bearer $MARTLLM_API_KEY\" \\\n  https://api.martllm.com/v1/video/generations/<job id>\n{ \"id\": \"6f1c...\", \"status\": \"succeeded\",\n  \"results\": [{ \"artifact_index\": 0, \"url\": \"https://api.martllm.com/v1/media/artifacts/6f1c.../0\",\n                \"content_type\": \"video/mp4\", \"duration_seconds\": 8 }],\n  \"usage\": { \"cost_usd\": 0.34 } }\n```\n\nOne edge case catches people out. The exact charge comes in a little after the file is ready, usually within 30 seconds. Until then a succeeded job shows `\"usage\": {\"cost_usd\": null, \"cost_pending\": true}`. Don't treat `null` as free. Read the job again later.\n\n```\ncurl -L -o veo.mp4 -H \"Authorization: Bearer $MARTLLM_API_KEY\" \\\n  https://api.martllm.com/v1/media/artifacts/<job id>/0\n```\n\nThe artifact URL needs the same `Authorization` header. It isn't a public link, so don't paste it into an `<img>` or `<video>` tag. Download it and serve it from your own storage.\n\n`pip install requests`, set `MARTLLM_API_KEY`, and this runs as is:\n\n``` python\nimport os\nimport sys\nimport time\nimport uuid\n\nimport requests\n\nAPI = \"https://api.martllm.com\"\nHEADERS = {\"Authorization\": f\"Bearer {os.environ['MARTLLM_API_KEY']}\"}\nDONE = {\"succeeded\", \"failed\", \"canceled\", \"expired\"}\n\ndef quote(body: dict) -> dict:\n    \"\"\"Same request with \"validate\": true: checked, priced, nothing made, nothing charged.\"\"\"\n    r = requests.post(f\"{API}/v1/video/generations\", headers=HEADERS,\n                      json={**body, \"validate\": True}, timeout=60)\n    r.raise_for_status()\n    return r.json()\n\ndef start(body: dict) -> dict:\n    \"\"\"Start the job. The Idempotency-Key makes a retried POST start one job, not two.\"\"\"\n    r = requests.post(f\"{API}/v1/video/generations\",\n                      headers={**HEADERS, \"Idempotency-Key\": str(uuid.uuid4())},\n                      json=body, timeout=60)\n    r.raise_for_status()\n    return r.json()  # HTTP 202: {\"id\", \"status\": \"queued\", \"max_cost_usd\", \"poll_url\", ...}\n\ndef wait(job_id: str, every: float = 7, give_up_after: float = 20 * 60) -> dict:\n    \"\"\"Poll every 5-10 s until the job ends (202 while running, 200 once it ends).\"\"\"\n    deadline = time.time() + give_up_after\n    while time.time() < deadline:\n        r = requests.get(f\"{API}/v1/video/generations/{job_id}\", headers=HEADERS, timeout=60)\n        r.raise_for_status()\n        job = r.json()\n        if job[\"status\"] in DONE:\n            return job\n        print(f\"  {job['status']} {job.get('progress') or ''}\", file=sys.stderr)\n        time.sleep(every)\n    raise TimeoutError(f\"job {job_id} still running after {give_up_after}s\")\n\ndef download(url: str, path: str) -> None:\n    with requests.get(url, headers=HEADERS, stream=True, timeout=300) as r:\n        r.raise_for_status()\n        with open(path, \"wb\") as f:\n            for chunk in r.iter_content(1 << 20):\n                f.write(chunk)\n\ndef make_video(body: dict, path: str) -> dict:\n    q = quote(body)\n    print(f\"{body['model']}: listed ${q['cost_usd']}, at most ${q['max_cost_usd']}\")\n    job = start(body)\n    job = wait(job[\"id\"])\n    if job[\"status\"] != \"succeeded\":\n        err = job.get(\"error\") or {}\n        raise RuntimeError(f\"{job['status']}: {err.get('message')} (retryable={err.get('retryable')})\")\n    download(job[\"results\"][0][\"url\"], path)\n    usage = job.get(\"usage\") or {}\n    if usage.get(\"cost_pending\"):\n        # The exact charge lands a little after the file is ready; GET the job again later.\n        print(\"saved\", path, \"- charge still pending\")\n    else:\n        print(\"saved\", path, \"- billed $\", usage.get(\"cost_usd\"))\n    return job\n\nif __name__ == \"__main__\":\n    make_video({\n        \"model\": \"google/veo-3.1-lite\",\n        \"prompt\": \"a paper boat drifting down a rain-soaked street at dusk, neon reflections\",\n        \"duration_seconds\": 8,\n        \"resolution\": \"720p\",\n        \"aspect_ratio\": \"16:9\",\n        \"audio\": True,\n    }, \"veo.mp4\")\n```\n\nOn a `failed` job, `error.retryable` tells you whether sending it again can work. A content refusal won't. A busy moment usually will.\n\nOnly the body changes. These are real model ids from the catalog, with the price each listed on 2026-11-28:\n\n**Veo 3.1 Lite, text to video, 8 s, 720p with sound.** $0.0425 per second, so **$0.34** a clip. It makes 4, 6 or 8 second clips at 720p or 1080p, 16:9 or 9:16. ([model page](https://martllm.com/models/google/veo-3.1-lite))\n\n```\n{\"model\": \"google/veo-3.1-lite\", \"prompt\": \"...\", \"duration_seconds\": 8,\n \"resolution\": \"720p\", \"audio\": True}\n```\n\n**Kling V3 Standard, text to video, 5 s.** $0.0732 per second, about **$0.37** for 5 seconds. Lengths 3 to 15 s. The image-to-video version, `kling/kling-v3-standard-image-to-video`, takes `image_url` and the same per-second price.\n\n```\n{\"model\": \"kling/kling-v3-standard-text-to-video\", \"prompt\": \"...\", \"duration_seconds\": 5}\n```\n\n**Seedance 2.0 Mini, image to video, 5 s at 480p.** $0.0163 per second at 480p ($0.0351 at 720p), about **$0.08** for 5 seconds. The picture becomes the first frame. Lengths 5 to 15 s. ([model page](https://martllm.com/models/bytedance/seedance-2-0-mini-image-to-video))\n\n```\n{\"model\": \"bytedance/seedance-2-0-mini-image-to-video\", \"prompt\": \"slow push-in as the waves roll\",\n \"image_url\": \"https://example.com/first-frame.png\", \"duration_seconds\": 5, \"resolution\": \"480p\"}\n```\n\nFor image-to-video, send a picture that already has the shape you want (crop it to 9:16 for a vertical clip). Most Kling, Veo and Seedance image-to-video models make the clip in the shape of the source picture and refuse an `aspect_ratio`.\n\n`\"models\": [\"kling/kling-v3-standard-text-to-video\"]` and that model is tried only if the first has no free provider right now. The reply's `model` field says which one took the job.`max_cost` on the request caps what one job can cost.\nThe same pattern runs as a Python script, an n8n workflow or a queue worker. The job is the unit: price it, start it once, wait, fetch it.\n\n*Alex, CEO, MartLLM*", "url": "https://wpnews.pro/news/how-to-generate-ai-video-from-code-veo-3-1-kling-and-seedance-with-one-api", "canonical_source": "https://dev.to/alex_martllm/how-to-generate-ai-video-from-code-veo-31-kling-and-seedance-with-one-api-3d9p", "published_at": "2026-11-28 04:31:50+00:00", "updated_at": "2026-11-28 04:43:19.996710+00:00", "lang": "en", "topics": ["generative-ai", "ai-products", "ai-tools", "developer-tools", "artificial-intelligence"], "entities": ["MartLLM", "Google", "Veo 3.1", "Kuaishou", "Kling", "ByteDance", "Seedance"], "also_reported_by": [], "takeaway": "Treat video generation as an async job — quote cost with validate:true, send an Idempotency-Key, poll every 5-10 seconds, and note that failed, canceled and expired jobs cost nothing.", "recommendation": {"advice": "Quote every video request with validate:true before starting it and attach an Idempotency-Key, so invalid parameters and retries never trigger charges.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/how-to-generate-ai-video-from-code-veo-3-1-kling-and-seedance-with-one-api", "markdown": "https://wpnews.pro/news/how-to-generate-ai-video-from-code-veo-3-1-kling-and-seedance-with-one-api.md", "text": "https://wpnews.pro/news/how-to-generate-ai-video-from-code-veo-3-1-kling-and-seedance-with-one-api.txt", "jsonld": "https://wpnews.pro/news/how-to-generate-ai-video-from-code-veo-3-1-kling-and-seedance-with-one-api.jsonld"}}