Skip to main content
PUT
https://api.pictory.ai
/
pictoryapis
/
v1
/
templates
/
{templateId}
Update Template
curl --request PUT \
  --url https://api.pictory.ai/pictoryapis/v1/templates/{templateId} \
  --header 'Authorization: <authorization>' \
  --header 'Content-Type: application/json' \
  --data '{
  "scenes": {}
}'
{
  "success": true,
  "message": "Template updated successfully",
  "templateId": "202512230204424435786014d42904bbc95813430789fe736"
}

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.
Template Modification: Updating a template affects all future videos created from it. Existing videos created from this template will not be affected.
You need a valid API key to use this endpoint. Get your API key from the API Access page in your Pictory dashboard.

API Endpoint

PUT https://api.pictory.ai/pictoryapis/v1/templates/{templateId}

Request Parameters

Path Parameters

templateId
string
required
The unique identifier of the template to updateExample: 202512230204424435786014d42904bbc95813430789fe736

Headers

Authorization
string
required
API key for authentication (starts with pictai_)
Authorization: YOUR_API_KEY

Body Parameters

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

Response

success
boolean
Indicates whether the update was successful
message
string
Confirmation message about the update
templateId
string
The ID of the updated template

Response Examples

{
  "success": true,
  "message": "Template updated successfully",
  "templateId": "202512230204424435786014d42904bbc95813430789fe736"
}

Code Examples

Replace YOUR_API_KEY with your actual API key that starts with pictai_
# 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

Usage Notes

Test Before Production: Always test template updates with non-production templates first to ensure the scene structure is valid and produces the expected results.
Scene Structure: The scenes array should match the structure used in Pictory projects. Refer to the Update Project endpoint documentation for scene object examples.
Version Control: Consider keeping backup copies of template configurations before making updates, especially for templates actively used in production.

Common Use Cases

1. Update Template Text Content

Modify the text content across all scenes in a template:
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:
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:
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:
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:
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