@androettop/synthesia-sdk
v1.2.0
Published
TypeScript SDK for Synthesia API
Maintainers
Readme
Synthesia TypeScript SDK
A comprehensive TypeScript SDK for the Synthesia API that allows you to create AI-generated videos programmatically.
Features
- 🎥 Video Creation: Create videos with custom scripts, avatars, and backgrounds
- 📋 Template Support: Use Synthesia templates for quick video generation
- 🔗 Webhook Management: Set up webhooks to receive video processing notifications
- 📁 Asset Upload: Upload audio, image, and video assets
- 🔒 Type Safety: Full TypeScript support with comprehensive type definitions
- ✅ Comprehensive Testing: Complete test suite for all endpoints
- 🚨 Error Handling: Robust error handling with custom error types
- ⚡ Rate Limit Handling: Built-in rate limit information tracking
📖 Documentation
For comprehensive documentation, guides, and examples, visit: https://androettop.github.io/synthesia-sdk
Installation
npm install @androettop/synthesia-sdkQuick Start
import { Synthesia } from "@androettop/synthesia-sdk";
const synthesia = new Synthesia({
apiKey: "your-api-key-here",
});
// Create a simple video
const result = await synthesia.videos.createVideo({
input: [{
scriptText: "Hello world! This is my first Synthesia video.",
avatar: "anna_costume1_cameraA",
background: "green_screen"
}],
title: "My First Video",
visibility: "private",
aspectRatio: "16:9",
test: true, // Use test mode for development
});
if (result.error) {
console.error("Error:", result.error.message);
} else {
console.log("Video created:", result.data.id);
}API Reference
Configuration
const synthesia = new Synthesia({
apiKey: "your-api-key", // Required: Your Synthesia API key
baseURL: "https://custom.api", // Optional: Custom API base URL
});Videos API
Create Video
const result = await synthesia.videos.createVideo({
input: [{
scriptText: "Your script text",
avatar: "anna_costume1_cameraA",
background: "green_screen"
}],
title: "Video Title",
visibility: "private", // Required: 'public' | 'private'
aspectRatio: "16:9", // Required: aspect ratio
test: true, // Optional: test mode
callbackId: "callback-id", // Optional: for tracking
});List Videos
const result = await synthesia.videos.listVideos({
source: "workspace", // Optional: 'workspace' | 'my_videos' | 'shared_with_me'
limit: 10, // Optional: number of videos to return (max 100)
offset: 0, // Optional: pagination offset
});Get Video
const result = await synthesia.videos.getVideo("video-id");Update Video
const result = await synthesia.videos.updateVideo("video-id", {
title: "New Title",
visibility: "public",
});Delete Video
const result = await synthesia.videos.deleteVideo("video-id");Create Video from Template
const result = await synthesia.videos.createVideoFromTemplate(
"template-id",
{
// Template variables
name: "John Doe",
company: "Acme Corp",
},
{
title: "Personalized Video",
test: true,
}
);Templates API
List Templates
const result = await synthesia.templates.listTemplates({
source: "synthesia", // Optional: 'synthesia' | 'workspace'
});Get Template
const result = await synthesia.templates.getTemplate("template-id");Webhooks API
Create Webhook
const result = await synthesia.webhooks.createWebhook({
url: "https://your-app.com/webhook",
events: ["video.completed", "video.failed"],
secret: "your-webhook-secret", // Optional but recommended
});List Webhooks
const result = await synthesia.webhooks.listWebhooks();Get Webhook
const result = await synthesia.webhooks.getWebhook("webhook-id");Update Webhook
// Note: Update webhook is not available in the API
// Use delete and create instead
await synthesia.webhooks.deleteWebhook("webhook-id");
const result = await synthesia.webhooks.createWebhook({
url: "https://your-app.com/webhook",
events: ["video.completed"],
});Delete Webhook
const result = await synthesia.webhooks.deleteWebhook("webhook-id");Uploads API
Upload Asset
const file = Buffer.from("image data");
const result = await synthesia.uploads.uploadAsset({
file,
contentType: "image/png",
});Upload Script Audio
const audioBuffer = Buffer.from("mp3 audio data");
const result = await synthesia.uploads.uploadScriptAudio(audioBuffer);Error Handling
The SDK provides comprehensive error handling with custom error types:
import {
SynthesiaSDKError,
ValidationError,
AuthenticationError,
} from "@androettop/synthesia-sdk";
try {
const result = await synthesia.videos.createVideo({
title: "Test Video",
});
if (result.error) {
throw SynthesiaSDKError.fromResponse(result.error);
}
} catch (error) {
if (error instanceof AuthenticationError) {
console.error("Authentication failed:", error.message);
} else if (error instanceof ValidationError) {
console.error("Validation error:", error.message, error.details);
} else if (error instanceof SynthesiaSDKError) {
console.error("Synthesia API error:", error.message);
if (error.isRateLimited()) {
console.log("Rate limited, retry after:", error.retryAfter);
}
}
}Utilities
The SDK includes utility functions for common tasks:
import { SynthesiaUtils } from "@androettop/synthesia-sdk";
// Validate webhook signatures
const isValid = SynthesiaUtils.validateWebhookSignature(
payload,
signature,
secret
);
// Poll video status until completion
const finalStatus = await SynthesiaUtils.pollVideoStatus(
(id) => synthesia.videos.getVideo(id),
"video-id",
{
maxAttempts: 60,
intervalMs: 10000,
onStatusUpdate: (status) => console.log("Status:", status),
}
);Rate Limiting
Track rate limit information:
const result = await synthesia.videos.createVideo(videoData);
const rateLimitInfo = synthesia.getRateLimitInfo();
if (rateLimitInfo) {
console.log("Rate limit:", rateLimitInfo.limit);
console.log("Remaining:", rateLimitInfo.remaining);
console.log("Reset at:", rateLimitInfo.resetAt);
}Webhook Handling
Example webhook handler:
import { SynthesiaUtils } from "@androettop/synthesia-sdk";
import express from "express";
const app = express();
app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
const payload = req.body.toString();
const signature = req.headers["x-signature"] as string;
const secret = "your-webhook-secret";
if (!SynthesiaUtils.validateWebhookSignature(payload, signature, secret)) {
return res.status(401).send("Invalid signature");
}
const data = JSON.parse(payload);
switch (data.event) {
case "video.completed":
console.log("Video completed:", data.video.id);
// Handle video completion
break;
case "video.failed":
console.log("Video failed:", data.video.id);
// Handle video failure
break;
}
res.status(200).send("OK");
});Examples
Check the examples/ directory for complete usage examples:
basic-usage.ts- Basic video creation and managementtemplate-usage.ts- Working with templateswebhook-usage.ts- Setting up and handling webhooks
Development
# Install dependencies
npm install
# Run tests
npm test
# Build the project
npm run build
# Run linting
npm run lintAPI Coverage
This SDK implements all available Synthesia API endpoints:
Videos API ✅
- [x] Create Video
- [x] List Videos
- [x] Get Video
- [x] Update Video
- [x] Delete Video
- [x] Create Video from Template
Templates API ✅
- [x] List Templates
- [x] Get Template
Webhooks API ✅
- [x] Create Webhook
- [x] List Webhooks
- [x] Get Webhook
- [x] Update Webhook
- [x] Delete Webhook
Upload API ✅
- [x] Upload Assets
- [x] Upload Script Audio
- [x] Upload Images (via uploadImage helper)
- [x] Upload Videos (via uploadVideo helper)
License
MIT License - see LICENSE file for details.
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Support
For issues with this SDK, please create an issue on GitHub.
For Synthesia API questions, consult the official documentation.
