DEV Community

diwushennian4955
diwushennian4955

Posted on

Veo 3 API Tutorial: Generate AI Videos in 5 Lines of Code (Python + JavaScript Guide 2025)

Veo 3 API Tutorial: Generate AI Videos in 5 Lines of Code (Python + JavaScript Guide 2025)

Google's Veo 3 just landed in the Gemini API — and it's the most capable AI video model available to developers right now. In this complete tutorial, you'll learn how to generate AI videos via API, plus how to use NexaAPI as a flexible, cost-effective alternative that's available right now with no waitlist.


What Is Veo 3?

Veo 3 is Google DeepMind's flagship video generation model, now available in paid preview via the Gemini API. It's the first model to natively generate synchronized audio alongside video — dialogue, sound effects, and music in a single pass.

Key capabilities:

  • Text-to-video generation (image-to-video coming soon)
  • Native audio generation (dialogue, SFX, music)
  • Up to 1080p HD output
  • Vertical video support (9:16 for social media)
  • Realistic physics simulation
  • SynthID watermarking for responsible AI

Pricing:

  • Veo 3: $0.40/second of video output
  • Veo 3 Fast: $0.15/second of video output
  • Requires Google Cloud billing account

Veo 3 API Access Requirements

To use Veo 3 via the Gemini API:

  1. Google Cloud account with billing enabled
  2. Paid tier access (not available on free tier)
  3. API key from Google AI Studio
  4. Install: pip install google-genai

The catch: Veo 3 is in paid preview — access isn't instant and requires Google Cloud setup.

Want to start building right now? Skip to the NexaAPI section — instant access, no waitlist.


Veo 3 vs NexaAPI: Quick Comparison

Feature Veo 3 (Gemini API) NexaAPI
Access Paid preview (waitlist) ✅ Instant
Pricing $0.40/sec Fraction of cost
Free tier
Models Veo 3 only 56+ models
Setup complexity High (Google Cloud) Low (3 lines)
Video models Veo 3, Veo 3 Fast Kling v1/v1.5/v1.6, Wan 2.1
Audio generation ✅ Native Via separate audio API
1080p support
Vertical video

How to Use Veo 3 API (Official Google Method)

For reference, here's the official Veo 3 API usage:

# Official Google Veo 3 API
# Requires: pip install google-genai
# Requires: Google Cloud billing account

import time
from google import genai
from google.genai import types

client = genai.Client()  # Uses GOOGLE_API_KEY env var

operation = client.models.generate_videos(
    model="veo-3.0-generate-preview",
    prompt="A stunning aerial view of the Amazon rainforest at dawn, cinematic quality",
    config=types.GenerateVideosConfig(
        negative_prompt="blurry, low quality",
        aspect_ratio="16:9",
        resolution="1080p"
    ),
)

# Poll for completion
while not operation.done:
    time.sleep(20)
    operation = client.operations.get(operation)

generated_video = operation.result.generated_videos[0]
client.files.download(file=generated_video.video)
generated_video.video.save("output.mp4")
print("Video saved!")
Enter fullscreen mode Exit fullscreen mode

Note: Requires Google Cloud billing and paid tier access. See official docs.


NexaAPI Video Generation — Start NOW {#nexaapi-video-generation-now}

NexaAPI gives you instant access to premium AI video generation models — no waitlist, no Google Cloud setup required. Access 56+ models including Kling v1, Kling v1.5, Kling v1.6, and Wan 2.1.

Installation

pip install nexaapi
Enter fullscreen mode Exit fullscreen mode

Basic Video Generation (Python)

# pip install nexaapi
from nexaapi import NexaAPI

# Get your free API key at https://nexa-api.com
client = NexaAPI(api_key='YOUR_API_KEY')

# Generate AI video — Veo 3 style quality
response = client.video.generate(
    model='kling-v1',  # Premium AI video model
    prompt='A cinematic drone shot of a futuristic city at sunset, ultra-realistic, 4K',
    duration=5,  # seconds
    aspect_ratio='16:9'
)

print('Video URL:', response.video_url)
print('Generation time:', response.generation_time)
Enter fullscreen mode Exit fullscreen mode

Async/Polling Pattern (Python)

from nexaapi import NexaAPI
import time

client = NexaAPI(api_key='YOUR_API_KEY')

# Submit video generation job
job = client.video.generate(
    model='kling-v1',
    prompt='A timelapse of cherry blossoms falling in slow motion, cinematic lighting',
    duration=5
)

# Poll for result
while job.status != 'completed':
    time.sleep(5)
    job = client.video.get_job(job.id)
    print(f'Status: {job.status}')

print('Video ready:', job.video_url)
Enter fullscreen mode Exit fullscreen mode

Vertical Video for Social Media (Python)

from nexaapi import NexaAPI

client = NexaAPI(api_key='YOUR_API_KEY')

# Generate vertical video (9:16) — perfect for TikTok, Instagram Reels
response = client.video.generate(
    model='kling-v1',
    prompt='A product showcase of premium headphones, studio lighting, minimalist background',
    duration=5,
    aspect_ratio='9:16'  # Vertical format
)

print('Vertical video ready:', response.video_url)
Enter fullscreen mode Exit fullscreen mode

JavaScript / Node.js Tutorial

Installation

npm install nexaapi
Enter fullscreen mode Exit fullscreen mode

Basic Video Generation (JavaScript)

// npm install nexaapi
import NexaAPI from 'nexaapi';

const client = new NexaAPI({ apiKey: 'YOUR_API_KEY' }); // Get free key: nexa-api.com

async function generateVideo() {
  // Generate AI video — same quality as Veo 3 style generation
  const job = await client.video.generate({
    model: 'kling-v1',
    prompt: 'A cinematic drone shot of a futuristic city at sunset, ultra-realistic, 4K',
    duration: 5,
    aspectRatio: '16:9'
  });

  console.log('Job ID:', job.id);

  // Poll for completion
  let result = job;
  while (result.status !== 'completed') {
    await new Promise(resolve => setTimeout(resolve, 5000));
    result = await client.video.getJob(job.id);
    console.log('Status:', result.status);
  }

  console.log('Video URL:', result.videoUrl);
  return result.videoUrl;
}

generateVideo().then(url => console.log('Done:', url));
Enter fullscreen mode Exit fullscreen mode

Express.js API Endpoint

import express from 'express';
import NexaAPI from 'nexaapi';

const app = express();
const client = new NexaAPI({ apiKey: process.env.NEXAAPI_KEY });

app.post('/generate-video', async (req, res) => {
  const { prompt, duration = 5, aspectRatio = '16:9' } = req.body;

  try {
    const job = await client.video.generate({
      model: 'kling-v1',
      prompt,
      duration,
      aspectRatio
    });

    // Return job ID for polling
    res.json({ jobId: job.id, status: job.status });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/video-status/:jobId', async (req, res) => {
  const job = await client.video.getJob(req.params.jobId);
  res.json({ 
    status: job.status, 
    videoUrl: job.status === 'completed' ? job.videoUrl : null 
  });
});

app.listen(3000, () => console.log('Video API server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

Advanced Prompt Engineering for AI Video

Getting great results from AI video generation is all about the prompt. Here are proven patterns:

Cinematic Style Prompts

prompts = [
    # Landscape/nature
    "Aerial drone shot over misty mountains at sunrise, golden hour lighting, 4K cinematic",

    # Product showcase
    "Luxury watch rotating on a marble surface, macro lens, studio lighting, slow motion",

    # Urban/architecture
    "Time-lapse of a busy city intersection at night, light trails, rain reflections",

    # Character/person
    "A chef plating an elegant dish in a Michelin-star kitchen, close-up, warm lighting",

    # Abstract/artistic
    "Ink droplets spreading in water in slow motion, macro photography, black background"
]

for prompt in prompts:
    response = client.video.generate(
        model='kling-v1',
        prompt=prompt,
        duration=5
    )
    print(f"Generated: {response.video_url}")
Enter fullscreen mode Exit fullscreen mode

Prompt Formula

[Camera movement] + [Subject] + [Action] + [Environment] + [Lighting] + [Style/Quality]
Enter fullscreen mode Exit fullscreen mode

Examples:

  • "Slow dolly shot of [subject] in [environment], [lighting], cinematic 4K"
  • "Aerial view of [location] at [time of day], [weather], drone footage"
  • "Close-up macro of [object] [action], [lighting], ultra-detailed"

Building a Video Generation App

Here's a complete mini-app that generates videos from text prompts:

#!/usr/bin/env python3
"""
AI Video Generator App
Powered by NexaAPI — https://nexa-api.com
"""

from nexaapi import NexaAPI
import argparse
import time

def main():
    parser = argparse.ArgumentParser(description='Generate AI videos with NexaAPI')
    parser.add_argument('prompt', help='Video description')
    parser.add_argument('--model', default='kling-v1', help='Model to use')
    parser.add_argument('--duration', type=int, default=5, help='Duration in seconds')
    parser.add_argument('--aspect', default='16:9', help='Aspect ratio (16:9 or 9:16)')
    parser.add_argument('--key', required=True, help='NexaAPI key (get at nexa-api.com)')
    args = parser.parse_args()

    client = NexaAPI(api_key=args.key)

    print(f"🎬 Generating video...")
    print(f"   Prompt: {args.prompt[:60]}...")
    print(f"   Model: {args.model}")
    print(f"   Duration: {args.duration}s")

    start = time.time()
    response = client.video.generate(
        model=args.model,
        prompt=args.prompt,
        duration=args.duration,
        aspect_ratio=args.aspect
    )
    elapsed = time.time() - start

    print(f"\n✅ Video ready in {elapsed:.1f}s!")
    print(f"   URL: {response.video_url}")

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Usage:

python video_generator.py "A stunning sunset over the ocean" --key YOUR_API_KEY
python video_generator.py "Product demo video" --aspect 9:16 --duration 8 --key YOUR_API_KEY
Enter fullscreen mode Exit fullscreen mode

Resources & Next Steps

  • 🚀 NexaAPI — Get your free API key, instant access to 56+ models
  • 🔌 RapidAPI Hub — Access NexaAPI via RapidAPI
  • 📦 Python SDK: pip install nexaapi | PyPI
  • 📦 Node.js SDK: npm install nexaapi | npm
  • 📖 Google Veo 3 Official Docs: developers.googleblog.com
  • 🧪 Veo 3 Cookbook: GitHub

Have questions about AI video generation? Drop them in the comments. What are you building with video AI?

Tags: veo3, ai, videogeneration, python, javascript, tutorial, nexaapi, gemini

Top comments (0)