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

# Run Automation Manually

> Execute automated clinical pathways for patient records

## Overview

Trigger automated or semi-automated clinical pathway execution for a patient record. This endpoint initiates the processing workflow that evaluates pathway conditions, executes actions, and manages the patient journey through the configured pathway.

## Endpoint

```
POST https://app.arahealth.io/api/v1/pub/records/automation
```

**Base URL:** `https://app.arahealth.io`
**Path:** `/api/v1/records/automation`
**Method:** `POST`

## Authentication

This endpoint requires Bearer token authentication.

### Headers

* `Authorization` (required) - Bearer token for authentication
* `Content-Type` (required) - Must be `application/json`

<Note>
  Contact Alto Health to obtain your authentication token. The token contains your organization, team, and user credentials.
</Note>

## Request Parameters

### Request Body

The request body should be a JSON object with the following fields:

| Field         | Type   | Required    | Description                                                        |
| ------------- | ------ | ----------- | ------------------------------------------------------------------ |
| `recordId`    | string | Yes         | Unique identifier for the patient record                           |
| `pathwayType` | string | Yes         | Type of pathway execution: `auto` or `semiAutomatic`               |
| `pathwayName` | string | Conditional | Name of the pathway to execute (required for `semiAutomatic` type) |

### Pathway Types

<AccordionGroup>
  <Accordion icon="bolt" title="auto - Fully Automated">
    The pathway runs automatically from start to finish without manual intervention. The system will:

    * Execute all pathway nodes sequentially
    * Evaluate conditions automatically
    * Complete actions without user input
    * Progress through the entire pathway flow

    **Use when:** You want the system to process the record completely automatically based on extracted data and configured rules.
  </Accordion>

  <Accordion icon="hand" title="semiAutomatic - Semi-Automated">
    The pathway executes with manual checkpoints where user review or intervention is required. The system will:

    * Pause at designated review points
    * Wait for user approval or input
    * Allow manual override of automated decisions
    * Resume execution after user action

    **Use when:** You need human oversight at critical decision points in the pathway.

    <Note>
      When using `semiAutomatic`, you must provide the `pathwayName` parameter to specify which pathway to execute.
    </Note>
  </Accordion>
</AccordionGroup>

## Code Examples

<CodeGroup>
  ```javascript JavaScript theme={null}
  const response = await fetch('https://app.arahealth.io/api/v1/pub/records/automation', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer your_auth_token',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      recordId: '6924b6882ccfec0e13b8e4b9',
      pathwayType: 'semiAutomatic',
      pathwayName: 'Achilles tendon pathology and rupture'
    })
  });

  const data = await response.json();
  console.log(data);
  // { status_code: 200, message: 'success', sub_message: 'success' }
  ```

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

  url = "https://app.arahealth.io/api/v1/pub/records/automation"

  payload = {
      "recordId": "6924b6882ccfec0e13b8e4b9",
      "pathwayType": "semiAutomatic",
      "pathwayName": "Achilles tendon pathology and rupture"
  }

  headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer your_auth_token'
  }

  response = requests.post(url, headers=headers, json=payload)
  print(response.json())
  # { "status_code": 200, "message": "success", "sub_message": "success" }
  ```

  ```bash cURL theme={null}
  curl -X POST https://app.arahealth.io/api/v1/pub/records/automation \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer your_auth_token" \
    -d '{
      "recordId": "6924b6882ccfec0e13b8e4b9",
      "pathwayType": "semiAutomatic",
      "pathwayName": "Achilles tendon pathology and rupture"
    }'
  ```
</CodeGroup>

## Response

### Success Response

A successful automation trigger returns:

```json theme={null}
{
  "status_code": 200,
  "message": "success",
  "sub_message": "success"
}
```

#### Response Fields

| Field         | Type   | Description                        |
| ------------- | ------ | ---------------------------------- |
| `status_code` | number | HTTP status code (200 for success) |
| `message`     | string | High-level status message          |
| `sub_message` | string | Additional status details          |

### Error Responses

#### Invalid Request (400)

```json theme={null}
{
  "status_code": 400,
  "message": "Invalid request",
  "detail": "recordId is required"
}
```

**Common causes:**

* Missing required fields (`recordId`, `pathwayType`)
* Invalid `recordId` format
* Missing `pathwayName` when using `semiAutomatic` type
* Invalid `pathwayType` value

#### Unauthorized (401)

```json theme={null}
{
  "status_code": 401,
  "message": "Unauthorized",
  "detail": "Invalid or expired token"
}
```

**Common causes:**

* Missing Authorization header
* Invalid Bearer token
* Expired authentication token

#### Record Not Found (404)

```json theme={null}
{
  "status_code": 404,
  "message": "Record not found",
  "detail": "No record found with the provided recordId"
}
```

**Common causes:**

* Invalid `recordId`
* Record belongs to a different organization/team
* Record has been archived or deleted

## Use Cases

<CardGroup cols={2}>
  <Card title="Automatic Triage" icon="robot">
    Trigger automatic pathway execution after document upload to classify and route referrals based on urgency and specialty.
  </Card>

  <Card title="Approval Workflows" icon="circle-check">
    Use semi-automatic pathways for cases requiring clinical review before proceeding with automated actions.
  </Card>

  <Card title="Batch Processing" icon="layer-group">
    Process multiple records through the same pathway by calling this endpoint for each record in a batch.
  </Card>

  <Card title="Integration Triggers" icon="plug">
    Integrate with external systems to automatically trigger pathways when new records are created.
  </Card>
</CardGroup>

## Example Workflow

<Steps>
  <Step title="Upload Document">
    Use the [Document Upload](/api-reference/endpoint/document-upload) endpoint to upload a patient referral document. Save the returned `recordId`.
  </Step>

  <Step title="Trigger Automation">
    Call the Run Automation Manually endpoint with the `recordId` to execute the clinical pathway. The pathway will automatically handle data extraction:

    ```javascript theme={null}
    await fetch('https://app.arahealth.io/api/v1/pub/records/automation', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer your_token',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        recordId: savedRecordId,
        pathwayType: 'auto'
      })
    });
    ```
  </Step>

  <Step title="Monitor Progress">
    The pathway executes asynchronously. Use webhooks or polling to monitor pathway execution status and completion.
  </Step>
</Steps>

## Pathway Execution

### What Happens When You Trigger Automation?

When you call this endpoint, Alto Health:

1. **Validates the Request** - Checks that the record exists and you have permission to access it
2. **Loads the Pathway** - Retrieves the configured pathway based on the type and name provided
3. **Initializes Execution** - Creates a run history record to track the pathway execution
4. **Processes Nodes** - Executes pathway nodes sequentially:
   * Evaluates conditions based on extracted data
   * Performs actions (notifications, status updates, etc.)
   * Makes routing decisions based on business rules
5. **Handles Wait Points** - For semi-automatic pathways, pauses at designated review nodes
6. **Completes or Pauses** - Either completes the pathway or waits for manual intervention

### Pathway Node Types

During execution, the pathway may include various node types:

* **Condition Nodes** - Evaluate rules based on extracted data
* **Action Nodes** - Perform operations like sending emails or updating status
* **Decision Nodes** - Route the record based on evaluation results
* **Wait Nodes** - Pause execution for manual review (semi-automatic only)

## Best Practices

<AccordionGroup>
  <Accordion icon="check-double" title="Validate Data Before Automation">
    Ensure that all required entity extraction is complete before triggering automation. Missing data may cause pathway execution to fail or make incorrect routing decisions.

    ```javascript theme={null}
    // Check extraction status first
    const jobStatus = await fetch(`https://app.arahealth.io/v1/jobs/${jobId}`);
    const { status } = await jobStatus.json();

    // Only trigger automation if extraction succeeded
    if (status === 'completed') {
      await fetch('/api/v1/records/automation', {
        method: 'POST',
        body: JSON.stringify({ recordId, pathwayType: 'auto' })
      });
    }
    ```
  </Accordion>

  <Accordion icon="arrows-rotate" title="Handle Asynchronous Execution">
    Pathway execution happens asynchronously. Don't expect immediate results. Use webhooks or implement polling to track completion.

    ```javascript theme={null}
    // Trigger automation
    const response = await fetch('/api/v1/records/automation', {
      method: 'POST',
      body: JSON.stringify({ recordId, pathwayType: 'auto' })
    });

    if (response.status === 200) {
      console.log('Automation started - results will be available asynchronously');
    }
    ```
  </Accordion>

  <Accordion icon="triangle-exclamation" title="Use Semi-Automatic for Critical Cases">
    For high-stakes clinical decisions, use `semiAutomatic` pathways to include human oversight at critical decision points.

    ```javascript theme={null}
    // High-priority case requiring review
    await fetch('/api/v1/records/automation', {
      method: 'POST',
      body: JSON.stringify({
        recordId,
        pathwayType: 'semiAutomatic',
        pathwayName: 'High Priority Review Pathway'
      })
    });
    ```
  </Accordion>

  <Accordion icon="shield" title="Verify Pathway Names">
    When using semi-automatic execution, ensure the pathway name exactly matches a configured pathway in your organization. Mismatched names will cause the request to fail.
  </Accordion>

  <Accordion icon="bug" title="Implement Error Handling">
    Always implement proper error handling for automation requests:

    ```javascript theme={null}
    try {
      const response = await fetch('/api/v1/records/automation', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ recordId, pathwayType: 'auto' })
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(`Automation failed: ${error.detail}`);
      }

      const result = await response.json();
      console.log('Automation triggered successfully:', result);
    } catch (error) {
      console.error('Failed to trigger automation:', error);
      // Implement retry logic or alert admins
    }
    ```
  </Accordion>
</AccordionGroup>

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Document Upload" icon="upload" href="/api-reference/endpoint/document-upload">
    Upload patient referral documents before triggering automation
  </Card>

  <Card title="Get Job Status" icon="clock" href="/api-reference/endpoint/get-job">
    Check the status of processing jobs
  </Card>

  <Card title="Webhooks" icon="webhook" href="/guides/webhooks">
    Set up webhooks to receive automation completion notifications
  </Card>
</CardGroup>

## Need Help?

<Card title="Contact Support" icon="headset">
  Email: [support@altohealth.io](mailto:support@altohealth.io)

  Include in your message:

  * Record ID
  * Pathway name (if applicable)
  * Error message and status code
  * Expected vs actual behavior
</Card>


## OpenAPI

````yaml POST /api/v1/pub/records/automation
openapi: 3.1.0
info:
  title: Alto HealthAPI
  description: API for managing healthcare records and document uploads
  version: 1.0.0
servers:
  - url: https://app.arahealth.io
security:
  - bearerAuth: []
paths:
  /api/v1/pub/records/automation:
    post:
      summary: Run Automation Manually
      description: >-
        Execute automated or semi-automated clinical pathway for a patient
        record
      requestBody:
        description: Automation execution request
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AutomationRequest'
      responses:
        '200':
          description: Automation triggered successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AutomationResponse'
        '400':
          description: Bad request - invalid input or missing required fields
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AutomationError'
        '401':
          description: Unauthorized - invalid or expired token
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AutomationError'
        '404':
          description: Record not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AutomationError'
components:
  schemas:
    AutomationRequest:
      type: object
      required:
        - recordId
        - pathwayType
      properties:
        recordId:
          type: string
          description: Unique identifier for the patient record
          example: 6924b6882ccfec0e13b8e4b9
        pathwayType:
          type: string
          description: Type of pathway execution
          enum:
            - auto
            - semiAutomatic
          example: semiAutomatic
        pathwayName:
          type: string
          description: Name of the pathway to execute (required for semiAutomatic type)
          example: Achilles tendon pathology and rupture
    AutomationResponse:
      type: object
      properties:
        status_code:
          type: integer
          description: HTTP status code
          example: 200
        message:
          type: string
          description: High-level status message
          example: success
        sub_message:
          type: string
          description: Additional status details
          example: success
    AutomationError:
      type: object
      properties:
        status_code:
          type: integer
          description: HTTP status code
          example: 400
        message:
          type: string
          description: Error message
          example: Invalid request
        detail:
          type: string
          description: Detailed error information
          example: recordId is required
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API Key
      description: Bearer token authentication using your Alto Health API key

````