> ## 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.

# Update Template

> Update the scene configuration of an existing video template

## Overview

Update the scene structure and content of an existing video template. This endpoint allows you to modify the template's scene array, which defines the video's structure, content, and visual elements.

<Warning>
  **Template Modification**: Updating a template affects all future videos created from it. Existing videos created from this template will not be affected.
</Warning>

<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}
PUT 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 update

  Example: `202512230204424435786014d42904bbc95813430789fe736`
</ParamField>

### Headers

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

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

### Body Parameters

<ParamField body="scenes" type="array of objects" required>
  Array of scene objects that define the template structure. Each scene represents a segment in the video template with its own content, visuals, and timing.

  <Expandable title="scene object structure">
    The exact structure of scene objects should match the scene format used in Pictory projects. Common fields include:

    * `text`: The text content for the scene
    * `duration`: Scene duration in seconds
    * `image`: Background visual URL or reference
    * `voiceOver`: Voice-over configuration
    * `settings`: Scene-specific settings
  </Expandable>
</ParamField>

***

## Response

<ResponseField name="success" type="boolean">
  Indicates whether the update was successful
</ResponseField>

<ResponseField name="message" type="string">
  Confirmation message about the update
</ResponseField>

<ResponseField name="templateId" type="string">
  The ID of the updated template
</ResponseField>

***

## Response Examples

<ResponseExample>
  ```json 200 - Success theme={null}
  {
    "success": true,
    "message": "Template updated successfully",
    "templateId": "202512230204424435786014d42904bbc95813430789fe736"
  }
  ```

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

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

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

***

## Code Examples

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

<CodeGroup>
  ```bash cURL theme={null}
  # Update template with new scenes
  curl --request PUT \
    --url 'https://api.pictory.ai/pictoryapis/v1/templates/YOUR_TEMPLATE_ID' \
    --header 'Authorization: YOUR_API_KEY' \
    --header 'Content-Type: application/json' \
    --header 'accept: application/json' \
    --data '{
      "scenes": [
        {
          "text": "Introduction scene with updated content",
          "duration": 5
        },
        {
          "text": "Main content scene",
          "duration": 8
        }
      ]
    }' | 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",
      "Content-Type": "application/json",
      "accept": "application/json"
  }

  # Define updated scenes
  updated_scenes = [
      {
          "text": "Introduction scene with updated content",
          "duration": 5
      },
      {
          "text": "Main content scene",
          "duration": 8
      }
  ]

  response = requests.put(url, headers=headers, json={"scenes": updated_scenes})
  result = response.json()

  if result.get('success'):
      print(f"Template {template_id} updated successfully")
  else:
      print(f"Failed to update template: {result.get('message')}")
  ```

  ```javascript JavaScript theme={null}
  const templateId = '202512230204424435786014d42904bbc95813430789fe736';
  const url = `https://api.pictory.ai/pictoryapis/v1/templates/${templateId}`;

  // Define updated scenes
  const updatedScenes = [
    {
      text: 'Introduction scene with updated content',
      duration: 5
    },
    {
      text: 'Main content scene',
      duration: 8
    }
  ];

  const response = await fetch(url, {
    method: 'PUT',
    headers: {
      'Authorization': 'YOUR_API_KEY',
      'Content-Type': 'application/json',
      'accept': 'application/json'
    },
    body: JSON.stringify({ scenes: updatedScenes })
  });

  const result = await response.json();

  if (result.success) {
    console.log(`Template ${templateId} updated successfully`);
  } else {
    console.log(`Failed to update template: ${result.message}`);
  }
  ```
</CodeGroup>

***

## Usage Notes

<Warning>
  **Test Before Production**: Always test template updates with non-production templates first to ensure the scene structure is valid and produces the expected results.
</Warning>

<Note>
  **Scene Structure**: The scenes array should match the structure used in Pictory projects. Refer to the [Update Project](/api-reference/projects/update-project) endpoint documentation for scene object examples.
</Note>

<Tip>
  **Version Control**: Consider keeping backup copies of template configurations before making updates, especially for templates actively used in production.
</Tip>

***

## Common Use Cases

### 1. Update Template Text Content

Modify the text content across all scenes in a template:

```python theme={null}
import requests

def update_template_text(template_id, new_scenes, api_key):
    """
    Update template with new scene content
    """
    url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"
    headers = {
        "Authorization": api_key,
        "Content-Type": "application/json"
    }

    payload = {"scenes": new_scenes}

    response = requests.put(url, headers=headers, json=payload)
    result = response.json()

    if result.get('success'):
        print(f"Template updated successfully")
        return True
    else:
        print(f"Update failed: {result.get('message')}")
        return False

# Example usage
new_scenes = [
    {"text": "Updated introduction", "duration": 5},
    {"text": "Updated main content", "duration": 8},
    {"text": "Updated conclusion", "duration": 4}
]

update_template_text("YOUR_TEMPLATE_ID", new_scenes, "YOUR_API_KEY")
```

### 2. Add New Scene to Template

Add additional scenes to an existing template:

```javascript theme={null}
async function addSceneToTemplate(templateId, newScene, apiKey) {
  // First, retrieve current template structure
  // Note: You may need to maintain template data separately
  // as there's no GET endpoint for individual templates

  const currentScenes = [
    // ... existing scenes
  ];

  // Add new scene
  currentScenes.push(newScene);

  const url = `https://api.pictory.ai/pictoryapis/v1/templates/${templateId}`;

  const response = await fetch(url, {
    method: 'PUT',
    headers: {
      'Authorization': `${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ scenes: currentScenes })
  });

  const result = await response.json();

  if (result.success) {
    console.log('Scene added successfully');
    return true;
  } else {
    console.error('Failed to add scene:', result.message);
    return false;
  }
}

// Example usage
const newScene = {
  text: 'New closing scene',
  duration: 5
};

await addSceneToTemplate('YOUR_TEMPLATE_ID', newScene, 'YOUR_API_KEY');
```

### 3. Batch Update Multiple Templates

Update multiple templates with similar modifications:

```python theme={null}
import requests
from typing import List, Dict

def batch_update_templates(
    template_ids: List[str],
    scene_updates: Dict,
    api_key: str
):
    """
    Update multiple templates with the same scene modifications
    """
    results = {
        'success': [],
        'failed': []
    }

    headers = {
        "Authorization": api_key,
        "Content-Type": "application/json"
    }

    for template_id in template_ids:
        url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"

        try:
            response = requests.put(
                url,
                headers=headers,
                json=scene_updates
            )
            result = response.json()

            if result.get('success'):
                results['success'].append(template_id)
                print(f"✓ Updated template: {template_id}")
            else:
                results['failed'].append({
                    'id': template_id,
                    'error': result.get('message')
                })
                print(f"✗ Failed template: {template_id}")

        except Exception as e:
            results['failed'].append({
                'id': template_id,
                'error': str(e)
            })
            print(f"✗ Error updating {template_id}: {e}")

    print(f"\nBatch update complete:")
    print(f"  Success: {len(results['success'])}")
    print(f"  Failed: {len(results['failed'])}")

    return results

# Example usage
template_ids = [
    "template_id_1",
    "template_id_2",
    "template_id_3"
]

scene_updates = {
    "scenes": [
        {"text": "Standardized intro", "duration": 5},
        {"text": "Main content placeholder", "duration": 10}
    ]
}

results = batch_update_templates(template_ids, scene_updates, "YOUR_API_KEY")
```

### 4. Update Template with Validation

Validate scene structure before updating:

```python theme={null}
import requests

def validate_scenes(scenes):
    """
    Validate scene structure before updating
    """
    if not isinstance(scenes, list):
        return False, "Scenes must be an array"

    if len(scenes) == 0:
        return False, "Scenes array cannot be empty"

    for i, scene in enumerate(scenes):
        if not isinstance(scene, dict):
            return False, f"Scene {i} must be an object"

        # Add more validation as needed
        if 'text' in scene and not isinstance(scene['text'], str):
            return False, f"Scene {i} text must be a string"

        if 'duration' in scene and not isinstance(scene['duration'], (int, float)):
            return False, f"Scene {i} duration must be a number"

    return True, "Validation passed"

def safe_update_template(template_id, scenes, api_key):
    """
    Update template with validation
    """
    # Validate scenes
    is_valid, message = validate_scenes(scenes)

    if not is_valid:
        print(f"Validation error: {message}")
        return False

    # Update template
    url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"
    headers = {
        "Authorization": api_key,
        "Content-Type": "application/json"
    }

    try:
        response = requests.put(
            url,
            headers=headers,
            json={"scenes": scenes}
        )
        result = response.json()

        if result.get('success'):
            print("Template updated successfully")
            return True
        else:
            print(f"Update failed: {result.get('message')}")
            return False

    except Exception as e:
        print(f"Error: {e}")
        return False

# Example usage
scenes = [
    {"text": "Validated scene 1", "duration": 5},
    {"text": "Validated scene 2", "duration": 8}
]

safe_update_template("YOUR_TEMPLATE_ID", scenes, "YOUR_API_KEY")
```

### 5. Rollback Template Changes

Implement a rollback mechanism for template updates:

```javascript theme={null}
class TemplateManager {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.backups = new Map();
  }

  async backupTemplate(templateId, scenes) {
    // Store backup locally
    this.backups.set(templateId, {
      scenes: JSON.parse(JSON.stringify(scenes)),
      timestamp: new Date().toISOString()
    });

    console.log(`Backup created for template ${templateId}`);
  }

  async updateTemplate(templateId, newScenes) {
    const url = `https://api.pictory.ai/pictoryapis/v1/templates/${templateId}`;

    try {
      const response = await fetch(url, {
        method: 'PUT',
        headers: {
          'Authorization': this.apiKey,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ scenes: newScenes })
      });

      const result = await response.json();

      if (result.success) {
        console.log('Template updated successfully');
        return { success: true, result };
      } else {
        console.error('Update failed:', result.message);
        return { success: false, error: result.message };
      }
    } catch (error) {
      console.error('Error updating template:', error);
      return { success: false, error: error.message };
    }
  }

  async rollbackTemplate(templateId) {
    const backup = this.backups.get(templateId);

    if (!backup) {
      console.error('No backup found for this template');
      return false;
    }

    console.log(`Rolling back to backup from ${backup.timestamp}`);
    return await this.updateTemplate(templateId, backup.scenes);
  }
}

// Example usage
const manager = new TemplateManager('YOUR_API_KEY');

// Backup current state
const currentScenes = [/* current scenes */];
await manager.backupTemplate('YOUR_TEMPLATE_ID', currentScenes);

// Update template
const newScenes = [/* new scenes */];
const result = await manager.updateTemplate('YOUR_TEMPLATE_ID', newScenes);

// Rollback if needed
if (!result.success) {
  await manager.rollbackTemplate('YOUR_TEMPLATE_ID');
}
```

***

## Best Practices

### Safety Guidelines

1. **Backup First**: Always backup the current template configuration before making updates
2. **Validate Structure**: Validate scene structure before sending updates to prevent errors
3. **Test Changes**: Test template updates in a development environment first
4. **Version Control**: Maintain version history of template configurations
5. **Gradual Rollout**: When updating production templates, do so gradually and monitor results

### Common Pitfalls

* **❌ No Backup**: Updating without backing up the current configuration
* **❌ Invalid Structure**: Sending incorrectly structured scene objects
* **❌ Missing Fields**: Omitting required fields in scene objects
* **❌ Production Testing**: Testing changes directly on production templates

### Performance Tips

* Batch similar updates to reduce API calls
* Cache template configurations locally to avoid repeated fetches
* Use validation before updates to prevent failed requests
* Implement retry logic for transient failures

***

## Related Endpoints

* [Get Templates](/api-reference/templates/get-templates) - Retrieve all available templates
* [Create Template](/api-reference/templates/create-template) - Create a new template
* [Update Project](/api-reference/projects/update-project) - Update project scenes (similar structure)
