Article
ai-videotext-to-videoavatarspythonapivideo-generationenterprise-contentautomation
Generate AI Avatar Videos with the Synthesia API
Programmatically create professional videos with AI avatars using the Synthesia API. This guide walks you through authenticating, scripting, and generating your first video with a complete Python starter script, ideal for scaling content production.
intermediate30 min5 steps
The play
- Get Your Synthesia API KeyTo use the Synthesia API, you need an API key, which is available on Enterprise plans. Find your key in your Synthesia account under 'Settings' > 'API Keys'. Store this key securely as it grants access to your account.
- Choose an Avatar and VoiceYou need to specify which avatar and voice to use. You can retrieve a list of available options by making GET requests to the `/v2/avatars` and `/v2/voices` endpoints. For this guide, we'll use a common avatar ('anna_costume1_cameraA') and voice ('en-US-Standard-C').
- Craft Your Video Request PayloadThe core of the API call is a JSON payload. It must contain `scriptText` and can specify `title`, `avatar`, `voice`, and `background`. The `scriptText` is where you write what the avatar will say.
- Trigger Video GenerationSend a POST request to the `/v2/videos` endpoint with your API key in the Authorization header and the JSON payload in the body. A successful request returns a `201 Created` status and a JSON object containing the new `id` for your video.
- Poll for Status and DownloadVideo generation is asynchronous. You must poll the `/v2/videos/{video_id}` endpoint until the `status` field changes from 'in_progress' to 'complete'. The final response will contain a `download` URL for your MP4 file.
Starter code
import requests
import time
import os
# --- Configuration ---
# Get your API key from Synthesia settings (Enterprise plan required)
API_KEY = os.getenv("SYNTHESIA_API_KEY", "YOUR_SYNTHESIA_API_KEY")
API_URL = "https://api.synthesia.io/v2"
# --- Video Script ---
VIDEO_PAYLOAD = {
"title": "API Welcome Video",
"scriptText": "Welcome to our platform! This video was generated programmatically using the Synthesia API. This allows us to create personalized content at scale.",
"avatar": "anna_costume1_cameraA",
"voice": "en-US-Standard-C",
"background": "off_white"
}
def create_video(api_key, payload):
"""Sends a request to create a new video."""
headers = {"Authorization": api_key, "Content-Type": "application/json"}
response = requests.post(f"{API_URL}/videos", headers=headers, json=payload)
response.raise_for_status() # Raises an exception for bad status codes
return response.json()['id']
def poll_for_video(api_key, video_id):
"""Polls the video status and returns the download URL when complete."""
headers = {"Authorization": api_key}
while True:
try:
response = requests.get(f"{API_URL}/videos/{video_id}", headers=headers)
response.raise_for_status()
status_data = response.json()
status = status_data.get('status')
print(f"Video ID '{video_id}' status: {status}")
if status == 'complete':
return status_data.get('download')
elif status == 'error':
raise Exception(f"Video generation failed: {status_data.get('errorReason')}")
# Wait for 20 seconds before polling again
time.sleep(20)
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e}")
break
if __name__ == "__main__":
if API_KEY == "YOUR_SYNTHESIA_API_KEY":
print("Error: Please replace 'YOUR_SYNTHESIA_API_KEY' with your actual Synthesia API key.")
else:
try:
print("Starting video generation...")
new_video_id = create_video(API_KEY, VIDEO_PAYLOAD)
print(f"Video creation initiated. Video ID: {new_video_id}")
print("\nPolling for video completion (this may take several minutes)...")
download_url = poll_for_video(API_KEY, new_video_id)
if download_url:
print(f"\nVideo generation complete!\nDownload your video here: {download_url}")
except requests.exceptions.RequestException as e:
print(f"An API request error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")