# Aperion Flow API Reference

## Overview

Aperion Flow provides a REST API for pipeline management and execution.

**Base URL:** `http://localhost:8001`

---

## Endpoints

### Health Check

#### GET /healthz

Liveness probe for container orchestration.

**Response:**
```json
{
  "status": "ok"
}
```

#### GET /readyz

Readiness probe indicating service is ready to accept requests.

**Response:**
```json
{
  "status": "ready"
}
```

#### GET /flow/health

Detailed health status.

**Response:**
```json
{
  "status": "healthy",
  "service": "aperion-flow",
  "timestamp": "2026-02-08T07:00:00Z"
}
```

---

### Pipeline Execution

#### POST /flow/start

Start a new pipeline execution.

**Request Body:**
```json
{
  "pipeline": {
    "name": "data_etl",
    "stages": [
      {
        "id": "fetch",
        "name": "Fetch Data",
        "handler": "app.handlers.fetch",
        "timeout": 30.0
      },
      {
        "id": "process",
        "name": "Process Data",
        "handler": "app.handlers.process",
        "depends_on": ["fetch"],
        "retry_count": 3
      },
      {
        "id": "store",
        "name": "Store Results",
        "handler": "app.handlers.store",
        "depends_on": ["process"]
      }
    ],
    "max_parallel": 2,
    "timeout": 300.0,
    "fail_fast": true
  },
  "initial_data": {
    "source_url": "https://api.example.com/data"
  },
  "correlation_id": "req-12345"
}
```

**Response (202 Accepted):**
```json
{
  "execution_id": "550e8400-e29b-41d4-a716-446655440000",
  "pipeline_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "pipeline_name": "data_etl",
  "status": "completed",
  "stages_total": 3,
  "stages_completed": 3,
  "stages_failed": 0,
  "stages_skipped": 0,
  "started_at": "2026-02-08T07:00:00Z",
  "completed_at": "2026-02-08T07:00:45Z",
  "error": null
}
```

**Error Response (500):**
```json
{
  "detail": "Pipeline execution failed: Handler not found"
}
```

---

#### POST /flow/resume

Resume a pipeline from its last checkpoint.

**Request Body:**
```json
{
  "pipeline": {
    "name": "data_etl",
    "stages": [...]
  },
  "execution_id": "550e8400-e29b-41d4-a716-446655440000",
  "correlation_id": "req-12346"
}
```

**Response (202 Accepted):**
```json
{
  "execution_id": "550e8400-e29b-41d4-a716-446655440000",
  "pipeline_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "pipeline_name": "data_etl",
  "status": "completed",
  "stages_total": 3,
  "stages_completed": 3,
  "stages_failed": 0,
  "stages_skipped": 0,
  "started_at": "2026-02-08T07:00:00Z",
  "completed_at": "2026-02-08T07:01:00Z",
  "error": null
}
```

**Error Response (404):**
```json
{
  "detail": "No checkpoint found for execution: 550e8400-..."
}
```

---

#### GET /flow/{execution_id}

Get the status of a pipeline execution.

**Path Parameters:**
- `execution_id` (string, required): The execution UUID

**Response (200):**
```json
{
  "execution_id": "550e8400-e29b-41d4-a716-446655440000",
  "pipeline_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "pipeline_name": "data_etl",
  "status": "running",
  "stages_total": 3,
  "stages_completed": 1,
  "stages_failed": 0,
  "stages_skipped": 0,
  "started_at": "2026-02-08T07:00:00Z",
  "completed_at": null,
  "error": null
}
```

**Error Response (404):**
```json
{
  "detail": "Execution not found: 550e8400-..."
}
```

---

#### GET /flow/{execution_id}/data

Get the output data from a completed pipeline execution.

**Response (200):**
```json
{
  "execution_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "data": {
    "fetched_records": 1000,
    "processed_records": 995,
    "stored_location": "s3://bucket/results/output.json"
  }
}
```

---

#### GET /flow/

List pipeline executions.

**Query Parameters:**
- `status` (string, optional): Filter by status (`pending`, `running`, `completed`, `failed`, `cancelled`)
- `limit` (integer, optional): Maximum results (default: 50, max: 100)

**Response (200):**
```json
[
  {
    "execution_id": "550e8400-e29b-41d4-a716-446655440000",
    "pipeline_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
    "pipeline_name": "data_etl",
    "status": "completed",
    "stages_total": 3,
    "stages_completed": 3,
    "stages_failed": 0,
    "stages_skipped": 0,
    "started_at": "2026-02-08T07:00:00Z",
    "completed_at": "2026-02-08T07:00:45Z",
    "error": null
  }
]
```

---

#### DELETE /flow/{execution_id}

Delete an execution record.

**Response (204 No Content):**
Empty body on success.

**Error Response (404):**
```json
{
  "detail": "Execution not found: 550e8400-..."
}
```

---

## Models

### Pipeline

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | string (UUID) | No | Auto-generated if not provided |
| name | string | Yes | Pipeline name |
| description | string | No | Pipeline description |
| version | string | No | Version string (default: "1.0.0") |
| stages | array[PipelineStage] | Yes | List of stages |
| max_parallel | integer | No | Max concurrent stages (default: 4) |
| timeout | number | No | Total timeout in seconds (default: 300) |
| fail_fast | boolean | No | Stop on first failure (default: true) |
| category | string | No | Pipeline category |
| tags | array[string] | No | Tags for filtering |
| metadata | object | No | Arbitrary metadata |

### PipelineStage

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | string (UUID) | No | Auto-generated if not provided |
| name | string | Yes | Stage name |
| description | string | No | Stage description |
| handler | string | Yes | Fully qualified handler name |
| timeout | number | No | Stage timeout in seconds (default: 30) |
| retry_count | integer | No | Retry attempts (default: 0) |
| retry_delay | number | No | Delay between retries (default: 1.0) |
| depends_on | array[string] | No | Stage IDs this depends on |
| condition | string | No | Condition expression |
| skip_on_failure | boolean | No | Skip if dependency failed |
| llm_assistance | array[LLMAssistanceConfig] | No | LLM assistance configs |
| tags | array[string] | No | Tags |
| metadata | object | No | Arbitrary metadata |

### LLMAssistanceConfig

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| mode | string | Yes | One of: `pre_validate`, `enrich_context`, `analyze_output`, `error_diagnosis` |
| enabled | boolean | No | Enable this mode (default: true) |
| timeout | number | No | LLM call timeout (default: 10.0) |
| cache_results | boolean | No | Cache LLM responses (default: true) |
| fallback_on_error | boolean | No | Continue if LLM fails (default: true) |
| prompt_template | string | No | Custom prompt template |
| metadata | object | No | Additional metadata |

### ExecutionStatusResponse

| Field | Type | Description |
|-------|------|-------------|
| execution_id | string | Execution UUID |
| pipeline_id | string | Pipeline UUID |
| pipeline_name | string | Pipeline name |
| status | string | One of: `pending`, `running`, `paused`, `completed`, `failed`, `cancelled` |
| stages_total | integer | Total number of stages |
| stages_completed | integer | Completed stages |
| stages_failed | integer | Failed stages |
| stages_skipped | integer | Skipped stages |
| started_at | datetime | Execution start time |
| completed_at | datetime | Execution end time |
| error | string | Error message if failed |

---

## Status Codes

| Code | Description |
|------|-------------|
| 200 | Success |
| 202 | Accepted (async operation started) |
| 204 | No Content (delete successful) |
| 400 | Bad Request (invalid input) |
| 404 | Not Found |
| 500 | Internal Server Error |

---

## Examples

### cURL Examples

**Start a pipeline:**
```bash
curl -X POST http://localhost:8001/flow/start \
  -H "Content-Type: application/json" \
  -d '{
    "pipeline": {
      "name": "hello_world",
      "stages": [
        {"name": "greet", "handler": "app.greet"}
      ]
    }
  }'
```

**Get execution status:**
```bash
curl http://localhost:8001/flow/550e8400-e29b-41d4-a716-446655440000
```

**List completed executions:**
```bash
curl "http://localhost:8001/flow/?status=completed&limit=10"
```

**Resume from checkpoint:**
```bash
curl -X POST http://localhost:8001/flow/resume \
  -H "Content-Type: application/json" \
  -d '{
    "pipeline": {"name": "...", "stages": [...]},
    "execution_id": "550e8400-e29b-41d4-a716-446655440000"
  }'
```

### Python Client Example

```python
import httpx

async def run_pipeline():
    async with httpx.AsyncClient() as client:
        # Start pipeline
        response = await client.post(
            "http://localhost:8001/flow/start",
            json={
                "pipeline": {
                    "name": "example",
                    "stages": [
                        {"name": "step1", "handler": "app.step1"},
                        {"name": "step2", "handler": "app.step2", "depends_on": ["step1"]},
                    ]
                },
                "initial_data": {"input": "value"}
            }
        )
        result = response.json()
        print(f"Execution ID: {result['execution_id']}")
        print(f"Status: {result['status']}")
        
        # Get output data
        data_response = await client.get(
            f"http://localhost:8001/flow/{result['execution_id']}/data"
        )
        print(f"Output: {data_response.json()['data']}")
```
