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

# Run Flow

> POST /api/v1/flows/{flowId}/run

Execute a flow to process a document. This is the primary endpoint for document extraction.

## Endpoint

```
POST https://app.doclo.ai/api/v1/flows/{flowId}/run
```

## Authentication

Requires an API key with `flows:execute` scope.

```bash theme={null}
Authorization: Bearer dc_live_your_api_key
```

## Path Parameters

| Parameter | Type   | Description                       |
| --------- | ------ | --------------------------------- |
| `flowId`  | string | **Required.** The flow identifier |

## Request Body

```json theme={null}
{
  "version": "1.2.0",
  "wait": false,
  "timeout": 30000,
  "idempotencyKey": "unique-request-123",
  "webhookUrl": "https://your-server.com/webhook",
  "webhookSecret": "your_webhook_secret",
  "metadata": {
    "customerId": "cust_123",
    "source": "upload"
  },
  "input": {
    "document": {
      "base64": "data:application/pdf;base64,JVBERi0xLjQK...",
      "filename": "invoice.pdf",
      "mimeType": "application/pdf"
    },
    "variables": {
      "extractLineItems": true
    }
  }
}
```

### Request Fields

| Field                     | Type    | Required | Description                                               |
| ------------------------- | ------- | -------- | --------------------------------------------------------- |
| `version`                 | string  | No       | Flow version to use (default: latest)                     |
| `wait`                    | boolean | No       | Wait for completion (default: false)                      |
| `timeout`                 | number  | No       | Sync wait timeout in ms (default: 30000, max: 60000)      |
| `idempotencyKey`          | string  | No       | Unique key for request deduplication                      |
| `webhookUrl`              | string  | No       | URL to receive completion webhook                         |
| `webhookSecret`           | string  | No       | Secret for webhook signature verification                 |
| `metadata`                | object  | No       | Custom metadata (returned in results)                     |
| `input`                   | object  | **Yes**  | Flow input data                                           |
| `input.document`          | object  | **Yes**  | Document to process                                       |
| `input.document.base64`   | string  | **Yes**  | Base64-encoded document (with or without data URL prefix) |
| `input.document.filename` | string  | No       | Original filename                                         |
| `input.document.mimeType` | string  | No       | MIME type (auto-detected if omitted)                      |
| `input.variables`         | object  | No       | Flow-specific variables                                   |

## Response

### Async Response (200 OK)

When `wait: false` (default), returns immediately with execution ID:

```json theme={null}
{
  "id": "exec_abc123def456",
  "flowId": "invoice-extractor",
  "version": "1.2.0",
  "status": "pending",
  "createdAt": "2024-02-20T15:30:00Z",
  "metadata": {
    "customerId": "cust_123",
    "source": "upload"
  }
}
```

Poll [GET /runs/{executionId}](/api-reference/runs/get) to check status and retrieve results.

### Sync Response (200 OK)

When `wait: true`, waits for completion (up to timeout):

```json theme={null}
{
  "id": "exec_abc123def456",
  "flowId": "invoice-extractor",
  "version": "1.2.0",
  "status": "completed",
  "createdAt": "2024-02-20T15:30:00Z",
  "completedAt": "2024-02-20T15:30:12Z",
  "output": {
    "invoiceNumber": "INV-2024-001",
    "date": "2024-02-15",
    "vendor": {
      "name": "Acme Corporation",
      "address": "123 Business St, City, ST 12345"
    },
    "lineItems": [
      {
        "description": "Professional Services",
        "quantity": 10,
        "unitPrice": 150.00,
        "total": 1500.00
      }
    ],
    "subtotal": 1500.00,
    "tax": 127.50,
    "total": 1627.50
  },
  "metrics": {
    "durationMs": 12340,
    "pageCount": 2,
    "creditsUsed": 4
  },
  "metadata": {
    "customerId": "cust_123",
    "source": "upload"
  }
}
```

### Response Fields

| Field                 | Type   | Description                                              |
| --------------------- | ------ | -------------------------------------------------------- |
| `id`                  | string | Unique execution identifier                              |
| `flowId`              | string | Flow that was executed                                   |
| `version`             | string | Flow version used                                        |
| `status`              | string | `pending`, `running`, `completed`, `failed`, `cancelled` |
| `createdAt`           | string | ISO 8601 start timestamp                                 |
| `completedAt`         | string | ISO 8601 completion timestamp (if finished)              |
| `output`              | object | Extracted data (when completed)                          |
| `error`               | object | Error details (when failed)                              |
| `metrics`             | object | Execution metrics (when completed)                       |
| `metrics.durationMs`  | number | Processing time in milliseconds                          |
| `metrics.pageCount`   | number | Number of pages processed                                |
| `metrics.creditsUsed` | number | Credits consumed                                         |
| `metadata`            | object | Custom metadata from request                             |

## Examples

### Basic Async Execution

```bash theme={null}
curl -X POST https://app.doclo.ai/api/v1/flows/invoice-extractor/run \
  -H "Authorization: Bearer dc_live_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "document": {
        "base64": "data:application/pdf;base64,JVBERi0xLjQK..."
      }
    }
  }'
```

### Sync Execution

```bash theme={null}
curl -X POST https://app.doclo.ai/api/v1/flows/invoice-extractor/run \
  -H "Authorization: Bearer dc_live_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "wait": true,
    "timeout": 30000,
    "input": {
      "document": {
        "base64": "data:application/pdf;base64,JVBERi0xLjQK..."
      }
    }
  }'
```

### With Webhook

```bash theme={null}
curl -X POST https://app.doclo.ai/api/v1/flows/invoice-extractor/run \
  -H "Authorization: Bearer dc_live_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "webhookUrl": "https://your-server.com/doclo-webhook",
    "webhookSecret": "whsec_your_secret",
    "input": {
      "document": {
        "base64": "data:application/pdf;base64,JVBERi0xLjQK..."
      }
    }
  }'
```

### TypeScript

```typescript theme={null}
import * as fs from 'fs';

// Read and encode document
const pdfBuffer = fs.readFileSync('invoice.pdf');
const base64 = `data:application/pdf;base64,${pdfBuffer.toString('base64')}`;

// Execute flow
const response = await fetch(
  'https://app.doclo.ai/api/v1/flows/invoice-extractor/run',
  {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.DOCLO_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      wait: true,
      input: {
        document: {
          base64,
          filename: 'invoice.pdf',
          mimeType: 'application/pdf'
        }
      }
    })
  }
);

const result = await response.json();

if (result.status === 'completed') {
  console.log('Invoice Number:', result.output.invoiceNumber);
  console.log('Total:', result.output.total);
} else if (result.status === 'failed') {
  console.error('Extraction failed:', result.error);
}
```

### With Idempotency

```typescript theme={null}
// Safe to retry - same idempotencyKey returns same execution
const response = await fetch(
  'https://app.doclo.ai/api/v1/flows/invoice-extractor/run',
  {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      idempotencyKey: `invoice-${documentHash}-${Date.now()}`,
      input: { document: { base64: documentData } }
    })
  }
);
```

## Errors

| Status | Code                   | Description                                 |
| ------ | ---------------------- | ------------------------------------------- |
| 400    | `INVALID_INPUT`        | Invalid JSON or missing required fields     |
| 401    | `UNAUTHORIZED`         | Missing or invalid API key                  |
| 402    | `INSUFFICIENT_CREDITS` | Not enough credits                          |
| 403    | `FORBIDDEN`            | API key missing `flows:execute` scope       |
| 404    | `FLOW_NOT_FOUND`       | Flow doesn't exist                          |
| 404    | `VERSION_NOT_FOUND`    | Requested version doesn't exist             |
| 422    | `VALIDATION_ERROR`     | Input doesn't match schema                  |
| 422    | `INVALID_DOCUMENT`     | Document is corrupted or unsupported format |
| 429    | `RATE_LIMITED`         | Rate limit exceeded                         |
| 429    | `CONCURRENT_LIMIT`     | Too many concurrent executions              |
| 504    | `EXECUTION_TIMEOUT`    | Sync wait timeout exceeded                  |

## Sync vs Async

| Mode                  | Use When                               | Timeout | Result          |
| --------------------- | -------------------------------------- | ------- | --------------- |
| Async (`wait: false`) | Large documents, background processing | None    | Poll or webhook |
| Sync (`wait: true`)   | Small documents, immediate response    | Max 60s | Direct response |

For documents over 10 pages or complex flows, async execution with webhooks is recommended.

## Next Steps

<CardGroup cols={2}>
  <Card title="Get Execution" icon="magnifying-glass" href="/api-reference/runs/get">
    Poll for async results
  </Card>

  <Card title="Webhooks" icon="bell" href="/cloud/webhooks">
    Set up webhook handlers
  </Card>
</CardGroup>
