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

# Get Template by ID

> Retrieve detailed information about a specific video template using its unique identifier

## Overview

Retrieve comprehensive details about a specific video template using its unique identifier. This endpoint returns the complete template configuration, including scene structure, variables, voice-over settings, background music, and S3 storage URLs for project files.

<Note>
  You need a valid API key to use this endpoint. Get your API key from the [API Access page](https://app.pictory.ai/api-access) in your Pictory dashboard.
</Note>

***

## API Endpoint

```http theme={null}
GET https://api.pictory.ai/pictoryapis/v1/templates/{templateId}
```

***

## Request Parameters

### Path Parameters

<ParamField path="templateId" type="string" required>
  The unique identifier of the template to retrieve

  Example: `202512230204424435786014d42904bbc95813430789fe736`
</ParamField>

### Headers

<ParamField header="Authorization" type="string" required>
  API key for authentication (starts with `pictai_`)

  ```
  Authorization: YOUR_API_KEY
  ```
</ParamField>

***

## Response

The response contains detailed template information including configuration, scenes, variables, and media settings.

<ResponseField name="templateId" type="string">
  Unique identifier for the template
</ResponseField>

<ResponseField name="name" type="string">
  Name of the template
</ResponseField>

<ResponseField name="language" type="string">
  Language code of the template (e.g., `en` for English)
</ResponseField>

<ResponseField name="published" type="boolean">
  Indicates whether the template is published and available for use
</ResponseField>

<ResponseField name="depricated" type="boolean">
  Indicates whether the template has been deprecated (note: API uses "depricated" spelling)
</ResponseField>

<ResponseField name="backgroundMusic" type="object">
  Background music configuration

  <Expandable title="backgroundMusic properties">
    <ResponseField name="enabled" type="boolean">
      Whether background music is enabled for this template
    </ResponseField>

    <ResponseField name="musicUrl" type="string">
      URL to the background music track
    </ResponseField>

    <ResponseField name="volume" type="number">
      Music volume level (0.0 to 1.0)
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="voiceOver" type="object">
  Voice-over configuration

  <Expandable title="voiceOver properties">
    <ResponseField name="enabled" type="boolean">
      Whether voice-over is enabled for this template
    </ResponseField>

    <ResponseField name="aiVoices" type="array of objects">
      AI voice settings

      <Expandable title="aiVoice object">
        <ResponseField name="speaker" type="string">
          Voice speaker ID
        </ResponseField>

        <ResponseField name="speed" type="number">
          Voice speed percentage (100 = normal speed)
        </ResponseField>

        <ResponseField name="amplificationLevel" type="number">
          Voice amplification level
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="scenes" type="array of objects">
  Array of scene objects that define the template structure

  <Expandable title="scene object">
    <ResponseField name="sceneId" type="string">
      Unique identifier for the scene
    </ResponseField>

    <ResponseField name="subtitles" type="array of objects">
      Subtitle configurations for the scene

      <Expandable title="subtitle object">
        <ResponseField name="text" type="string">
          Subtitle text, may include template variables in `{{variableName}}` format
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="layers" type="array of arrays">
      Visual layers for the scene, organized as nested arrays

      <Expandable title="layer object">
        <ResponseField name="layerId" type="string">
          Unique identifier for the layer
        </ResponseField>

        <ResponseField name="type" type="string">
          Layer type (e.g., `text`, `image`, `video`)
        </ResponseField>

        <ResponseField name="text" type="string">
          Text content for text layers
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="variables" type="object">
  Template variables that can be customized when creating videos from this template. Keys are variable names, values are default values or placeholders.

  Example: `{"Name": "NAME", "Company": "COMPANY_NAME"}`
</ResponseField>

<ResponseField name="schemaVersion" type="string">
  Template schema version (e.g., `v2`, `v3`)
</ResponseField>

<ResponseField name="project" type="string">
  S3 URL to the complete project template JSON file
</ResponseField>

<ResponseField name="structure" type="string">
  S3 URL to the project template structure JSON file
</ResponseField>

***

## Response Examples

<ResponseExample>
  ```json 200 - Success theme={null}
  {
    "templateId": "202512230204424435786014d42904bbc95813430789fe736",
    "name": "Hello World Template",
    "language": "en",
    "published": true,
    "depricated": false,
    "backgroundMusic": {
      "enabled": true,
      "musicUrl": "https://tracks.melod.ie/track_versions/71/MEL106_09_1_Raw_Power_%28Full%29_Stefano_Mastronardi_stream.mp3",
      "volume": 0.1
    },
    "voiceOver": {
      "enabled": true,
      "aiVoices": [
        {
          "speaker": "3108",
          "speed": 100,
          "amplificationLevel": 0
        }
      ]
    },
    "scenes": [
      {
        "sceneId": "20251222191719950af11290d66804b7f97cad70cde355bcc",
        "subtitles": [
          {
            "text": "Hi {{Name}}, how are you doing today?"
          }
        ],
        "layers": [
          [
            {
              "layerId": "2025122211203035206c45618d2c74013a7022de479df95f2",
              "type": "text",
              "text": "Hello"
            }
          ]
        ]
      }
    ],
    "variables": {
      "Name": "NAME"
    },
    "schemaVersion": "v3",
    "project": "https://projects-prod.s3.us-east-2.amazonaws.com/project_templates/teams/aa46778d-7965-46e0-967d-b48ee5d6ead9/202512230204424435786014d42904bbc95813430789fe736.json",
    "structure": "https://projects-prod.s3.us-east-2.amazonaws.com/project_template_structures/teams/aa46778d-7965-46e0-967d-b48ee5d6ead9/202512230204424435786014d42904bbc95813430789fe736.json"
  }
  ```

  ```json 401 - Unauthorized theme={null}
  {
    "message": "Unauthorized"
  }
  ```

  ```json 404 - Not Found theme={null}
  {
    "message": "Template not found"
  }
  ```

  ```json 400 - Bad Request theme={null}
  {
    "code": "INVALID_REQUEST",
    "message": "Invalid template ID"
  }
  ```
</ResponseExample>

***

## Code Examples

<Tip>
  Replace `YOUR_API_KEY` with your actual API key that starts with `pictai_`
</Tip>

<CodeGroup>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://api.pictory.ai/pictoryapis/v1/templates/YOUR_TEMPLATE_ID' \
    --header 'Authorization: YOUR_API_KEY' \
    --header 'accept: application/json' | python -m json.tool
  ```

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

  template_id = "202512230204424435786014d42904bbc95813430789fe736"
  url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"

  headers = {
      "Authorization": "YOUR_API_KEY",
      "accept": "application/json"
  }

  response = requests.get(url, headers=headers)
  template = response.json()

  # Print template information
  print(f"Template: {template['name']}")
  print(f"  ID: {template['templateId']}")
  print(f"  Language: {template['language']}")
  print(f"  Published: {template['published']}")
  print(f"  Schema Version: {template['schemaVersion']}")
  print(f"  Variables: {list(template.get('variables', {}).keys())}")
  print(f"  Scenes: {len(template['scenes'])}")
  ```

  ```javascript JavaScript theme={null}
  const templateId = '202512230204424435786014d42904bbc95813430789fe736';
  const response = await fetch(
    `https://api.pictory.ai/pictoryapis/v1/templates/${templateId}`,
    {
      method: 'GET',
      headers: {
        'Authorization': 'YOUR_API_KEY',
        'accept': 'application/json'
      }
    }
  );

  const template = await response.json();

  // Print template information
  console.log(`Template: ${template.name}`);
  console.log(`  ID: ${template.templateId}`);
  console.log(`  Language: ${template.language}`);
  console.log(`  Published: ${template.published}`);
  console.log(`  Schema Version: ${template.schemaVersion}`);
  console.log(`  Variables: ${Object.keys(template.variables || {}).join(', ')}`);
  console.log(`  Scenes: ${template.scenes.length}`);
  ```
</CodeGroup>

***

## Usage Notes

<Tip>
  Use this endpoint to retrieve template details before using it to create videos or before updating the template configuration.
</Tip>

<Note>
  **Template Variables**: The `variables` object shows all customizable placeholders in the template. These can be replaced with actual values when creating videos from the template.
</Note>

<Note>
  **S3 URLs**: The `project` and `structure` URLs point to S3 storage containing the complete template configuration and structure data.
</Note>

***

## Common Use Cases

### 1. Retrieve Template Details

Get complete information about a specific template:

```python theme={null}
import requests

def get_template_details(template_id, api_key):
    """
    Retrieve detailed information about a template
    """
    url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"
    headers = {"Authorization": api_key}

    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        template = response.json()

        print(f"Template: {template['name']}")
        print(f"Language: {template['language']}")
        print(f"Schema: {template['schemaVersion']}")
        print(f"\nSettings:")
        print(f"  Background Music: {'Enabled' if template.get('backgroundMusic', {}).get('enabled') else 'Disabled'}")
        print(f"  Voice Over: {'Enabled' if template.get('voiceOver', {}).get('enabled') else 'Disabled'}")
        print(f"\nStructure:")
        print(f"  Scenes: {len(template['scenes'])}")
        print(f"  Variables: {', '.join(template.get('variables', {}).keys())}")

        return template
    else:
        print(f"Error: {response.status_code}")
        return None

# Example usage
template = get_template_details("YOUR_TEMPLATE_ID", "YOUR_API_KEY")
```

### 2. Extract Template Variables

Identify all customizable variables in a template:

```javascript theme={null}
async function getTemplateVariables(templateId, apiKey) {
  const response = await fetch(
    `https://api.pictory.ai/pictoryapis/v1/templates/${templateId}`,
    {
      headers: { 'Authorization': `${apiKey}` }
    }
  );

  const template = await response.json();

  // Extract variables from template
  const variables = template.variables || {};

  console.log(`Template: ${template.name}`);
  console.log(`\nCustomizable Variables:`);

  Object.entries(variables).forEach(([key, defaultValue]) => {
    console.log(`  - ${key}: ${defaultValue}`);
  });

  // Also check for variables in subtitles
  const subtitleVariables = new Set();
  template.scenes.forEach(scene => {
    scene.subtitles?.forEach(subtitle => {
      const matches = subtitle.text.match(/\{\{(\w+)\}\}/g);
      if (matches) {
        matches.forEach(match => {
          const varName = match.replace(/\{\{|\}\}/g, '');
          subtitleVariables.add(varName);
        });
      }
    });
  });

  console.log(`\nVariables used in subtitles:`);
  subtitleVariables.forEach(v => console.log(`  - ${v}`));

  return {
    defined: variables,
    usedInSubtitles: Array.from(subtitleVariables)
  };
}

// Example usage
const vars = await getTemplateVariables('YOUR_TEMPLATE_ID', 'YOUR_API_KEY');
```

### 3. Analyze Template Structure

Analyze and report on template structure:

```python theme={null}
import requests

def analyze_template_structure(template_id, api_key):
    """
    Analyze template structure and generate report
    """
    url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"
    headers = {"Authorization": api_key}

    response = requests.get(url, headers=headers)
    template = response.json()

    # Analyze structure
    analysis = {
        'name': template['name'],
        'language': template['language'],
        'schema_version': template['schemaVersion'],
        'total_scenes': len(template['scenes']),
        'has_background_music': template.get('backgroundMusic', {}).get('enabled', False),
        'has_voice_over': template.get('voiceOver', {}).get('enabled', False),
        'variables': list(template.get('variables', {}).keys()),
        'scene_details': []
    }

    # Analyze each scene
    for i, scene in enumerate(template['scenes'], 1):
        scene_info = {
            'scene_number': i,
            'scene_id': scene['sceneId'],
            'subtitle_count': len(scene.get('subtitles', [])),
            'layer_count': sum(len(layer_group) for layer_group in scene.get('layers', []))
        }
        analysis['scene_details'].append(scene_info)

    # Print report
    print(f"=== Template Analysis: {analysis['name']} ===\n")
    print(f"Language: {analysis['language']}")
    print(f"Schema: {analysis['schema_version']}")
    print(f"Total Scenes: {analysis['total_scenes']}")
    print(f"Background Music: {'Yes' if analysis['has_background_music'] else 'No'}")
    print(f"Voice Over: {'Yes' if analysis['has_voice_over'] else 'No'}")
    print(f"Variables: {', '.join(analysis['variables']) if analysis['variables'] else 'None'}")

    print(f"\nScene Breakdown:")
    for scene in analysis['scene_details']:
        print(f"  Scene {scene['scene_number']}:")
        print(f"    Subtitles: {scene['subtitle_count']}")
        print(f"    Layers: {scene['layer_count']}")

    return analysis

# Example usage
analysis = analyze_template_structure("YOUR_TEMPLATE_ID", "YOUR_API_KEY")
```

### 4. Compare Template Versions

Compare two template versions:

```python theme={null}
import requests

def compare_templates(template_id_1, template_id_2, api_key):
    """
    Compare two templates and identify differences
    """
    headers = {"Authorization": api_key}
    url = "https://api.pictory.ai/pictoryapis/v1/templates/"

    # Fetch both templates
    template1 = requests.get(f"{url}{template_id_1}", headers=headers).json()
    template2 = requests.get(f"{url}{template_id_2}", headers=headers).json()

    differences = []

    # Compare basic properties
    if template1['name'] != template2['name']:
        differences.append(f"Name: '{template1['name']}' vs '{template2['name']}'")

    if template1['language'] != template2['language']:
        differences.append(f"Language: '{template1['language']}' vs '{template2['language']}'")

    if len(template1['scenes']) != len(template2['scenes']):
        differences.append(f"Scene count: {len(template1['scenes'])} vs {len(template2['scenes'])}")

    # Compare variables
    vars1 = set(template1.get('variables', {}).keys())
    vars2 = set(template2.get('variables', {}).keys())

    if vars1 != vars2:
        added = vars2 - vars1
        removed = vars1 - vars2
        if added:
            differences.append(f"Variables added: {', '.join(added)}")
        if removed:
            differences.append(f"Variables removed: {', '.join(removed)}")

    # Print comparison
    print(f"=== Template Comparison ===")
    print(f"Template 1: {template1['name']} ({template_id_1})")
    print(f"Template 2: {template2['name']} ({template_id_2})")

    if differences:
        print(f"\nDifferences found:")
        for diff in differences:
            print(f"  - {diff}")
    else:
        print("\nNo significant differences found")

    return differences

# Example usage
compare_templates("TEMPLATE_ID_1", "TEMPLATE_ID_2", "YOUR_API_KEY")
```

### 5. Download Template Configuration

Download and save complete template configuration:

```javascript theme={null}
async function downloadTemplateConfiguration(templateId, apiKey) {
  const response = await fetch(
    `https://api.pictory.ai/pictoryapis/v1/templates/${templateId}`,
    {
      headers: { 'Authorization': `${apiKey}` }
    }
  );

  const template = await response.json();

  // Create backup object
  const backup = {
    exportDate: new Date().toISOString(),
    templateData: template
  };

  // In Node.js, save to file
  const fs = require('fs');
  const filename = `template_${templateId}_${Date.now()}.json`;

  fs.writeFileSync(filename, JSON.stringify(backup, null, 2));

  console.log(`Template configuration saved to ${filename}`);

  // Also download project and structure files if needed
  if (template.project) {
    console.log(`Project URL: ${template.project}`);
  }
  if (template.structure) {
    console.log(`Structure URL: ${template.structure}`);
  }

  return backup;
}

// Example usage
await downloadTemplateConfiguration('YOUR_TEMPLATE_ID', 'YOUR_API_KEY');
```

### 6. Validate Template Before Use

Validate template configuration before creating videos:

```python theme={null}
import requests

def validate_template(template_id, api_key):
    """
    Validate template before using it to create videos
    """
    url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"
    headers = {"Authorization": api_key}

    try:
        response = requests.get(url, headers=headers)

        if response.status_code != 200:
            return False, f"Failed to fetch template: {response.status_code}"

        template = response.json()

        # Validation checks
        issues = []

        # Check if published
        if not template.get('published'):
            issues.append("Template is not published")

        # Check if deprecated
        if template.get('depricated'):
            issues.append("Template is deprecated")

        # Check for scenes
        if not template.get('scenes'):
            issues.append("Template has no scenes")

        # Check for empty variables
        variables = template.get('variables', {})
        if variables and any(not v for v in variables.values()):
            issues.append("Template has empty variable placeholders")

        # Report results
        if issues:
            print(f"Template validation failed:")
            for issue in issues:
                print(f"  ✗ {issue}")
            return False, issues
        else:
            print(f"✓ Template '{template['name']}' is valid and ready to use")
            return True, None

    except Exception as e:
        return False, f"Error validating template: {str(e)}"

# Example usage
is_valid, issues = validate_template("YOUR_TEMPLATE_ID", "YOUR_API_KEY")
```

***

## Best Practices

### Template Inspection

1. **Retrieve Before Update**: Always fetch the template details before updating to understand the current structure
2. **Validate Configuration**: Check that the template is published and not deprecated before using it
3. **Understand Variables**: Review all variables and their default values before creating videos
4. **Check Schema Version**: Be aware of the schema version as it affects available features

### Performance Tips

* Cache template details locally to reduce API calls
* Only fetch template details when needed (e.g., before creating videos or updating)
* Use the template list endpoint to get basic info, then fetch details only for selected templates
* Store frequently used template configurations locally

***

## Related Endpoints

* [Get Templates](/api-reference/templates/get-templates) - List all available templates
* [Update Template](/api-reference/templates/update-template) - Modify template configuration
* [Create Template](/api-reference/templates/create-template) - Create a new template
