> ## 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 Text Styles

> Retrieve all available text styles defined in the Pictory application

## Overview

Fetch all text styles defined in the Pictory App. Text styles are predefined formatting presets that control the appearance of text in your videos, including font, size, color, weight, alignment, and other visual properties. These styles can be applied to captions, titles, headings, and body text in your video projects.

Use this endpoint to retrieve available styles for video editing, branding customization, or to allow users to select from predefined text formatting options.

<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/styles
```

***

## Request Parameters

### Headers

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

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

***

## Response

Returns an array of text style objects, each containing a unique identifier and descriptive name.

<ResponseField name="Array" type="array of objects">
  List of available text styles

  <Expandable title="style object">
    <ResponseField name="id" type="uuid" required>
      Unique identifier for the text style
    </ResponseField>

    <ResponseField name="name" type="string" required>
      Descriptive name of the text style (e.g., "Navy blue", "Bold edge", "Standard Black Caption")
    </ResponseField>
  </Expandable>
</ResponseField>

### Response Examples

<ResponseExample>
  ```json 200 - Success theme={null}
  [
    {
      "id": "8f3deae9-fe38-4c53-8be0-616bef1da916",
      "name": "Navy blue"
    },
    {
      "id": "8b715161-182a-4ef4-8130-b04873f464f6",
      "name": "Indigo ink"
    },
    {
      "id": "6d9cc665-8087-4587-ab6d-f9d7d01f82c4",
      "name": "Default"
    },
    {
      "id": "4111e523-eb9c-41a2-b17b-c312694ce4eb",
      "name": "Sleek"
    },
    {
      "id": "fc2737ae-d88b-4914-8b8d-5152d94dc3f6",
      "name": "Black Traditional Caption"
    },
    {
      "id": "c8d30e79-a7cc-4ae4-8cf9-2c6286abb407",
      "name": "Dark Blue Caption"
    },
    {
      "id": "bcbcef60-9f8f-4357-ac32-ecf5144f2f12",
      "name": "Headliner"
    },
    {
      "id": "ac666d90-f402-42b3-8b69-738afa09741c",
      "name": "Flash"
    }
  ]
  ```

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

  ```json 500 - Internal Server Error theme={null}
  {
    "error": {
      "code": "INTERNAL_ERROR",
      "message": "An unexpected error occurred"
    }
  }
  ```
</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/styles' \
    --header 'Authorization: YOUR_API_KEY' \
    --header 'accept: application/json' | python -m json.tool
  ```

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

  url = "https://api.pictory.ai/pictoryapis/v1/styles"
  headers = {
      "Authorization": "YOUR_API_KEY",
      "accept": "application/json"
  }

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

  print(f"Total styles available: {len(styles)}\n")

  # Display first 10 styles
  for style in styles[:10]:
      print(f"- {style['name']} (ID: {style['id']})")
  ```

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

  const styles = await response.json();

  console.log(`Total styles available: ${styles.length}\n`);

  // Display first 10 styles
  styles.slice(0, 10).forEach(style => {
    console.log(`- ${style.name} (ID: ${style.id})`);
  });
  ```

  ```php PHP theme={null}
  <?php
  // Replace 'YOUR_API_KEY' with your actual API key

  function getTextStyles($apiKey) {
      $url = 'https://api.pictory.ai/pictoryapis/v1/styles';

      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
          'Authorization: ' . $apiKey,
          'accept: application/json'
      ]);

      $response = curl_exec($ch);
      $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      curl_close($ch);

      if ($httpCode !== 200) {
          throw new Exception('Request failed with status ' . $httpCode);
      }

      return json_decode($response, true);
  }

  // Usage
  try {
      $styles = getTextStyles('YOUR_API_KEY');

      echo "Total styles available: " . count($styles) . "\n\n";

      // Display first 10 styles
      foreach (array_slice($styles, 0, 10) as $style) {
          echo "- {$style['name']} (ID: {$style['id']})\n";
      }
  } catch (Exception $e) {
      echo "Error: " . $e->getMessage() . "\n";
  }
  ?>
  ```

  ```go Go theme={null}
  // Replace "YOUR_API_KEY" with your actual API key

  package main

  import (
      "encoding/json"
      "fmt"
      "io"
      "net/http"
  )

  type TextStyle struct {
      ID   string `json:"id"`
      Name string `json:"name"`
  }

  func getTextStyles(apiKey string) ([]TextStyle, error) {
      url := "https://api.pictory.ai/pictoryapis/v1/styles"

      req, err := http.NewRequest("GET", url, nil)
      if err != nil {
          return nil, err
      }

      req.Header.Set("Authorization", apiKey)
      req.Header.Set("accept", "application/json")

      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          return nil, err
      }
      defer resp.Body.Close()

      body, err := io.ReadAll(resp.Body)
      if err != nil {
          return nil, err
      }

      if resp.StatusCode != http.StatusOK {
          return nil, fmt.Errorf("request failed (status %d): %s", resp.StatusCode, string(body))
      }

      var styles []TextStyle
      if err := json.Unmarshal(body, &styles); err != nil {
          return nil, err
      }

      return styles, nil
  }

  // Usage
  func main() {
      styles, err := getTextStyles("YOUR_API_KEY")
      if err != nil {
          panic(err)
      }

      fmt.Printf("Total styles available: %d\n\n", len(styles))

      // Display first 10 styles
      limit := 10
      if len(styles) < limit {
          limit = len(styles)
      }

      for i := 0; i < limit; i++ {
          fmt.Printf("- %s (ID: %s)\n", styles[i].Name, styles[i].ID)
      }
  }
  ```
</CodeGroup>

***

## Common Use Cases

### 1. List All Available Styles

Retrieve and display all text styles:

```python theme={null}
import requests

url = "https://api.pictory.ai/pictoryapis/v1/styles"
headers = {
    "Authorization": "YOUR_API_KEY",
    "accept": "application/json"
}

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

print(f"Total styles: {len(styles)}\n")

# Group by category (based on name patterns)
captions = [s for s in styles if 'caption' in s['name'].lower()]
headings = [s for s in styles if 'heading' in s['name'].lower() or 'title' in s['name'].lower()]
others = [s for s in styles if s not in captions and s not in headings]

print(f"Caption styles: {len(captions)}")
print(f"Heading/Title styles: {len(headings)}")
print(f"Other styles: {len(others)}")
```

### 2. Search Styles by Name

Find styles matching specific criteria:

```python theme={null}
import requests

def search_styles(api_key, search_term):
    """
    Search for text styles by name.

    Args:
        api_key: Your API key
        search_term: Text to search for in style names
    """
    url = "https://api.pictory.ai/pictoryapis/v1/styles"
    headers = {
        "Authorization": api_key,
        "accept": "application/json"
    }

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

    # Case-insensitive search
    search_term_lower = search_term.lower()
    matches = [
        style for style in styles
        if search_term_lower in style['name'].lower()
    ]

    return matches

# Usage - Find all "black" styles
black_styles = search_styles("YOUR_API_KEY", "black")

print(f"Found {len(black_styles)} styles containing 'black':")
for style in black_styles:
    print(f"- {style['name']}")

# Find caption styles
caption_styles = search_styles("YOUR_API_KEY", "caption")
print(f"\nFound {len(caption_styles)} caption styles")
```

### 3. Create Style Selector for UI

Build a dropdown/selector component:

```python theme={null}
import requests

def get_styles_for_selector(api_key, category=None):
    """
    Get text styles formatted for a UI selector.

    Args:
        api_key: Your API key
        category: Optional filter ('caption', 'heading', 'title', etc.)
    """
    url = "https://api.pictory.ai/pictoryapis/v1/styles"
    headers = {
        "Authorization": api_key,
        "accept": "application/json"
    }

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

    # Filter by category if specified
    if category:
        styles = [
            s for s in styles
            if category.lower() in s['name'].lower()
        ]

    # Format for UI selector
    selector_options = [
        {
            "value": style['id'],
            "label": style['name']
        }
        for style in sorted(styles, key=lambda x: x['name'])
    ]

    return selector_options

# Usage
all_options = get_styles_for_selector("YOUR_API_KEY")
caption_options = get_styles_for_selector("YOUR_API_KEY", category="caption")

print(f"All styles: {len(all_options)}")
print(f"Caption styles: {len(caption_options)}")

# Example output for first 5
print("\nFirst 5 options:")
for option in all_options[:5]:
    print(f"  {option['label']} -> {option['value']}")
```

### 4. Cache Styles Locally

Cache styles to reduce API calls:

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

class StyleCache:
    def __init__(self, api_key, cache_duration_hours=24):
        self.api_key = api_key
        self.cache_duration = timedelta(hours=cache_duration_hours)
        self.cache_file = "text_styles_cache.json"
        self.styles = None
        self.last_updated = None

    def get_styles(self, force_refresh=False):
        """Get styles from cache or API."""
        # Check if cache is valid
        if not force_refresh and self._is_cache_valid():
            print("Using cached styles")
            return self.styles

        # Fetch from API
        print("Fetching styles from API")
        url = "https://api.pictory.ai/pictoryapis/v1/styles"
        headers = {
            "Authorization": self.api_key,
            "accept": "application/json"
        }

        response = requests.get(url, headers=headers)
        self.styles = response.json()
        self.last_updated = datetime.now()

        # Save to cache file
        self._save_cache()

        return self.styles

    def _is_cache_valid(self):
        """Check if cache exists and is still valid."""
        try:
            with open(self.cache_file, 'r') as f:
                cache_data = json.load(f)

            last_updated = datetime.fromisoformat(cache_data['last_updated'])
            if datetime.now() - last_updated < self.cache_duration:
                self.styles = cache_data['styles']
                self.last_updated = last_updated
                return True
        except (FileNotFoundError, json.JSONDecodeError, KeyError):
            pass

        return False

    def _save_cache(self):
        """Save styles to cache file."""
        cache_data = {
            'styles': self.styles,
            'last_updated': self.last_updated.isoformat()
        }

        with open(self.cache_file, 'w') as f:
            json.dump(cache_data, f)

# Usage
cache = StyleCache("YOUR_API_KEY", cache_duration_hours=24)

# First call - fetches from API
styles = cache.get_styles()
print(f"Loaded {len(styles)} styles")

# Second call - uses cache
styles = cache.get_styles()
print(f"Loaded {len(styles)} styles")

# Force refresh
styles = cache.get_styles(force_refresh=True)
print(f"Loaded {len(styles)} styles (refreshed)")
```

### 5. Group Styles by Category

Organize styles into logical categories:

```python theme={null}
import requests
from collections import defaultdict

def categorize_styles(api_key):
    """
    Categorize text styles based on their names.

    Args:
        api_key: Your API key

    Returns:
        Dictionary with categorized styles
    """
    url = "https://api.pictory.ai/pictoryapis/v1/styles"
    headers = {
        "Authorization": api_key,
        "accept": "application/json"
    }

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

    categories = {
        'Captions': [],
        'Headings/Titles': [],
        'Colors': [],
        'Standard': [],
        'Special Effects': [],
        'Other': []
    }

    for style in styles:
        name_lower = style['name'].lower()

        if 'caption' in name_lower:
            categories['Captions'].append(style)
        elif 'heading' in name_lower or 'title' in name_lower:
            categories['Headings/Titles'].append(style)
        elif any(color in name_lower for color in ['black', 'blue', 'yellow', 'red', 'purple', 'orange', 'green', 'pink']):
            categories['Colors'].append(style)
        elif 'standard' in name_lower or 'default' in name_lower:
            categories['Standard'].append(style)
        elif any(effect in name_lower for effect in ['bold', 'flash', 'retro', 'handwritten', 'cartoon']):
            categories['Special Effects'].append(style)
        else:
            categories['Other'].append(style)

    return categories

# Usage
categories = categorize_styles("YOUR_API_KEY")

for category, styles in categories.items():
    print(f"\n{category} ({len(styles)} styles):")
    for style in styles[:5]:  # Show first 5 of each category
        print(f"  - {style['name']}")
    if len(styles) > 5:
        print(f"  ... and {len(styles) - 5} more")
```

***

## Style Categories

Based on the returned styles, common categories include:

| Category            | Examples                                                             | Use Case                         |
| ------------------- | -------------------------------------------------------------------- | -------------------------------- |
| **Captions**        | Black Traditional Caption, Dark Blue Caption, Standard White Caption | Subtitles and closed captions    |
| **Headings**        | Bold One-word Heading, Orange Handwritten Heading, Headliner         | Video titles and section headers |
| **Colors**          | Navy blue, Sunflower yellow, Lemon Yellow, Indigo ink                | Color-themed text                |
| **Standard**        | Default, Standard, Body text, Sub heading, Heading                   | General-purpose text             |
| **Branded**         | Sleek, Classic mini, Clean, Bold edge, Polished pro                  | Consistent branding              |
| **Special Effects** | Flash, Retro, Handwritten, Typewriter, Cartoon                       | Creative and stylized text       |
| **News/Media**      | Red Breaking News Caption, Large Yellow News Heading                 | News and announcements           |

***

## Usage Notes

<Tip>
  **Caching Recommended**: Text styles rarely change. Cache the results locally to improve performance and reduce API calls.
</Tip>

<Note>
  **Style IDs**: Use the UUID `id` field when applying styles to video elements. Style names are for display purposes only.
</Note>

<Note>
  **Consistent Across Projects**: The same text styles are available across all your video projects, ensuring brand consistency.
</Note>

***

## Best Practices

1. **Cache Styles**: Fetch styles once and cache them locally. Text styles change infrequently.

2. **Use Style IDs**: Always reference styles by their UUID `id`, not by name. Names may change, but IDs remain constant.

3. **Provide Search/Filter**: In user interfaces, provide search or filter functionality to help users find specific styles quickly from the large list.

4. **Group by Category**: Organize styles into logical categories (captions, headings, colors) for better user experience.

5. **Show Previews**: If possible, display visual previews of text styles to help users make selections.

6. **Handle Missing Styles Gracefully**: If a referenced style ID does not exist, fall back to a default style.

7. **Sort Alphabetically**: Present styles in alphabetical order for easy browsing.

8. **Validate Style IDs**: Before applying a style, verify the ID exists in the current list of available styles.
