Back to Renderful
Tutorial

How to Generate AI Videos with an API: Step-by-Step Tutorial

·8 min read
Kling v3 Pro playground on Renderful — generate AI videos with API

Want to generate AI videos programmatically? This tutorial walks you through the entire process — from choosing a model to downloading the finished video. You'll learn how to use Renderful's REST API with code examples in Python, JavaScript, and cURL to generate videos using Sora, Kling, Runway, and other top models.

Prerequisites

Before you begin, make sure you have the following:

  • A Renderful account and API key (sign up at renderful.ai/signup)
  • Basic knowledge of HTTP requests (REST APIs)
  • Python 3.7+ or Node.js 16+ (for the code examples)
  • A way to make HTTP requests (cURL, requests library, or fetch)

Step 1: Choose Your Video Model

Renderful gives you access to multiple video generation models. Each has different strengths, speeds, and price points:

ModelSpeedQualityPrice
Sora 22-5 minExcellentFrom $0.20
Kling 1.630-90sVery GoodFrom $0.10
Runway Gen-31-3 minVery GoodFrom $0.15
Hailuo MiniMax1-2 minGoodFrom $0.08
Wan 2.130-60sGoodFrom $0.05

Step 2: Set Up Authentication

All API requests require an API key passed in the Authorization header. After signing up, you can find your key in the Renderful dashboard.

Header
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json

Keep your API key secure. Never expose it in client-side code or public repositories. Use environment variables to store it safely.

Step 3: Send a Generation Request

Send a POST request to the generations endpoint with your model, prompt, and settings. Here are examples in three languages:

cURL:

POST/api/v1/generations
curl -X POST https://api.renderful.ai/api/v1/generations \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "kling/v1.6-standard",
    "input": {
      "prompt": "A golden retriever running through a field of wildflowers at sunset",
      "aspect_ratio": "16:9",
      "duration": 5
    },
    "webhook": "https://your-app.com/webhook"
  }'

Python:

Python
import requests

response = requests.post(
    "https://api.renderful.ai/api/v1/generations",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "model": "kling/v1.6-standard",
        "input": {
            "prompt": "A golden retriever running through a field of wildflowers at sunset",
            "aspect_ratio": "16:9",
            "duration": 5
        },
        "webhook": "https://your-app.com/webhook"
    }
)

generation = response.json()
print(f"Generation ID: {generation['id']}")
print(f"Status: {generation['status']}")

JavaScript:

JavaScript
const response = await fetch("https://api.renderful.ai/api/v1/generations", {
  method: "POST",
  headers: {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "kling/v1.6-standard",
    input: {
      prompt: "A golden retriever running through a field of wildflowers at sunset",
      aspect_ratio: "16:9",
      duration: 5,
    },
    webhook: "https://your-app.com/webhook",
  }),
});

const generation = await response.json();
console.log("Generation ID:", generation.id);
console.log("Status:", generation.status);

Step 4: Poll for Results or Use Webhooks

Video generation is asynchronous. You have two options to get your result:

Option A: Webhooks (Recommended)

Pass a webhook URL in your request. Renderful will send a POST request to your URL when the video is ready, with the full generation result in the body.

Option B: Polling

Use the generation ID from the initial response to check status. Poll the GET endpoint until the status changes to completed.

Polling example (Python):

Python
import time
import requests

generation_id = "gen_abc123"

while True:
    resp = requests.get(
        f"https://api.renderful.ai/api/v1/generations/{generation_id}",
        headers={"Authorization": "Bearer YOUR_API_KEY"}
    )
    data = resp.json()

    if data["status"] == "completed":
        print(f"Video URL: {data['output']['url']}")
        break
    elif data["status"] == "failed":
        print(f"Error: {data['error']}")
        break

    time.sleep(5)  # Wait 5 seconds before next poll

Step 5: Download & Use Your Video

Once generation is complete, you'll receive a URL to the MP4 video file. Download it or use the URL directly in your application:

Python
import requests

video_url = data["output"]["url"]

# Download the video file
video = requests.get(video_url)
with open("output.mp4", "wb") as f:
    f.write(video.content)

print("Video saved to output.mp4")

Video URLs are temporary and expire after 24 hours. Download or cache the video promptly for long-term use.

Complete Working Example

Here's a complete Python script that generates a video and downloads it:

generate_video.py
import os
import time
import requests

API_KEY = os.environ["RENDERFUL_API_KEY"]
BASE_URL = "https://api.renderful.ai/api/v1"

def generate_video(prompt, model="kling/v1.6-standard", duration=5):
    """Generate a video and wait for completion."""
    # Step 1: Start generation
    resp = requests.post(
        f"{BASE_URL}/generations",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={
            "model": model,
            "input": {
                "prompt": prompt,
                "aspect_ratio": "16:9",
                "duration": duration,
            },
        },
    )
    resp.raise_for_status()
    gen_id = resp.json()["id"]
    print(f"Started generation {gen_id}")

    # Step 2: Poll for completion
    while True:
        status_resp = requests.get(
            f"{BASE_URL}/generations/{gen_id}",
            headers={"Authorization": f"Bearer {API_KEY}"},
        )
        data = status_resp.json()

        if data["status"] == "completed":
            return data["output"]["url"]
        elif data["status"] == "failed":
            raise Exception(f"Generation failed: {data.get('error')}")

        print(f"Status: {data['status']}... waiting")
        time.sleep(5)

    # Step 3: Download video
    video_url = generate_video("A timelapse of a city skyline from day to night")
    video = requests.get(video_url)
    with open("output.mp4", "wb") as f:
        f.write(video.content)
    print("Video saved to output.mp4")

Troubleshooting Common Errors

401 Unauthorized

Your API key is missing or invalid. Check that you are passing it in the Authorization header as "Bearer YOUR_API_KEY".

422 Validation Error

The request body is malformed. Verify that required fields (model, input.prompt) are present and correctly formatted.

429 Too Many Requests

You are sending requests too quickly. Add a delay between requests or use webhooks instead of polling.

Generation Status: "failed"

The model could not generate the video. Try simplifying your prompt, reducing the duration, or switching to a different model.

Related Articles

Frequently Asked Questions

How long does it take to generate an AI video via API?
Generation time varies by model. Fast models like Kling can produce a 5-second clip in 30-60 seconds. Higher-quality models like Sora may take 2-5 minutes for longer, more detailed videos.
What programming languages can I use to call the API?
Any language that can make HTTP requests works with the Renderful API. We provide examples in Python, JavaScript/TypeScript, cURL, and Go. Official SDKs are available for Python and JavaScript.
Can I generate videos longer than 10 seconds?
Yes. Some models support videos up to 60 seconds. You can also chain multiple generations together using the extend feature to create longer videos from shorter clips.
Do I need a GPU to use the video generation API?
No. All processing happens on Renderful servers. You just send an API request and receive the finished video. No GPU, no ML libraries, and no model weights needed on your end.
Can I generate video from an image instead of text?
Yes. Renderful supports both text-to-video and image-to-video generation. For image-to-video, pass an image URL in the input along with an optional motion prompt to control the animation.

Start Generating AI Videos Today

Create your Renderful account, get free credits, and start generating videos with Sora, Kling, Runway, and 20+ other AI models through a single API.