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

# Templates API

> Create and manage templates with nested sections and extraction rules

# Templates API

The Templates API manages templates with nested sections and content extraction rules. Templates define the structure and content requirements for generated documents.

## List Templates

Retrieve all templates accessible to the authenticated user, sorted by creation date (newest first).

```bash theme={null}
GET /api/v1/templates/
```

### Request Example

```bash theme={null}
curl -X GET "https://api.artosai.com/api/v1/templates/" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

### Response

```json theme={null}
{
  "templates": [
    {
      "id": "tmpl-uuid-1",
      "template_name": "CSR Template",
      "source_document_name": "csr-example.docx",
      "url": "https://s3.amazonaws.com/bucket/template.docx?X-Amz-Algorithm=...",
      "detected_document_type": "CSR",
      "template_id": "tmpl-uuid-1",
      "sections": [
        {
          "section_id": "sect-uuid-1",
          "section_name": "1. Executive Summary",
          "order_index": 0,
          "level": 1
        },
        {
          "section_id": "sect-uuid-2",
          "section_name": "2. Study Design",
          "order_index": 1,
          "level": 1
        }
      ],
      "status": "active",
      "template_file_name": "csr-template.docx",
      "created_at": "2024-01-20T10:00:00Z",
      "updated_at": "2024-01-25T12:00:00Z"
    }
  ]
}
```

### Status Codes

* **200 OK**: Templates retrieved successfully
* **401 Unauthorized**: Missing or invalid Bearer token

***

## Get Single Template

Retrieve a specific template with full details including sections, rules, users, and style information.

```bash theme={null}
GET /api/v1/templates/{template_id}
```

### Path Parameters

| Parameter     | Type   | Required | Description          |
| ------------- | ------ | -------- | -------------------- |
| `template_id` | string | Yes      | UUID of the template |

### Request Example

```bash theme={null}
curl -X GET "https://api.artosai.com/api/v1/templates/tmpl-uuid-1" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

### Response

```json theme={null}
{
  "url": "https://s3.amazonaws.com/bucket/template.docx?X-Amz-Algorithm=...",
  "template_name": "CSR Template",
  "source_document_name": "csr-example.docx",
  "detected_document_type": "CSR",
  "document_type": "CSR",
  "template_id": "tmpl-uuid-1",
  "template_s3_uri": "org-uuid/templates/csr-template.docx",
  "template_file_name": "csr-template.docx",
  "sections": [
    {
      "section_id": "sect-uuid-1",
      "order_index": 0,
      "level": 1,
      "section_name": "1. Executive Summary",
      "synopsis": "Summary of key findings",
      "template_instructions": "Summarize in 2-3 paragraphs",
      "template_text": "This section provides a concise overview...",
      "is_repeating": false,
      "rules": [
        {
          "rule_id": "rule-uuid-1",
          "rule_type": "CopyPasteRule",
          "rule_mode": "auto",
          "description": "Extract safety findings",
          "style_names": ["Normal"],
          "fill": null,
          "color": null
        }
      ]
    }
  ],
  "examples": [
    {
      "example_id": "ex-uuid-1",
      "content": "Example CSR executive summary text..."
    }
  ],
  "all_styles": ["Normal", "Heading 1", "Heading 2", "Table Text"],
  "users": [
    {
      "user_id": "user-uuid-1",
      "email": "alice@example.com"
    }
  ],
  "document_instructions": "Follow ICH E3 guidelines for all sections.",
  "document_metadata": {
    "sponsor": "Acme Pharma",
    "study_number": "ACME-2024-001"
  },
  "hidden_text_style": "Hidden",
  "include_instructions": true
}
```

### Status Codes

* **200 OK**: Template retrieved successfully
* **400 Bad Request**: Authentication failure
* **404 Not Found**: Template not found

***

## Create Template

Create a new template with nested sections and extraction rules.

```bash theme={null}
POST /api/v1/templates/
```

### Request Body

```json theme={null}
{
  "template_name": "CSR Template",
  "document_type": "CSR",
  "sections": [
    {
      "order_index": 0,
      "level": 1,
      "section_name": "1. Executive Summary",
      "synopsis": "Overview of document findings",
      "template_instructions": "Summarize key findings in 2-3 paragraphs",
      "template_text": "This section provides a concise overview...",
      "section_type": "summary",
      "section_mode": "auto",
      "is_repeating": false,
      "rules": [
        {
          "rule_type": "CopyPasteRule",
          "rule_mode": "auto",
          "description": "Extract safety data"
        }
      ]
    },
    {
      "order_index": 1,
      "level": 1,
      "section_name": "2. Study Design",
      "synopsis": "Description of study methodology",
      "template_instructions": "Describe study design and objectives"
    }
  ],
  "template_s3_uri": "org-id/templates/csr-template.docx",
  "document_description": "Standard CSR template per ICH E3",
  "tags": ["csr", "regulatory"],
  "users": ["user-uuid-1", "user-uuid-2"]
}
```

### Request Parameters

| Parameter              | Type   | Required   | Description                                           |
| ---------------------- | ------ | ---------- | ----------------------------------------------------- |
| `template_name`        | string | Yes        | Template name                                         |
| `document_type`        | string | Yes        | Document type (e.g., `"CSR"`, `"IND"`, `"NDA"`)       |
| `sections`             | array  | Yes        | At least one section required                         |
| `template_s3_uri`      | string | Required\* | S3 URI for the template file                          |
| `template_file_name`   | string | Required\* | Template file name (alternative to `template_s3_uri`) |
| `document_description` | string | No         | Description                                           |
| `tags`                 | array  | No         | Categorization tags                                   |
| `users`                | array  | No         | User IDs to grant access                              |

\* Either `template_s3_uri` or `template_file_name` must be provided.

### Section Parameters

| Parameter               | Type    | Required | Description                                         |
| ----------------------- | ------- | -------- | --------------------------------------------------- |
| `order_index`           | integer | Yes      | Position in template (0-based, must be unique)      |
| `level`                 | integer | Yes      | Nesting level (1 = top-level, 2 = subsection, etc.) |
| `section_name`          | string  | Yes      | Section title                                       |
| `synopsis`              | string  | No       | Brief summary                                       |
| `template_instructions` | string  | No       | Completion instructions                             |
| `template_text`         | string  | No       | Template text                                       |
| `section_type`          | string  | No       | Section type classification                         |
| `section_mode`          | string  | No       | Operation mode                                      |
| `is_repeating`          | boolean | No       | Default: `false`                                    |
| `expansion_type`        | string  | No       | For repeating sections                              |
| `rules`                 | array   | No       | Extraction rules for the section                    |

### Request Example

```bash theme={null}
curl -X POST "https://api.artosai.com/api/v1/templates/" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "template_name": "CSR Template",
    "document_type": "CSR",
    "sections": [
      {
        "order_index": 0,
        "level": 1,
        "section_name": "1. Executive Summary",
        "template_instructions": "Summarize findings"
      }
    ],
    "template_s3_uri": "org-id/templates/csr-template.docx"
  }'
```

### Python Example

```python theme={null}
import requests

url = "https://api.artosai.com/api/v1/templates/"
headers = {
    "Authorization": "Bearer YOUR_TOKEN",
    "Content-Type": "application/json"
}

payload = {
    "template_name": "CSR Template",
    "document_type": "CSR",
    "sections": [
        {
            "order_index": 0,
            "level": 1,
            "section_name": "1. Executive Summary",
            "template_instructions": "Summarize key findings"
        },
        {
            "order_index": 1,
            "level": 1,
            "section_name": "2. Study Design",
            "template_instructions": "Describe study methodology"
        }
    ],
    "template_s3_uri": "org-id/templates/csr-template.docx"
}

response = requests.post(url, headers=headers, json=payload)
template = response.json()
print(f"Created template: {template['template_id']}")
print(f"Sections: {template['section_count']}, Rules: {template['rule_count']}")
```

### Response (201 Created)

```json theme={null}
{
  "template_id": "tmpl-uuid-789",
  "template_name": "CSR Template",
  "organization_id": "org-uuid-789",
  "section_count": 2,
  "rule_count": 1,
  "created_at": "2024-01-25T12:00:00Z",
  "message": "Template created successfully"
}
```

### Response Fields

| Field             | Type    | Description                               |
| ----------------- | ------- | ----------------------------------------- |
| `template_id`     | string  | UUID of the created template              |
| `template_name`   | string  | Name of the template                      |
| `organization_id` | string  | Organization UUID                         |
| `section_count`   | integer | Number of sections created                |
| `rule_count`      | integer | Total number of rules across all sections |
| `created_at`      | string  | ISO 8601 creation timestamp               |
| `message`         | string  | Success message                           |

### Status Codes

* **201 Created**: Template created successfully
* **400 Bad Request**: Validation errors (missing fields, duplicate `order_index`, missing `template_s3_uri`/`template_file_name`)
* **401 Unauthorized**: Authentication failure
* **500 Internal Server Error**: Database operation failure

***

## Add Section to Template

Add a new section to an existing template.

```bash theme={null}
POST /api/v1/templates/{template_id}/sections
```

### Path Parameters

| Parameter     | Type   | Required | Description          |
| ------------- | ------ | -------- | -------------------- |
| `template_id` | string | Yes      | UUID of the template |

### Request Body

```json theme={null}
{
  "section_name": "3. Safety Analysis",
  "level": 1,
  "order_index": 2
}
```

### Request Parameters

| Parameter      | Type    | Required | Description                                         |
| -------------- | ------- | -------- | --------------------------------------------------- |
| `section_name` | string  | Yes      | Name/title of the section                           |
| `level`        | integer | Yes      | Nesting level (1 = top-level, 2 = subsection, etc.) |
| `order_index`  | integer | Yes      | Position in the template (0-based)                  |

### Request Example

```bash theme={null}
curl -X POST "https://api.artosai.com/api/v1/templates/tmpl-uuid-1/sections" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "section_name": "3. Safety Analysis",
    "level": 1,
    "order_index": 2
  }'
```

### Response

```json theme={null}
{
  "message": "Section added successfully",
  "section_id": "sect-uuid-new",
  "template_id": "tmpl-uuid-1",
  "section_name": "3. Safety Analysis",
  "level": 1,
  "order_index": 2
}
```

### Status Codes

* **200 OK**: Section added successfully
* **400 Bad Request**: Authentication errors
* **403 Forbidden**: Unauthorized access
* **404 Not Found**: Template not found
* **500 Internal Server Error**: Database operation failure

***

## Rename Template Section

Update the name of an existing template section.

```bash theme={null}
PUT /api/v1/templates/{template_id}/sections/{section_id}/rename
```

### Path Parameters

| Parameter     | Type   | Required | Description                   |
| ------------- | ------ | -------- | ----------------------------- |
| `template_id` | string | Yes      | UUID of the template          |
| `section_id`  | string | Yes      | UUID of the section to rename |

### Request Body

```json theme={null}
{
  "section_name": "3.1 Adverse Events"
}
```

### Request Parameters

| Parameter      | Type   | Required | Description                                               |
| -------------- | ------ | -------- | --------------------------------------------------------- |
| `section_name` | string | Yes      | New name for the section (e.g., `"2.1 Efficacy Results"`) |

### Request Example

```bash theme={null}
curl -X PUT "https://api.artosai.com/api/v1/templates/tmpl-uuid-1/sections/sect-uuid-1/rename" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "section_name": "3.1 Adverse Events"
  }'
```

### Response

```json theme={null}
{
  "section_id": "sect-uuid-1",
  "section_name": "3.1 Adverse Events",
  "message": "Section renamed successfully"
}
```

### Status Codes

* **200 OK**: Section renamed successfully
* **400 Bad Request**: Authentication errors
* **403 Forbidden**: Unauthorized access
* **404 Not Found**: Template or section not found
* **500 Internal Server Error**: Database operation failure

***

## Reorder Template Sections

Reorder and automatically renumber all sections in a template. After reordering, section names are renumbered to reflect the new hierarchy (e.g., `"1."`, `"1.1"`, `"2."`).

```bash theme={null}
PUT /api/v1/templates/{template_id}/sections/reorder
```

### Path Parameters

| Parameter     | Type   | Required | Description          |
| ------------- | ------ | -------- | -------------------- |
| `template_id` | string | Yes      | UUID of the template |

### Request Body

```json theme={null}
{
  "sections": [
    { "section_id": "sect-uuid-2", "order_index": 0, "level": 1 },
    { "section_id": "sect-uuid-1", "order_index": 1, "level": 1 },
    { "section_id": "sect-uuid-3", "order_index": 2, "level": 2 }
  ]
}
```

### Request Parameters

| Parameter  | Type  | Required | Description                                                               |
| ---------- | ----- | -------- | ------------------------------------------------------------------------- |
| `sections` | array | Yes      | List of `{section_id, order_index, level}` objects defining the new order |

### Request Example

```bash theme={null}
curl -X PUT "https://api.artosai.com/api/v1/templates/tmpl-uuid-1/sections/reorder" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "sections": [
      { "section_id": "sect-uuid-2", "order_index": 0, "level": 1 },
      { "section_id": "sect-uuid-1", "order_index": 1, "level": 1 },
      { "section_id": "sect-uuid-3", "order_index": 2, "level": 2 }
    ]
  }'
```

### Response

```json theme={null}
{
  "template_id": "tmpl-uuid-1",
  "sections": [
    {
      "section_id": "sect-uuid-2",
      "section_name": "1. Study Design",
      "order_index": 0,
      "level": 1
    },
    {
      "section_id": "sect-uuid-1",
      "section_name": "2. Executive Summary",
      "order_index": 1,
      "level": 1
    },
    {
      "section_id": "sect-uuid-3",
      "section_name": "2.1 Safety Overview",
      "order_index": 2,
      "level": 2
    }
  ],
  "message": "Sections reordered and renumbered successfully"
}
```

### Status Codes

* **200 OK**: Sections reordered successfully
* **400 Bad Request**: Authentication errors
* **403 Forbidden**: Unauthorized access
* **404 Not Found**: Template not found
* **500 Internal Server Error**: Database operation failure

***

## Update Rule Styles

Update the style names, fill color, and/or text color for a specific rule within a template section.

```bash theme={null}
PUT /api/v1/templates/{template_id}/rules/{rule_id}/styles
```

### Path Parameters

| Parameter     | Type   | Required | Description                                   |
| ------------- | ------ | -------- | --------------------------------------------- |
| `template_id` | string | Yes      | UUID of the template (used for authorization) |
| `rule_id`     | string | Yes      | UUID of the rule to update                    |

### Request Body

```json theme={null}
{
  "style_names": ["Heading 2", "Normal"],
  "fill": "#FFFF00",
  "color": "#FF0000"
}
```

### Request Parameters

| Parameter     | Type   | Required | Description                                                                |
| ------------- | ------ | -------- | -------------------------------------------------------------------------- |
| `style_names` | array  | No       | List of Word style names to apply (e.g., `["Heading 2", "Normal"]`)        |
| `fill`        | string | No       | Background fill color as hex (e.g., `"#FFFF00"`), or `null`/`""` to remove |
| `color`       | string | No       | Text/font color as hex (e.g., `"#FF0000"`), or `null`/`""` to remove       |

### Request Example

```bash theme={null}
curl -X PUT "https://api.artosai.com/api/v1/templates/tmpl-uuid-1/rules/rule-uuid-1/styles" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "style_names": ["Heading 2"],
    "fill": "#FFF2CC",
    "color": null
  }'
```

### Response

```json theme={null}
{
  "rule_id": "rule-uuid-1",
  "styles": {
    "style_names": ["Heading 2"],
    "fill": "#FFF2CC",
    "color": null
  },
  "updated": true
}
```

### Status Codes

* **200 OK**: Rule styles updated successfully
* **400 Bad Request**: Authentication errors
* **403 Forbidden**: Unauthorized access
* **404 Not Found**: Template or rule not found
* **500 Internal Server Error**: Database operation failure

***

## Delete Template Section

Delete a section from an template. Associated rules are automatically deleted via CASCADE.

```bash theme={null}
DELETE /api/v1/templates/{template_id}/sections/{section_id}
```

### Path Parameters

| Parameter     | Type   | Required | Description                   |
| ------------- | ------ | -------- | ----------------------------- |
| `template_id` | string | Yes      | UUID of the template          |
| `section_id`  | string | Yes      | UUID of the section to delete |

### Query Parameters

| Parameter          | Type    | Required | Default | Description                                                    |
| ------------------ | ------- | -------- | ------- | -------------------------------------------------------------- |
| `cascade_children` | boolean | No       | `true`  | If `true`, also delete child sections at deeper nesting levels |

### Request Example

```bash theme={null}
# Delete section and its children
curl -X DELETE "https://api.artosai.com/api/v1/templates/tmpl-uuid-1/sections/sect-uuid-1" \
  -H "Authorization: Bearer YOUR_TOKEN"

# Delete only this section (leave children)
curl -X DELETE "https://api.artosai.com/api/v1/templates/tmpl-uuid-1/sections/sect-uuid-1?cascade_children=false" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

### Response

```json theme={null}
{
  "message": "Section deleted successfully",
  "deleted_section_id": "sect-uuid-1",
  "deleted_count": 1
}
```

### Response Fields

| Field                | Type    | Description                                                      |
| -------------------- | ------- | ---------------------------------------------------------------- |
| `message`            | string  | Success message                                                  |
| `deleted_section_id` | string  | UUID of the deleted section                                      |
| `deleted_count`      | integer | Total number of sections deleted (includes children if cascaded) |

### Status Codes

* **200 OK**: Section deleted successfully
* **400 Bad Request**: Invalid parameters
* **403 Forbidden**: Not authorized
* **404 Not Found**: Template or section not found
