> ## Documentation Index
> Fetch the complete documentation index at: https://docs.slidevid.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate Video from Template

> Create personalized videos using templates with scene-based variable replacement

## Overview

Generate videos from templates by providing variable values for each scene. This is perfect for creating personalized video content at scale.

## How Templates Work

Templates in SlideVid use **scenes** - each scene has a script with `{{variables}}` that you replace:

1. **Get template details** to see scenes and variables
2. **Prepare your data** with values for each variable per scene
3. **Generate video** with the `templateId` and `scenes` array

### Request Body

<ParamField body="type" type="string" required>
  Video type (must match template type). Use `class` for template-based videos.
</ParamField>

<ParamField body="templateId" type="string" required>
  The template ID to use (1-20 characters)
</ParamField>

<ParamField body="title" type="string" required>
  Video title (1-100 characters)
</ParamField>

<ParamField body="caption" type="boolean" required>
  Enable auto-generated captions
</ParamField>

<ParamField body="language" type="string" required>
  Language code for the video (max 2 characters). Example: `en`, `es`, `fr`
</ParamField>

<ParamField body="scenes" type="array" required>
  Array of scenes (1-20 scenes). Each scene contains:

  <Expandable title="Scene Object">
    <ParamField body="script" type="string" required>
      Script text for this scene (1-5000 characters)
    </ParamField>

    <ParamField body="avatar" type="object">
      Avatar configuration for this scene

      <Expandable title="Avatar Object">
        <ParamField body="id" type="string">
          Avatar ID (nullable)
        </ParamField>

        <ParamField body="topLeft" type="object">
          Top-left position with `x` and `y` coordinates
        </ParamField>

        <ParamField body="bottomRight" type="object">
          Bottom-right position with `x` and `y` coordinates
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="variables" type="array">
      Variables to replace in the scene (max 20 per scene)

      <Expandable title="Variable Object">
        <ParamField body="key" type="string" required>
          Variable key (1-100 characters)
        </ParamField>

        <ParamField body="value" type="string" required>
          Variable value (1-2000 characters)
        </ParamField>

        <ParamField body="type" type="string" default="text">
          Variable type: `text` or `media`
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="voice" type="string">
      Voice ID for this scene (max 20 characters)
    </ParamField>

    <ParamField body="voiceSettings" type="object">
      Voice settings for this scene

      <Expandable title="Voice Settings Object">
        <ParamField body="speed" type="number">
          Speech speed (0.7-1.2)
        </ParamField>

        <ParamField body="stability" type="number">
          Voice stability (0-1)
        </ParamField>

        <ParamField body="similarityBoost" type="number">
          Similarity boost (0-1)
        </ParamField>

        <ParamField body="style" type="number">
          Style intensity (0-1)
        </ParamField>

        <ParamField body="useSpeakerBoost" type="boolean">
          Enable speaker boost
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="webhook" type="string">
  URL to receive completion notification (max 500 characters)
</ParamField>

<ParamField body="metadata" type="object">
  Custom data to pass through to webhook responses. Use this to correlate videos with your internal systems (e.g., course IDs, user IDs, order numbers). Maximum size: 5KB.

  ```json theme={null}
  {
    "courseId": "python-101",
    "lessonId": "lesson-5",
    "studentId": "student-123"
  }
  ```
</ParamField>

## Scene Structure

Each scene in the `scenes` array must include:

<ResponseField name="script" type="string" required>
  The script for this scene (can include `{{variables}}`)
</ResponseField>

<ResponseField name="variables" type="array" required>
  Array of `{key, type, value}` pairs to replace in the script

  ```json theme={null}
  [
    {"key": "name", "type": "text", "value": "John Doe"},
    {"key": "product", "type": "text", "value": "AI Video Tool"}
  ]
  ```
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.slidevid.ai/v1/project/create" \
    -H "Content-Type: application/json" \
    -H "x-api-key: your_api_key_here" \
    -d '{
      "type": "class",
      "templateId": "cmha385y900012yhv17qfmase",
      "title": "My Video from Template",
      "caption": true,
      "language": "en",
      "scenes": [
        {
          "script": "Welcome to our presentation. Today we'\''ll discuss the key features of our product.",
          "avatar": {
            "id": "1",
            "topLeft": { "x": 0, "y": 0 },
            "bottomRight": { "x": 100, "y": 100 }
          },
          "variables": [
            {"key": "name", "type": "text", "value": "Juan Montiel"},
            {"key": "description_small", "type": "text", "value": "Welcome to our presentation."},
            {"key": "background", "type": "media", "value": "https://example.com/background.jpg"}
          ],
          "voice": "voice_abc123"
        },
        {
          "script": "Our platform offers seamless integration with your existing tools and workflows.",
          "variables": [
            {"key": "module_number", "type": "text", "value": "1"}
          ],
          "voice": "voice_abc123"
        }
      ],
      "webhook": "https://yoursite.com/webhook",
      "metadata": {
        "courseId": "python-101",
        "lessonId": "lesson-5"
      }
    }'
  ```

  ```javascript Node.js theme={null}
  const API_KEY = process.env.SLIDEVID_API_KEY;
  const TEAM_ID = process.env.SLIDEVID_TEAM_ID;
  const templateId = 'cmha385y900012yhv17qfmase';

  // 1. Get template details to know what variables are needed
  const templateRes = await fetch(`https://api.slidevid.ai/v1/template/${templateId}`, {
    headers: { 'x-api-key': API_KEY }
  });
  const template = await templateRes.json().data;

  // 2. Prepare scenes with your data
  const scenes = template.scenes.map((scene, index) => {
    // Your custom data per scene
    const sceneData = {
      name: 'Juan Montiel',
      description_small: scene.script,
      module_number: String(index + 1)
    };

    // Map to variables array
    const variables = scene.variables.map(v => ({
      key: v.key,
      type: v.type,
      value: sceneData[v.key] || v.value
    }));

    return {
      script: scene.script,
      variables: variables,
      voice: 'voice_abc123'
    };
  });

  // 3. Generate video
  const response = await fetch('https://api.slidevid.ai/v1/project/create', {
    method: 'POST',
    headers: {
      'x-api-key': API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      type: template.type,
      templateId: templateId,
      title: 'My Video from Template',
      caption: true,
      language: 'en',
      scenes: scenes,
      webhook: 'https://yoursite.com/webhook',
      metadata: {
        courseId: 'python-101',
        lessonId: 'lesson-5'
      }
    })
  });

  const { projectId } = await response.json().data;
  console.log('Video created:', projectId);
  ```

  ```python Python theme={null}
  import requests
  import os

  API_KEY = os.getenv('SLIDEVID_API_KEY')
  TEAM_ID = os.getenv('SLIDEVID_TEAM_ID')
  template_id = 'cmha385y900012yhv17qfmase'

  # 1. Get template details
  template_res = requests.get(
      f'https://api.slidevid.ai/v1/template/{template_id}',
      headers={'x-api-key': API_KEY}
  )
  template = template_res.json()['data']

  # 2. Prepare scenes with your data
  customer_data = {
      'name': 'Juan Montiel',
      'description_small': 'key features of our product',
      'module_number': '1'
  }

  scenes = []
  for scene in template['scenes']:
      variables = [
          {
              'key': v['key'],
              'type': v['type'],
              'value': customer_data.get(v['key'], v['value'])
          }
          for v in scene['variables']
      ]
      scenes.append({
          'script': scene['script'],
          'variables': variables,
          'voice': 'voice_abc123'
      })

  # 3. Generate video
  response = requests.post(
      'https://api.slidevid.ai/v1/project/create',
      headers={
          'x-api-key': API_KEY,
          'Content-Type': 'application/json'
      },
      json={
          'type': template['type'],
          'templateId': template_id,
          'title': 'My Video from Template',
          'caption': True,
          'language': 'en',
          'scenes': scenes,
          'webhook': 'https://yoursite.com/webhook',
          'metadata': {
              'courseId': 'python-101',
              'lessonId': 'lesson-5'
          }
      }
  )

  project_id = response.json()['data']['projectId']
  print(f'Video created: {project_id}')
  ```
</RequestExample>

<ResponseExample>
  ```json Success Response theme={null}
  {
    "success": true,
    "message": "Project created successfully",
    "data": {
      "projectId": "proj_new_xyz789",
      "status": "processing",
    }
  }
  ```

  ```json Error Response theme={null}
  {
    "success": false,
    "message": "Missing required variables for scene 1: name, description_small"
  }
  ```
</ResponseExample>

## Bulk Generation Example

Generate personalized videos for multiple customers:

```javascript Bulk Generation theme={null}
const API_KEY = process.env.SLIDEVID_API_KEY;
const TEAM_ID = process.env.SLIDEVID_TEAM_ID;

const template = await getTemplateDetails(templateId);

const customers = [
  { id: 'cust_1', name: 'John Doe', company: 'Acme Corp', plan: 'Pro' },
  { id: 'cust_2', name: 'Jane Smith', company: 'TechStart', plan: 'Enterprise' },
  { id: 'cust_3', name: 'Bob Wilson', company: 'Digital Inc', plan: 'Starter' }
];

for (const customer of customers) {
  // Map template scenes with customer data
  const scenes = template.scenes.map(scene => ({
    script: scene.script,
    avatar: { id: "1" },
    variables: scene.variables.map(v => ({
      key: v.key,
      type: v.type,
      value: customer[v.key] || v.value
    })),
    voice: 'voice_abc123'
  }));

  // Generate video
  const response = await fetch('https://api.slidevid.ai/v1/project/create', {
    method: 'POST',
    headers: {
      'x-api-key': API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      type: template.type,
      templateId: templateId,
      title: `Video for ${customer.name}`,
      caption: true,
      language: 'en',
      scenes: scenes,
      webhook: 'https://yoursite.com/webhook',
      metadata: {
        customerId: customer.id,
        customerName: customer.name
      }
    })
  });

  console.log(`Video created for ${customer.name}`);

  // Rate limiting - wait 1 second between requests
  await new Promise(resolve => setTimeout(resolve, 1000));
}
```

## Variable Replacement Rules

<AccordionGroup>
  <Accordion title="Variable Format" icon="brackets-curly">
    Variables in scripts use double curly brackets: `{{variable_name}}`

    ```
    "Hello {{first_name}}! Welcome to {{company_name}}."
    ```
  </Accordion>

  <Accordion title="Case Sensitive" icon="text">
    Variable names are case-sensitive:

    * `{{name}}` ≠ `{{Name}}`
    * `{{firstName}}` ≠ `{{firstname}}`
  </Accordion>

  <Accordion title="All Variables Required" icon="exclamation">
    You must provide values for **all** variables in each scene:

    ```json theme={null}
    // ❌ Will fail if scene has {{name}} and {{product}}
    "variables": [
      {"key": "name", "value": "John"}
    ]

    // ✅ Correct
    "variables": [
      {"key": "name", "value": "John"},
      {"key": "product", "value": "AI Tool"}
    ]
    ```
  </Accordion>

  <Accordion title="Empty Values" icon="circle-empty">
    Empty string values are allowed:

    ```json theme={null}
    {"key": "optional_field", "value": ""}
    ```

    This replaces `{{optional_field}}` with an empty string.
  </Accordion>
</AccordionGroup>

## Overriding Template Settings

You can override some template settings:

<Tabs>
  <Tab title="Captions">
    ```json theme={null}
    {
      "templateId": "...",
      "caption": true,
      "scenes": [...]
    }
    ```
  </Tab>

  <Tab title="Title">
    ```json theme={null}
    {
      "templateId": "...",
      "title": "Custom Video Title",  // Override name
      "scenes": [...]
    }
    ```
  </Tab>

  <Tab title="Metadata">
    ```json theme={null}
    {
      "templateId": "...",
      "metadata": {
        "orderId": "12345",
        "customerId": "cust_abc"
      },
      "scenes": [...]
    }
    ```
  </Tab>
</Tabs>

## Best Practices

<CardGroup cols={2}>
  <Card title="Validate First" icon="shield-check">
    Get template details and validate your data before generating
  </Card>

  <Card title="Use Webhooks" icon="webhook">
    Always provide webhook URLs for async notification
  </Card>

  <Card title="Rate Limiting" icon="gauge">
    Add delays between bulk requests (1 second recommended)
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Check for missing variables before generation
  </Card>
</CardGroup>

<Warning>
  **Missing Variables**: If any required variable is missing, the video generation will fail. Always validate your data against the template's variable requirements first.
</Warning>

## API Limits

| Limit                       | Value            |
| --------------------------- | ---------------- |
| Max scenes per project      | 20               |
| Max script length per scene | 5,000 characters |
| Max variables per scene     | 20               |
| Max variable key length     | 100 characters   |
| Max variable value length   | 2,000 characters |
| Max title length            | 200 characters   |
| Max webhook URL length      | 500 characters   |
| Max metadata size           | 5KB              |

## Related Endpoints

<CardGroup cols={3}>
  <Card title="Template Details" icon="info" href="/api-reference/template/details">
    Get template structure and variables
  </Card>

  <Card title="List Templates" icon="list" href="/api-reference/template/list">
    Browse available templates
  </Card>

  <Card title="List Videos" icon="video" href="/api-reference/video/list">
    View your generated videos
  </Card>
</CardGroup>
