LTX-2 API Code Examples
Ready-to-use code samples for integrating LTX-2 API into your applications. Examples in Node.js, Python, and cURL.
Node.js
text-to-video.js
const axios = require('axios');
const API_KEY = 'your_api_key_here';
const BASE_URL = 'https://api.ltx-2api.com/v1';
async function generateVideo(prompt, options = {}) {
try {
// Submit generation request
const response = await axios.post(`${BASE_URL}/text-to-video`, {
prompt,
duration: options.duration || 10,
resolution: options.resolution || '1080p',
fps: options.fps || 25,
mode: options.mode || 'fast',
webhook_url: options.webhookUrl
}, {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
}
});
const { task_id } = response.data;
console.log(`Task created: ${task_id}`);
// Poll for completion (if no webhook)
if (!options.webhookUrl) {
return await pollForCompletion(task_id);
}
return { task_id };
} catch (error) {
console.error('Error:', error.response?.data || error.message);
throw error;
}
}
async function pollForCompletion(taskId, maxAttempts = 60) {
for (let i = 0; i < maxAttempts; i++) {
const status = await axios.get(`${BASE_URL}/status/${taskId}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
if (status.data.status === 'completed') {
return status.data;
} else if (status.data.status === 'failed') {
throw new Error(status.data.error);
}
await new Promise(r => setTimeout(r, 2000)); // Wait 2s
}
throw new Error('Timeout waiting for video');
}
// Usage
generateVideo('A beautiful sunset over the ocean', {
duration: 8,
resolution: '1080p',
mode: 'pro'
}).then(result => {
console.log('Video URL:', result.video_url);
});Python
text_to_video.py
import requests
import time
API_KEY = "your_api_key_here"
BASE_URL = "https://api.ltx-2api.com/v1"
def generate_video(prompt, duration=10, resolution="1080p", fps=25, mode="fast"):
"""Generate a video from a text prompt."""
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"prompt": prompt,
"duration": duration,
"resolution": resolution,
"fps": fps,
"mode": mode
}
# Submit request
response = requests.post(f"{BASE_URL}/text-to-video", json=payload, headers=headers)
response.raise_for_status()
task_id = response.json()["task_id"]
print(f"Task created: {task_id}")
# Poll for completion
return poll_for_completion(task_id, headers)
def poll_for_completion(task_id, headers, max_attempts=60):
"""Poll the status endpoint until video is ready."""
for _ in range(max_attempts):
response = requests.get(f"{BASE_URL}/status/{task_id}", headers=headers)
data = response.json()
if data["status"] == "completed":
return data
elif data["status"] == "failed":
raise Exception(data.get("error", "Generation failed"))
print(f"Progress: {data.get('progress', 0)}%")
time.sleep(2)
raise Exception("Timeout waiting for video")
# Usage
if __name__ == "__main__":
result = generate_video(
prompt="A golden retriever playing fetch in a park",
duration=8,
mode="pro"
)
print(f"Video URL: {result['video_url']}")cURL
Submit Request
# Generate video
curl -X POST https://api.ltx-2api.com/v1/text-to-video \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Timelapse of clouds moving over mountains",
"duration": 10,
"resolution": "1080p",
"fps": 25,
"mode": "fast"
}'
# Check status
curl https://api.ltx-2api.com/v1/status/TASK_ID \
-H "Authorization: Bearer YOUR_API_KEY"Image-to-Video Example (Python)
image_to_video.py
import requests
def image_to_video(image_url, prompt=None, duration=8, motion_strength=0.5):
"""Animate an image into a video."""
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"image_url": image_url,
"duration": duration,
"motion_strength": motion_strength,
"resolution": "1080p",
"mode": "pro"
}
if prompt:
payload["prompt"] = prompt
response = requests.post(f"{BASE_URL}/image-to-video", json=payload, headers=headers)
response.raise_for_status()
return response.json()["task_id"]
# Usage
task_id = image_to_video(
image_url="https://example.com/product.jpg",
prompt="Camera slowly zooms in, product rotates slightly",
motion_strength=0.3
)