API完整文档
基础信息
Base URL: https://api.videomatic.com/v1
认证方式: API Key (Header) 或 JWT Token
请求格式: JSON
响应格式: JSON
一、认证鉴权
1. API Key认证(推荐)
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.videomatic.com/v1/videos
获取API Key:
- 登录控制台
- 前往"设置 → API密钥"
- 点击"创建新密钥"
2. JWT Token认证
# 1. 登录获取token
curl -X POST https://api.videomatic.com/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"***"}'
# 2. 使用token
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
https://api.videomatic.com/v1/videos
二、核心API
1. 创建单个视频
端点: POST /videos
请求:
{
"template_id": "template_abc123",
"data": {
"product_name": "iPhone 15 Pro",
"price": 7999,
"product_image": "https://example.com/image.jpg"
},
"options": {
"resolution": "1080x1920",
"format": "mp4",
"quality": "high"
}
}
响应:
{
"id": "video_xyz789",
"status": "queued",
"created_at": "2025-01-09T10:00:00Z",
"estimated_time": 120
}
2. 批量创建视频
端点: POST /videos/batch
请求:
{
"template_id": "template_abc123",
"data_source": {
"type": "url",
"url": "https://example.com/products.csv"
},
"options": {
"concurrent": 10
}
}
响应:
{
"batch_id": "batch_123abc",
"total_count": 100,
"status": "processing",
"created_at": "2025-01-09T10:00:00Z"
}
3. 查询视频状态
端点: GET /videos/:id
响应:
{
"id": "video_xyz789",
"status": "completed",
"progress": 100,
"file_url": "https://cdn.videomatic.com/videos/xyz789.mp4",
"duration": 15.5,
"file_size": 2048576,
"created_at": "2025-01-09T10:00:00Z",
"completed_at": "2025-01-09T10:02:30Z"
}
状态值:
queued: 排队中processing: 渲染中completed: 已完成failed: 失败
4. 获取批量任务进度
端点: GET /videos/batch/:batch_id
响应:
{
"batch_id": "batch_123abc",
"total": 100,
"completed": 85,
"failed": 2,
"processing": 13,
"progress": 85,
"videos": [
{"id": "video_1", "status": "completed"},
{"id": "video_2", "status": "completed"},
...
]
}
5. 模板管理
获取模板列表
GET /templates?category=ecommerce&page=1&limit=20
获取模板详情
GET /templates/:template_id
创建自定义模板
POST /templates
Content-Type: application/json
{
"name": "我的模板",
"category": "ecommerce",
"config": {...}
}
三、SDK示例
Python SDK
安装:
pip install videomatic
使用:
from videomatic import VideoMatic
# 初始化
client = VideoMatic(api_key="your_api_key")
# 创建单个视频
video = client.videos.create(
template_id="template_abc123",
data={
"product_name": "iPhone 15 Pro",
"price": 7999,
"product_image": "https://example.com/image.jpg"
}
)
print(f"视频ID: {video.id}")
print(f"状态: {video.status}")
# 等待完成
video.wait_until_completed()
print(f"视频URL: {video.file_url}")
# 批量创建
batch = client.videos.batch_create(
template_id="template_abc123",
data_source="https://example.com/products.csv"
)
# 监控进度
for progress in batch.watch_progress():
print(f"进度: {progress['completed']}/{progress['total']}")
Node.js SDK
安装:
npm install videomatic
使用:
const VideoMatic = require('videomatic');
const client = new VideoMatic({
apiKey: 'your_api_key'
});
// 创建视频
const video = await client.videos.create({
templateId: 'template_abc123',
data: {
productName: 'iPhone 15 Pro',
price: 7999,
productImage: 'https://example.com/image.jpg'
}
});
console.log('视频ID:', video.id);
// 等待完成
await video.waitUntilCompleted();
console.log('视频URL:', video.fileUrl);
// 批量创建
const batch = await client.videos.batchCreate({
templateId: 'template_abc123',
dataSource: 'https://example.com/products.csv'
});
// 监控进度
batch.on('progress', (progress) =\> {
console.log(`进度: ${progress.completed}/${progress.total}`);
});
await batch.waitUntilCompleted();
Go SDK
安装:
go get github.com/videomatic/videomatic-go
使用:
package main
import (
"fmt"
"github.com/videomatic/videomatic-go"
)
func main() {
client := videomatic.NewClient("your_api_key")
// 创建视频
video, err := client.Videos.Create(&videomatic.VideoCreateParams{
TemplateID: "template_abc123",
Data: map[string]interface{}{
"product_name": "iPhone 15 Pro",
"price": 7999,
"product_image": "https://example.com/image.jpg",
},
})
if err != nil {
panic(err)
}
fmt.Printf("视频ID: %s\n", video.ID)
// 等待完成
video.WaitUntilCompleted()
fmt.Printf("视频URL: %s\n", video.FileURL)
}
四、Webhook回调
配置Webhook
在控制台"设置 → Webhook"中配置回调URL。
事件类型
| 事件 | 说明 |
|---|---|
video.created | 视频创建 |
video.processing | 开始渲染 |
video.completed | 渲染完成 |
video.failed | 渲染失败 |
batch.completed | 批量任务完成 |
Webhook请求
Headers:
X-Videomatic-Event: video.completed
X-Videomatic-Signature: sha256=...
Content-Type: application/json
Body:
{
"event": "video.completed",
"data": {
"id": "video_xyz789",
"status": "completed",
"file_url": "https://cdn.videomatic.com/videos/xyz789.mp4",
"created_at": "2025-01-09T10:00:00Z",
"completed_at": "2025-01-09T10:02:30Z"
},
"timestamp": 1704790950
}
验证签名
import hmac
import hashlib
def verify_webhook(payload, signature, secret):
"""验证Webhook签名"""
expected = hmac.new(
secret.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(
f"sha256={expected}",
signature
)
五、限流策略
限流规则
| 套餐 | 请求限制 | 并发渲染 |
|---|---|---|
| Free | 100次/天 | 1 |
| Starter | 1000次/天 | 5 |
| Pro | 10000次/天 | 20 |
| Enterprise | 无限制 | 自定义 |
限流响应
状态码: 429 Too Many Requests
响应:
{
"error": {
"code": "rate_limit_exceeded",
"message": "API调用次数超限",
"retry_after": 3600
}
}
Headers:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1704794550
六、错误处理
HTTP状态码
| 状态码 | 说明 |
|---|---|
| 200 | 成功 |
| 201 | 创建成功 |
| 400 | 请求参数错误 |
| 401 | 未授权 |
| 403 | 禁止访问 |
| 404 | 资源不存在 |
| 429 | 请求过多 |
| 500 | 服务器错误 |
错误响应格式
{
"error": {
"code": "invalid_parameter",
"message": "template_id is required",
"field": "template_id"
}
}
错误码
| 错误码 | 说明 |
|---|---|
invalid_parameter | 参数错误 |
unauthorized | 未授权 |
quota_exceeded | 配额超限 |
template_not_found | 模板不存在 |
render_failed | 渲染失败 |
invalid_data | 数据格式错误 |
七、最佳实践
1. 错误重试
import time
def create_video_with_retry(client, params, max_retries=3):
"""带重试的视频创建"""
for attempt in range(max_retries):
try:
return client.videos.create(**params)
except Exception as e:
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt) # 指数退避
2. 批量优化
# ❌ 不推荐:循环调用
for item in items:
client.videos.create(template_id=..., data=item)
# ✅ 推荐:批量创建
client.videos.batch_create(
template_id=...,
data_source=items
)
3. Webhook vs 轮询
# ❌ 不推荐:频繁轮询
while True:
video = client.videos.get(video_id)
if video.status == 'completed':
break
time.sleep(5)
# ✅ 推荐:使用Webhook
# 在Webhook回调中处理完成事件
八、完整示例
电商批量视频生成
from videomatic import VideoMatic
import pandas as pd
# 初始化
client = VideoMatic(api_key="your_api_key")
# 读取商品数据
df = pd.read_excel("products.xlsx")
# 批量创建
batch = client.videos.batch_create(
template_id="ecommerce_showcase_v1",
data=df.to_dict('records'),
webhook_url="https://yourapp.com/webhook"
)
print(f"批量任务ID: {batch.id}")
print(f"共 {batch.total} 个视频")
# 监控进度(可选)
for progress in batch.watch_progress():
print(f"已完成: {progress['completed']}/{progress['total']}")
if progress['failed'] \> 0:
print(f"失败: {progress['failed']}")
# 下载所有视频
videos = batch.get_completed_videos()
for video in videos:
video.download(f"output/{video.id}.mp4")
九、API变更日志
| 版本 | 日期 | 变更 |
|---|---|---|
| v1.0 | 2025-01-01 | 初始版本 |
| v1.1 | 2025-02-01 | 新增批量创建 |
| v1.2 | 2025-03-01 | 新增Webhook |
更新记录
- 2025-01-09: 初始版本,完成API完整文档