Sora API Integration Guide
Complete step-by-step tutorial on integrating OpenAI's Sora API with Python code examples
đ Table of Contents
1. Introduction to Sora API
OpenAI's Sora API enables developers to generate high-quality, realistic videos from text descriptions. This powerful AI model can create videos up to 90 seconds long with synchronized audio, making it ideal for content creation, marketing, and creative applications.
Key Features
đĨ Text-to-Video
Generate videos from detailed text descriptions with realistic motion and physics.
đŧī¸ Image-to-Video
Animate static images with natural motion and scene continuity.
đ Audio Sync
Automatic audio generation including ambient sounds and effects.
⥠Fast Generation
Create professional-quality videos in minutes, not hours.
Available Models
| Model | Max Duration | Best For |
|---|---|---|
| sora-2 | 20 seconds | Fast prototyping, social media content |
| sora-2-pro | 90 seconds | High-quality production, cinematic content |
2. Quick Setup Guide
What You'll Need
- OpenAI API Key: Sign up at platform.openai.com
- Python 3.8+ or Node.js 16+
- Basic REST API knowledge
1Install Dependencies
pip install openai python-dotenv requests
2Configure API Key
Create a .env file:
OPENAI_API_KEY=your_api_key_here
đ Security Tip
Never commit your API key to version control. Add .env to your .gitignore file.
3Test Your Setup
from openai import OpenAI
import os
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
# Test connection
try:
models = client.models.list()
print("â Connection successful!")
except Exception as e:
print(f"â Error: {e}")
3. Basic Usage Examples
Your First Video Generation
Here's a simple example to generate your first video:
from openai import OpenAI
import os
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
def generate_video(prompt, duration=5):
"""Generate a video from text prompt."""
response = client.videos.generate(
model="sora-2",
prompt=prompt,
duration=duration
)
return response
# Example usage
prompt = "A serene mountain landscape at sunrise with cinematic lighting"
result = generate_video(prompt, duration=10)
print(f"Video URL: {result.url}")
print(f"Duration: {result.duration}s")
Download Generated Video
import requests
def download_video(video_url, output_path="output.mp4"):
"""Download video from URL."""
response = requests.get(video_url, stream=True)
with open(output_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"â Downloaded: {output_path}")
# Usage
download_video(result.url, "my_video.mp4")
đĄ Prompt Writing Tips
- Be specific about camera movement (e.g., "dolly shot", "pan right")
- Describe lighting (e.g., "golden hour", "soft studio lighting")
- Mention atmosphere and mood (e.g., "serene", "energetic")
- Keep prompts concise but detailed
4. Advanced Features
Image-to-Video Generation
Animate static images with motion:
import base64
def image_to_video(image_path, prompt, duration=5):
"""Animate an image with AI."""
with open(image_path, 'rb') as f:
image_data = base64.b64encode(f.read()).decode('utf-8')
response = client.videos.generate(
model="sora-2-pro",
prompt=prompt,
image=image_data,
duration=duration
)
return response
# Example
result = image_to_video(
"portrait.jpg",
"The person smiles and waves, natural motion"
)
Batch Processing
Generate multiple videos efficiently:
from concurrent.futures import ThreadPoolExecutor
def generate_batch(prompts, model="sora-2"):
"""Generate multiple videos in parallel."""
def generate_single(prompt):
return client.videos.generate(
model=model,
prompt=prompt,
duration=5
)
with ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(generate_single, prompts))
return results
# Example
prompts = [
"Ocean waves at sunset",
"City traffic time-lapse",
"Forest in autumn"
]
videos = generate_batch(prompts)
Custom Parameters
| Parameter | Options | Description |
|---|---|---|
| duration | 1-20 (sora-2) 1-90 (pro) |
Video length in seconds |
| resolution | "1080p", "4k" | Output resolution |
| seed | 0-999999 | For reproducibility |
5. Best Practices
Writing Effective Prompts
đ¯ Be Specific
Good: "Dolly shot forward, golden hour, serene"
Avoid: "Nice nature video"
đŦ Camera Terms
Use: "tracking shot", "pan right", "close-up"
đ Audio Details
Mention sounds: "footsteps", "wind rustling", "birds chirping"
âąī¸ Structure Shots
Long videos: "Shot 1 (0-5s): wide, Shot 2 (5-10s): close"
Cost Optimization
- Test First: Use sora-2 with 5s duration for testing
- Choose Wisely: Use sora-2 for social media, sora-2-pro for production
- Cache Results: Save and reuse similar generations
- Batch Processing: Generate multiple videos in parallel
Error Handling
from openai import RateLimitError, APIError
import time
def robust_generate(prompt, max_retries=3):
"""Generate with retry logic."""
for attempt in range(max_retries):
try:
return client.videos.generate(
model="sora-2",
prompt=prompt,
duration=5
)
except RateLimitError:
wait_time = 2 ** attempt
print(f"Rate limit. Waiting {wait_time}s...")
time.sleep(wait_time)
except APIError as e:
if "content_policy" in str(e):
print(f"Policy violation: {e}")
return None
if attempt < max_retries - 1:
time.sleep(2 ** attempt)
return None
â ī¸ Content Policy
Ensure compliance with OpenAI's usage policies:
- No violent, sexual, or hateful content
- No unauthorized use of public figures
- Disclose AI-generated content
- Videos include automatic watermarks
6. Real-World Examples
Example 1: Marketing Video Generator
def create_product_video(product_name, features):
"""Generate product marketing video."""
features_text = ", ".join(features)
prompt = f"""
Professional showcase for {product_name}.
Smooth camera pan revealing the product.
Clean modern aesthetic with studio lighting.
Highlights: {features_text}.
Premium commercial quality.
"""
return client.videos.generate(
model="sora-2-pro",
prompt=prompt.strip(),
duration=15
)
# Usage
video = create_product_video(
"SmartWatch Pro",
["Heart rate monitor", "GPS", "7-day battery"]
)
Example 2: Social Media Content Pipeline
PLATFORM_SPECS = {
"instagram": {"duration": 15, "style": "vibrant, trendy"},
"tiktok": {"duration": 15, "style": "creative, authentic"},
"youtube": {"duration": 30, "style": "engaging hook"}
}
def generate_for_platform(content_idea, platform):
"""Create platform-optimized content."""
specs = PLATFORM_SPECS[platform]
prompt = f"""
{content_idea}
Optimized for {platform}. {specs['style']}.
Vertical format (9:16).
Maximum impact in {specs['duration']}s.
"""
return client.videos.generate(
model="sora-2",
prompt=prompt.strip(),
duration=specs['duration']
)
# Example
video = generate_for_platform(
"Quick morning workout routine",
"instagram"
)
đ Next Steps
- Experiment with different prompts and parameters
- Build your own video generation workflows
- Join the OpenAI developer community
- Check out the full API documentation
Ready to Start Building?
Get started with OpenAI's Sora API and bring your video generation ideas to life.
Get API Access â View Documentation