Seedance 2.5 from ByteDance is officially available on Apiframe.

How to Build a Kling AI Image-to-Video API Integration: A Python Tutorial (2026)

A hands-on Python tutorial for Kling's image-to-video API, covering auth, requests, polling, and working code.

Janice Last updated November 6, 2026 July 13, 2026 · 8 min read Intermediate
How to Build a Kling AI Image-to-Video API Integration: A Python Tutorial (2026)

Kling 3.0 is one of the stronger image-to-video models available right now, with flexible clip length, resolution modes up to 4K, built-in audio, and the ability to set the last frame as well as the first. This tutorial builds a working Python integration, from checking your API key through to a FastAPI endpoint you can drop into a backend. If you want the feature and pricing overview first, start with our Kling 3.0 API guide, or see Kling 2.1 to 3.0 if you are still deciding which version to use.

We are using Apiframe here, since it offers Kling 3.0 through one endpoint shared with every other major video model, with a single API key and credit balance rather than a separate integration per provider.

What You'll Build

By the end you will have a Python script that sends a source image and a text prompt to Kling, waits until the video is ready, and returns a finished video link. We then wrap that in a small FastAPI endpoint so a real application can call it.

Prerequisites

You will need Python 3.10 or later, an Apiframe API key, and the requests library. httpx is a drop-in alternative if you want a client that can handle other work while waiting on a response. Getting Started with Apiframe covers signup and key creation. New accounts come with 100 free credits, which is worth knowing before you start: Kling 3.0 is one of the more expensive models on the platform, and 100 credits will not cover a single clip. Budget for a top-up before running this tutorial end to end.

bash
pip install requests fastapi uvicorn

Checking Your API Key

Every request needs an X-API-Key header, and keys always start with afk_. Keep the key on your server, never in code that runs in a browser or a mobile app, since anyone who reads it can spend your credits. The examples below hard-code it for readability, but load it from an environment variable in anything real. Before writing the integration, confirm the key works.

python
import os
import requests

API_KEY = os.environ["APIFRAME_API_KEY"]

response = requests.get(
    "https://api.apiframe.ai/v2/me",
    headers={"X-API-Key": API_KEY},
)
print(response.json())

A valid key returns your account details and your team's current credit balance. A 401 means the key is missing, wrong, or has been revoked, so check what you copied from the dashboard.

Sending Your First Image-to-Video Request

Kling's image-to-video generation runs through the same endpoint as text-to-video: POST /v2/videos/generate, with model set to "kling-3.0". What makes it image-to-video is passing a start_image URL inside klingParams, the image Kling animates as the first frame. That image has to be reachable at a public URL, so upload it somewhere Kling can fetch it before you call the API.

Required parameters

  • prompt: what should happen in the video (1 to 4,000 characters). Describe motion, not just the scene, since the image already supplies the scene.
  • model: "kling-3.0"
  • klingParams.start_image: a public URL for the source image you want animated

Optional parameters

  • klingParams.duration: clip length in seconds, from 3 to 15 (defaults to 5). Since billing is per second, this is the parameter that moves your bill most.
  • klingParams.mode: "standard" (720p), "pro" (1080p, the default), or "4k" (2160p). Standard costs a quarter of what 4K does, so start there while you are iterating on prompts.
  • klingParams.aspect_ratio: shape of the frame as a "W:H" string, like "16:9". Match it to your source image, since a mismatch means Kling has to crop or pad.
  • klingParams.end_image: a URL for the frame Kling should finish on, useful for controlled transitions between two known images
  • klingParams.negative_prompt: things to keep out of the output (up to 2,500 characters)
  • klingParams.generate_audio: whether to generate matching audio (defaults to true). Kling is one of a handful of models that produce audio and video together. Worth setting to false if you do not need it, since audio adds roughly half again to the per-second rate.
  • klingParams.multi_prompt: a list of timed prompts, passed as a string, when you want different things to happen at different points in the clip

Here is a complete request that animates a source image into a 10-second clip.

python
import os
import requests

API_KEY = os.environ["APIFRAME_API_KEY"]

response = requests.post(
    "https://api.apiframe.ai/v2/videos/generate",
    headers={
        "X-API-Key": API_KEY,
        "Content-Type": "application/json",
    },
    json={
        "prompt": "the camera slowly pushes in as the subject turns toward the light",
        "model": "kling-3.0",
        "klingParams": {
            "start_image": "https://example.com/your-source-image.jpg",
            "duration": 10,
            "mode": "pro",
            "aspect_ratio": "16:9",
            "generate_audio": True,
        },
    },
)

job = response.json()
print(job)  # {"jobId": "...", "status": "QUEUED"}

Worth pausing on what that request costs before you run it. Pro mode with audio is 49 credits per second, so 10 seconds is 490 credits, about $4.90. Switching to standard mode without audio drops the same clip to 240 credits, about $2.40. Test with short standard clips and only move up once the prompt is working.

The request comes back before the video exists. Apiframe queues the job and hands you a jobId you use to follow its progress.

Waiting for the Generated Video

Video generation always runs as a background job, Kling included, so the pattern is the same everywhere: submit the request, then either check back for the result or wait to be notified. Apiframe suggests checking every 5 to 10 seconds for video jobs, since they take noticeably longer than image generation. The same submit-and-check loop applies to every video model on the platform, which our general image-to-video tutorial walks through if you want to compare approaches.

python
import os
import time
import requests

API_KEY = os.environ["APIFRAME_API_KEY"]

def wait_for_video(job_id: str, timeout_seconds: int = 600, poll_interval: int = 8) -> str:
    headers = {"X-API-Key": API_KEY}
    deadline = time.time() + timeout_seconds

    while time.time() < deadline:
        response = requests.get(
            f"https://api.apiframe.ai/v2/jobs/{job_id}",
            headers=headers,
        )
        job = response.json()
        status = job["status"]

        if status == "COMPLETED":
            return job["result"]["videoUrl"]
        if status == "FAILED":
            raise RuntimeError(f"Generation failed: {job.get('error')}")

        print(f"Status: {status} ({job.get('progress', 0)}%)")
        time.sleep(poll_interval)

    raise TimeoutError(f"Job {job_id} did not complete within {timeout_seconds} seconds")

A COMPLETED job returns a result object shaped like {"videoUrl": "https://cdn2.apiframe.ai/videos/....mp4"}. That file is hosted for 90 days, so copy it to your own storage if you need it longer. The ten-minute timeout above is deliberately generous, since a 15-second 4K clip sits at the slow end of the range.

If you would rather not check at all, pass a webhookUrl and webhookEvents (["completed", "failed"]) in the original request and Apiframe will send the result to your server when the job finishes. That is the better option for production traffic, since it avoids keeping a loop running for every job. Our walkthrough on setting up callbacks covers receiving them and confirming they genuinely came from Apiframe.

Handling Errors and Retries

The error format is the same across the API: a response body with an error message and a details object pointing at the specific field that was wrong. The status codes worth handling:

StatusMeaningWhat to do
400Validation failed, check detailsFix the request, do not retry as-is
401Missing or invalid API keyCheck your X-API-Key header
402Not enough creditsTop up before retrying
403Key inactive, or admin rights neededCheck key status in the console
404Not foundVerify the job ID
429Too many requestsWait and retry
503Temporarily unavailableRetry, waiting longer each time

A job can also come back as FAILED after being accepted, usually because the prompt or source image was rejected by the content filters. Credits are refunded automatically when a job fails, so a failed generation costs you nothing. Our guide to content moderation for generated media explains what usually trips these filters, which matters more for image-to-video than text-to-video, since the source image gets checked as well as the prompt.

Do not blindly resubmit on every failure. A content rejection will fail again with the same input, so retrying only helps for temporary errors like 429 or 503. The case that really costs you is a timeout, where the response never arrived but the job may well have been accepted. Resubmitting then starts a second generation and bills you twice, which at Kling's rates means several dollars gone. Pass an Idempotency-Key header to prevent that. The key has to stay the same across retries of the same logical request, so generate it once per request, not once per attempt.

python
import os
import time
import uuid
import requests

API_KEY = os.environ["APIFRAME_API_KEY"]

def submit_with_retry(payload: dict, max_attempts: int = 3) -> dict:
    # Generated once, outside the retry loop, so every attempt
    # reuses it. A repeat key returns the original job instead
    # of starting (and billing for) a second generation.
    idempotency_key = str(uuid.uuid4())

    for attempt in range(max_attempts):
        try:
            response = requests.post(
                "https://api.apiframe.ai/v2/videos/generate",
                headers={
                    "X-API-Key": API_KEY,
                    "Content-Type": "application/json",
                    "Idempotency-Key": idempotency_key,
                },
                json=payload,
                timeout=30,
            )
            if response.status_code in (429, 503):
                time.sleep(2 ** attempt)
                continue
            response.raise_for_status()
            return response.json()
        except requests.Timeout:
            # The job may already have been accepted. The shared
            # idempotency key makes this retry safe.
            time.sleep(2 ** attempt)

    raise RuntimeError("Could not submit job after retries")

Wrapping It in a FastAPI Endpoint

Putting the pieces together, here is a small endpoint that takes an image URL and a prompt, submits the job, waits for it, and returns the finished video link.

python
import os
import time
import requests
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()
API_KEY = os.environ["APIFRAME_API_KEY"]
BASE_URL = "https://api.apiframe.ai/v2"


class ImageToVideoRequest(BaseModel):
    image_url: str
    prompt: str
    duration: int = 5
    mode: str = "standard"


@app.post("/generate-video")
def generate_video(req: ImageToVideoRequest):
    submit_response = requests.post(
        f"{BASE_URL}/videos/generate",
        headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
        json={
            "prompt": req.prompt,
            "model": "kling-3.0",
            "klingParams": {
                "start_image": req.image_url,
                "duration": req.duration,
                "mode": req.mode,
            },
        },
    )

    if not submit_response.ok:
        raise HTTPException(
            status_code=submit_response.status_code,
            detail=submit_response.json(),
        )

    job_id = submit_response.json()["jobId"]
    deadline = time.time() + 600

    while time.time() < deadline:
        job = requests.get(
            f"{BASE_URL}/jobs/{job_id}",
            headers={"X-API-Key": API_KEY},
        ).json()

        if job["status"] == "COMPLETED":
            return {"videoUrl": job["result"]["videoUrl"], "jobId": job_id}
        if job["status"] == "FAILED":
            raise HTTPException(status_code=500, detail=job.get("error"))

        time.sleep(8)

    raise HTTPException(status_code=504, detail="Generation timed out")

This works as a demo but not in production, because the loop holds the HTTP connection open for the entire generation, one to five minutes, and most load balancers and browsers will give up before then. For anything real, replace the loop with a callback or a background task queue (Celery, arq, or FastAPI's own BackgroundTasks) so the endpoint returns the jobId immediately and a second endpoint reports progress. Note the default mode here is standard rather than pro, so a caller who does not specify one gets the cheaper option.

What This Workflow Costs

Kling 3.0 bills per second of output, and the rate depends on the mode and whether audio is switched on. Credits are $0.01 each.

VariantCredits per second5-second clip10-second clip
Standard (720p)24$1.20$2.40
Standard + audio37$1.85$3.70
Pro (1080p)32$1.60$3.20
Pro + audio49$2.45$4.90
4K (with or without audio)61$3.05$6.10

Two things follow from that table. Length and mode compound, so a 15-second 4K clip at 915 credits ($9.15) costs more than seven times a 5-second standard clip at 120 credits ($1.20). And audio is not a rounding error: it adds about half again to the rate, so turn it off when you do not need it. Budget accordingly at volume, and read our full breakdown in the AI video API pricing guide if you are comparing Kling against Runway, Hailuo, or Seedance. To forecast a monthly bill, our post on estimating AI video costs works through the math.

If those numbers are higher than your use case justifies, Kling is not the only option. Hailuo 2.3 handles image-to-video at a fraction of the cost and is particularly good with human movement, and our comparison of the best image-to-video APIs covers the rest. Since the request format is shared, switching is largely a matter of changing the model name and its parameters object.

FAQ

Does Kling have an official public API?

Yes. Kling AI runs its own developer platform with prepaid packages. Going through Apiframe gets you the same model behind one endpoint shared with every other major video and image model, so you are not managing a separate account and credit system just for Kling. If you are weighing options, we compare the main Kling 3.0 API providers side by side.

Which Python version and libraries does this need?

Python 3.10 or newer, plus requests (or httpx). The FastAPI example also needs fastapi and uvicorn to run as a server.

How long does a typical generation take?

One to five minutes depending on length and mode, with 4K and longer clips at the slower end. That is why checking every 5 to 10 seconds, or using a callback instead, beats a tight loop. Our guide to what drives wait times breaks this down across models.

What kind of source image works best?

A sharp image with a clear subject, at a shape matching your chosen aspect ratio. Low-resolution or blurry sources produce blurry motion, since the model has less to work with. The image also has to be reachable at a public URL, and it goes through the same content checks as the prompt, so photos of real people and visible brand logos are the most common cause of a rejected job.

Can I control how the clip ends as well as how it starts?

Yes. Pass end_image alongside start_image and Kling generates the motion between the two frames, which is how controlled transitions between two known images are built. Not every model offers this, and not every Kling version does either, so our comparison of Kling versions is worth checking if you are on an older one.

Power your next AI product with Apiframe.

Instant access to 70+ media models through a single API. Start free and scale when you're ready.