Seedance 2.5 from ByteDance is officially available on Apiframe.

How to Build an Image-to-Video API Integration: A Python Tutorial (2026)

A step-by-step Python tutorial for building an image-to-video API integration: auth, requests, polling, error handling, and a working FastAPI endpoint.

Janice Last updated November 4, 2026 July 7, 2026 · 7 min read Intermediate
How to Build an Image-to-Video API Integration: A Python Tutorial (2026)

Animating a still image into a short video clip has become one of the more practical uses of AI generation, and it is easier to build than most developers expect. This tutorial walks through a complete Python integration: setting up authentication, sending your first request, checking for the result, handling errors, and wrapping the whole thing in a simple endpoint you can call from a frontend.

By the end, you will have a working /animate endpoint that takes an image and returns a generated video.

What Is an Image-to-Video API (and When to Use One)

Image-to-video generation takes a still image and adds motion to it: camera movement, subject animation, or a continuation of the scene, producing a short clip that starts from that reference image. It is a different problem from text-to-video, where the model builds a scene from scratch out of a written description. With image-to-video, the first frame is fixed, and the model's job is working out how to bring it to life convincingly. If you want the other side of this, we have a matching text-to-video Python tutorial.

A few common use cases: animating product photos for online listings or ads, adding motion to social content without reshooting anything, giving avatars subtle idle movement, and turning storyboard frames into rough preview clips before committing to full production.

Prerequisites

Before starting, you will need an API key, Python 3.9 or later, the requests library installed (pip install requests), and a source image you want to animate. Nothing exotic, just a standard web API integration. Our getting started guide covers account and key setup if you do not have one yet.

Step 1: Set Up Your Environment and Authentication

Start by storing your API key as an environment variable rather than writing it into your source code:

bash
export APIFRAME_API_KEY="your_api_key_here"

Then confirm the key works with a quick check:

python
import os
import requests

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

response = requests.get(
    f"{BASE_URL}/me",
    headers={"X-API-Key": API_KEY}
)

print(response.status_code, response.json())

If that returns a 200 with your account details, you are ready to move on.

Step 2: Send Your First Image-to-Video Request

Choosing a Model

Kling, Hailuo, and Seedance all offer image-to-video modes, and on a unified API like Apiframe they run through the same endpoint, so moving between them later means changing a few fields rather than rebuilding the integration. Kling gives you the widest choice of quality and cost tiers. Hailuo is the strongest on human movement, which matters if your image has a person in it. Seedance generates the longest single clips, up to 30 seconds. For a closer comparison of these and other options, see our roundup of image-to-video APIs.

Key Parameters

This tutorial uses Kling 3.0, so the parameters go inside a klingParams object. The ones you will work with are start_image (the URL of the image you are animating, which has to be hosted somewhere publicly reachable), duration (clip length in seconds, up to 15 on Kling 3.0), mode ("standard" or "pro," trading cost against quality), and aspect_ratio (match it to your source image or your target platform). Other model families use their own params object and their own field names, so check the docs for the model you settle on. Our Kling versions guide covers which Kling model to pick.

Here is a basic request. The source image has to be hosted at a public URL already, so upload it to your own storage first if it is only sitting on your local disk.

python
response = requests.post(
    f"{BASE_URL}/videos/generate",
    headers={
        "X-API-Key": API_KEY,
        "Content-Type": "application/json",
    },
    json={
        "prompt": "slow zoom in, gentle camera drift",
        "model": "kling-3.0",
        "klingParams": {
            "start_image": "https://your-cdn.example.com/product-photo.jpg",
            "duration": 5,
            "mode": "pro",
            "aspect_ratio": "9:16"
        }
    }
)

job = response.json()
job_id = job["jobId"]
print(f"Job submitted: {job_id}")

Step 3: Poll for Results and Download the Video

Video generation is not instant, so this follows a common pattern: you submit a request, get a job ID back right away, and check a status endpoint until the video is ready.

python
import time

def wait_for_video(job_id, timeout=300, interval=8):
    elapsed = 0
    while elapsed < timeout:
        status_response = requests.get(
            f"{BASE_URL}/jobs/{job_id}",
            headers={"X-API-Key": API_KEY}
        )
        job = status_response.json()

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

        time.sleep(interval)
        elapsed += interval

    raise TimeoutError("Video generation timed out")

video_url = wait_for_video(job_id)
print(f"Video ready: {video_url}")

video_data = requests.get(video_url).content
with open("output.mp4", "wb") as f:
    f.write(video_data)

The wait here is deliberately simple, a fixed interval. In production, lengthen the gap a little after each check so you are not hammering the status endpoint through a long generation. Better still, skip checking entirely and let the result come to you, which our walkthrough on setting up webhook callbacks explains.

Step 4: Handle Errors, Retries, and Rate Limits

Three error patterns come up often enough to plan for directly.

Rate limit responses (usually a 429, meaning you are sending requests faster than your plan allows) should be met with a pause and a retry rather than an immediate resubmission.

Timeouts on the submission call itself are worth retrying once or twice, since they are usually a passing network problem rather than a real failure.

Content moderation rejections (the model refusing to animate a particular image) should be shown clearly to the user rather than retried quietly, because retrying will not change the outcome. Our guide to AI content moderation covers what tends to trigger this.

Here is a retry wrapper that waits twice as long after each failed attempt, so repeated failures back off instead of piling up:

python
def submit_with_retry(payload, max_retries=3):
    for attempt in range(max_retries):
        response = requests.post(
            f"{BASE_URL}/videos/generate",
            headers={
                "X-API-Key": API_KEY,
                "Content-Type": "application/json",
            },
            json=payload
        )
        if response.status_code == 202:
            return response.json()
        if response.status_code == 429:
            wait_time = 2 ** attempt
            time.sleep(wait_time)
            continue
        response.raise_for_status()

    raise RuntimeError("Max retries exceeded")

For production jobs, it is also worth sending an Idempotency-Key header with each submission if your provider supports it. That way a retried request will not accidentally start a second generation and charge you twice.

Step 5: Wrap the Call in a Simple API Endpoint

Once the core logic works, wrapping it in a small FastAPI endpoint lets your frontend trigger animations without touching the provider's API directly. Because Kling expects a hosted image URL rather than the raw file, this endpoint takes a URL. If your frontend only has a local file, upload it to your own storage first and pass the resulting URL.

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class AnimateRequest(BaseModel):
    image_url: str
    prompt: str = "gentle camera drift"

@app.post("/animate")
async def animate(req: AnimateRequest):
    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": 5,
                "mode": "pro"
            }
        }
    )
    job = response.json()

    video_url = wait_for_video(job["jobId"])
    return {"video_url": video_url}

A frontend can now POST a JSON body with an image URL to /animate and get back a video URL once generation finishes. One caveat: this holds the HTTP request open for the full generation, which can be a minute or more, so most setups will time out. For anything real, move the waiting into a background task or a webhook. If you want this same pattern with Kling-specific detail, see our Kling image-to-video Python tutorial.

Cost Considerations for Image-to-Video at Scale

Per-clip costs vary enormously by model and settings. A short clip on a budget model lands under $0.30, a standard Hailuo 2.3 clip is around $0.41, and a 5-second Kling 3.0 pro clip with audio is roughly $2.45. Stretch that to 15 seconds and you are over $7. The gap between the cheapest and most expensive option here is more than twentyfold, so the model and settings you default to matter far more than any other optimization.

A few ways to keep spend down at volume: default to the shortest duration that still works rather than the maximum, draft on a cheap fast model and only run finals on the expensive one, cache results for repeated inputs instead of regenerating, and offer lower resolution on free tiers. For how the major models price out, see our AI video API pricing guide, and our guide to estimating monthly AI video costs walks through the math at your own volume.

Common Pitfalls and Troubleshooting

Blurry or glitchy motion usually comes from vague or contradictory motion wording in the prompt, or from a cluttered, low-resolution source image. Being specific about camera movement ("slow zoom," "static shot," "gentle pan") and starting from a clean, sharp image tends to fix it.

Timeout handling matters more than people expect on a first integration. Generation time shifts with load and model choice, so set a generous timeout and tell the user what is happening rather than assuming a fixed wait.

Mismatched aspect ratios between your source image and the requested output produce awkward cropping, so match the aspect_ratio parameter to your actual source image where you can.

Content moderation rejections happen more often with images containing real people or brand logos. If you are building around user-uploaded images, treat this as a normal path with a clear error message rather than a rare edge case.

FAQ

Which model is best for image-to-video?

It depends on your priority. Kling offers the widest spread of quality and price tiers, Hailuo handles human movement and facial expression best, and Seedance produces the longest single clips. Our Kling 3.0 API guide and Hailuo 2.3 guide cover those two in depth.

How long does generation take?

Usually between 90 seconds and about three minutes, depending on model, resolution, and clip length. Faster variants land near 90 seconds and the heavier models closer to 180. Build your interface around a waiting state rather than an instant response.

Can I animate any image?

Mostly, but content moderation applies, and images featuring real public figures or certain brand elements may be rejected depending on the model and the provider's policies.

Is there a free way to test this?

Most providers, including Apiframe, offer trial credits or a free tier, enough to build the integration in this tutorial before committing to a paid plan. See our breakdown of free AI video generation APIs for the exact limits across providers. If you are building the text-to-video side of your product too, our AI video API guide covers the broader landscape, and our AI video generation API guide goes deeper on choosing between models. You can get an API key and start with free credits to try the integration above yourself.

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.