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

# Delete Template

> Permanently delete a specific video template using its unique identifier

## Overview

Permanently delete a video template from your Pictory account using its unique identifier. This action removes the template and all its configuration data, including scene structures, variables, and settings.

<Warning>
  **This action is permanent and cannot be undone.** Once deleted, the template and all its configuration will be permanently removed from your account. Videos already 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}
DELETE 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 delete

  Example: `202512230204424435786014d42904bbc95813430789fe736`
</ParamField>

### Headers

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

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

***

## Response

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

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

***

## Response Examples

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

  ```json 204 - No Content theme={null}
  // Empty response body (successful deletion)
  ```

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

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

  ```json 403 - Forbidden theme={null}
  {
    "success": false,
    "message": "You do not have permission to delete this template"
  }
  ```
</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 DELETE \
    --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.delete(url, headers=headers)

  if response.status_code in [200, 204]:
      print(f"Template {template_id} deleted successfully")
  else:
      try:
          result = response.json()
          print(f"Failed to delete template: {result.get('message', 'Unknown error')}")
      except:
          print(f"Failed to delete template: HTTP {response.status_code}")
  ```

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

  if (response.status === 200 || response.status === 204) {
    console.log(`Template ${templateId} deleted successfully`);
  } else {
    const result = await response.json().catch(() => ({}));
    console.log(`Failed to delete template: ${result.message || 'Unknown error'}`);
  }
  ```
</CodeGroup>

***

## Usage Notes

<Warning>
  **Permanent Deletion**: Deleted templates cannot be recovered. Ensure you have backups of template configurations before deleting.
</Warning>

<Tip>
  Before deleting a template, consider using the [Get Template By Id](/api-reference/templates/get-template-by-id) endpoint to retrieve and back up the complete template configuration for archival purposes.
</Tip>

<Note>
  **Existing Videos**: Videos that were already created from this template will continue to exist and function normally. Only the template itself is deleted.
</Note>

<Note>
  **Permission Requirements**: You can only delete templates that belong to your account or team. Attempting to delete templates from other accounts will result in a 403 Forbidden error.
</Note>

***

## Common Use Cases

### 1. Delete Single Template with Confirmation

Delete a template after user confirmation:

```python theme={null}
import requests

def delete_template_with_confirmation(template_id, api_key):
    """
    Delete a template after confirming with the user
    """
    # First, get template details
    get_url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"
    headers = {"Authorization": api_key}

    template_response = requests.get(get_url, headers=headers)

    if template_response.status_code != 200:
        print("Template not found")
        return False

    template = template_response.json()
    template_name = template.get('name', 'Unknown')

    # Confirm deletion
    print(f"Are you sure you want to delete template '{template_name}'? (yes/no)")
    confirmation = input().strip().lower()

    if confirmation != 'yes':
        print("Deletion cancelled")
        return False

    # Delete template
    delete_url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"
    delete_response = requests.delete(delete_url, headers=headers)

    if delete_response.status_code in [200, 204]:
        print(f"Template '{template_name}' deleted successfully")
        return True
    else:
        try:
            result = delete_response.json()
            print(f"Failed to delete template: {result.get('message')}")
        except:
            print(f"Failed to delete template: HTTP {delete_response.status_code}")
        return False

# Example usage
delete_template_with_confirmation("YOUR_TEMPLATE_ID", "YOUR_API_KEY")
```

### 2. Bulk Delete Deprecated Templates

Delete all deprecated templates:

```python theme={null}
import requests

def delete_deprecated_templates(api_key, dry_run=True):
    """
    Delete all deprecated templates
    """
    headers = {"Authorization": api_key}

    # Get all templates
    list_url = "https://api.pictory.ai/pictoryapis/v1/templates"
    response = requests.get(list_url, headers=headers)
    templates = response.json().get('items', [])

    # Find deprecated templates
    deprecated_templates = [
        t for t in templates
        if t.get('depricated') or t.get('deprecated')
    ]

    print(f"Found {len(deprecated_templates)} deprecated templates")

    if dry_run:
        print("DRY RUN - Templates that would be deleted:")
        for template in deprecated_templates:
            print(f"  - {template.get('name', 'Unknown')} (ID: {template['templateId']})")
        return

    # Delete deprecated templates
    deleted_count = 0
    for template in deprecated_templates:
        delete_url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template['templateId']}"
        delete_response = requests.delete(delete_url, headers=headers)

        if delete_response.status_code in [200, 204]:
            print(f"✓ Deleted: {template.get('name', 'Unknown')}")
            deleted_count += 1
        else:
            print(f"✗ Failed: {template.get('name', 'Unknown')}")

    print(f"\nDeleted {deleted_count} out of {len(deprecated_templates)} deprecated templates")

# Example usage - dry run first
delete_deprecated_templates("YOUR_API_KEY", dry_run=True)

# Then execute for real
# delete_deprecated_templates("YOUR_API_KEY", dry_run=False)
```

### 3. Delete Templates by Language

Delete all templates for a specific language:

```javascript theme={null}
async function deleteTemplatesByLanguage(language, apiKey, confirmAll = false) {
  const headers = { 'Authorization': `${apiKey}` };

  // Get all templates
  const listResponse = await fetch(
    'https://api.pictory.ai/pictoryapis/v1/templates',
    { headers }
  );
  const data = await listResponse.json();

  // Filter by language
  const matchingTemplates = data.items.filter(t => t.language === language);

  console.log(`Found ${matchingTemplates.length} templates with language: ${language}`);

  if (!confirmAll) {
    console.log('Set confirmAll=true to delete these templates');
    matchingTemplates.forEach(t => {
      console.log(`  - ${t.name} (${t.templateId})`);
    });
    return matchingTemplates;
  }

  // Delete matching templates
  const results = {
    deleted: [],
    failed: []
  };

  for (const template of matchingTemplates) {
    const deleteResponse = await fetch(
      `https://api.pictory.ai/pictoryapis/v1/templates/${template.templateId}`,
      { method: 'DELETE', headers }
    );

    if (deleteResponse.status === 200 || deleteResponse.status === 204) {
      results.deleted.push(template.name);
      console.log(`✓ Deleted: ${template.name}`);
    } else {
      results.failed.push(template.name);
      console.log(`✗ Failed: ${template.name}`);
    }
  }

  console.log(`\nDeleted: ${results.deleted.length}, Failed: ${results.failed.length}`);
  return results;
}

// Example usage
const results = await deleteTemplatesByLanguage('en', 'YOUR_API_KEY', false);
```

### 4. Back Up Before Delete

Back up template configuration before deletion:

```python theme={null}
import requests
import json
import os
from datetime import datetime

def backup_and_delete_template(template_id, api_key, backup_dir="./template_backups"):
    """
    Backup template configuration before deleting
    """
    headers = {"Authorization": api_key}

    # Get template details
    get_url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"
    response = requests.get(get_url, headers=headers)

    if response.status_code != 200:
        print("Template not found")
        return False

    template = response.json()
    template_name = template.get('name', template_id)

    # Create backup directory
    os.makedirs(backup_dir, exist_ok=True)

    # Save template configuration
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{template_name.replace(' ', '_')}_{template_id}_{timestamp}.json"
    filepath = os.path.join(backup_dir, filename)

    backup_data = {
        "deletedDate": datetime.now().isoformat(),
        "templateData": template
    }

    with open(filepath, 'w') as f:
        json.dump(backup_data, f, indent=2)

    print(f"Backup saved to: {filepath}")

    # Delete template
    print(f"Deleting template...")
    delete_url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template_id}"
    delete_response = requests.delete(delete_url, headers=headers)

    if delete_response.status_code in [200, 204]:
        print(f"Template '{template_name}' deleted successfully")
        return True
    else:
        print(f"Failed to delete template")
        return False

# Example usage
backup_and_delete_template("YOUR_TEMPLATE_ID", "YOUR_API_KEY")
```

### 5. Safe Delete with Retry Logic

Delete template with error handling and retry:

```javascript theme={null}
async function safeDeleteTemplate(templateId, apiKey, maxRetries = 3) {
  const headers = { 'Authorization': `${apiKey}` };

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      console.log(`Attempt ${attempt} to delete template ${templateId}...`);

      const response = await fetch(
        `https://api.pictory.ai/pictoryapis/v1/templates/${templateId}`,
        { method: 'DELETE', headers }
      );

      if (response.status === 401) {
        throw new Error('Unauthorized - check your API key');
      }

      if (response.status === 404) {
        console.log('Template already deleted or does not exist');
        return { success: true, message: 'Template not found' };
      }

      if (response.status === 200 || response.status === 204) {
        console.log('Template deleted successfully');
        return { success: true };
      }

      const result = await response.json().catch(() => ({}));

      if (attempt < maxRetries) {
        console.log(`Deletion failed, retrying in ${attempt * 2} seconds...`);
        await new Promise(resolve => setTimeout(resolve, attempt * 2000));
      }
    } catch (error) {
      console.error(`Error on attempt ${attempt}:`, error.message);

      if (attempt === maxRetries) {
        throw error;
      }

      await new Promise(resolve => setTimeout(resolve, attempt * 2000));
    }
  }

  throw new Error(`Failed to delete template after ${maxRetries} attempts`);
}

// Example usage
try {
  const result = await safeDeleteTemplate('YOUR_TEMPLATE_ID', 'YOUR_API_KEY');
  console.log('Result:', result);
} catch (error) {
  console.error('Final error:', error.message);
}
```

### 6. Delete Unpublished Draft Templates

Delete all unpublished draft templates:

```python theme={null}
import requests

def delete_unpublished_templates(api_key, confirm=False):
    """
    Delete all unpublished (draft) templates
    """
    headers = {"Authorization": api_key}

    # Get all templates
    list_url = "https://api.pictory.ai/pictoryapis/v1/templates"
    response = requests.get(list_url, headers=headers)
    templates = response.json().get('items', [])

    # Find unpublished templates
    unpublished = [t for t in templates if not t.get('published')]

    print(f"Found {len(unpublished)} unpublished templates")

    if not unpublished:
        print("No unpublished templates to delete")
        return

    # List templates
    for i, template in enumerate(unpublished, 1):
        print(f"{i}. {template.get('name', 'Unknown')} (ID: {template['templateId']})")

    if not confirm:
        print("\nSet confirm=True to delete these templates")
        return

    # Delete templates
    deleted_count = 0
    for template in unpublished:
        delete_url = f"https://api.pictory.ai/pictoryapis/v1/templates/{template['templateId']}"
        delete_response = requests.delete(delete_url, headers=headers)

        if delete_response.status_code in [200, 204]:
            print(f"✓ Deleted: {template.get('name', 'Unknown')}")
            deleted_count += 1
        else:
            print(f"✗ Failed: {template.get('name', 'Unknown')}")

    print(f"\nDeleted {deleted_count} out of {len(unpublished)} unpublished templates")

# Example usage
delete_unpublished_templates("YOUR_API_KEY", confirm=False)
```

***

## Best Practices

### Safety Measures

1. **Always back up before deletion**: Use the Get Template By Id endpoint to retrieve the complete configuration before deleting
2. **Implement confirmation**: Require user confirmation before executing delete operations
3. **Use dry runs**: Test deletion logic with dry run mode before executing
4. **Log deletions**: Keep audit logs of deleted templates for accountability
5. **Handle errors gracefully**: Implement proper error handling and retry logic

### Common Pitfalls

* **❌ No Backup**: Deleting without backing up the template configuration
* **❌ Bulk Operations**: Deleting multiple templates without confirmation
* **❌ Production Testing**: Testing deletion on production templates
* **❌ Ignoring Errors**: Not checking response status codes

### Bulk Operations

When deleting multiple templates:

* Add delays between deletions to avoid rate limiting
* Process deletions in batches
* Implement comprehensive error handling
* Provide progress updates to users
* Log both successes and failures

### Recovery Planning

Since deletion is permanent:

* Maintain regular backups of template configurations
* Export template data before deletion
* Keep deletion logs for audit trails
* Store template JSON files for potential recreation

***

## Related Endpoints

* [Get Templates](/api-reference/templates/get-templates) - List all available templates
* [Get Template By Id](/api-reference/templates/get-template-by-id) - Retrieve template details before deleting
* [Update Template](/api-reference/templates/update-template) - Modify template instead of deleting
* [Create Template](/api-reference/templates/create-template) - Create a new template
