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

# Run Workflow

> Create a fresh workflow run.

Create a workflow run. The canonical API route is flat: `workflow_id` belongs
in the request body, not in the URL.

The response returns immediately with `lifecycle.status` set to `"running"` or
`"pending"` — use the Get Run endpoint to check for updates.

Workflows can accept two types of inputs:

* **documents**: File inputs for Document (start) blocks
* **json\_inputs**: JSON data for JSON Input (start\_json) blocks

<RequestExample>
  ```python Python theme={null}
  from retab import MIMEData, Retab

  client = Retab()

  document = MIMEData(
      filename="invoice.pdf",
      url="https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf",
  )

  # Run with documents only
  run = client.workflows.runs.create(
      workflow_id="wf_abc123xyz",
      documents={
          "start_document-block-1": document,
      }
  )

  # Run with documents and JSON inputs
  run = client.workflows.runs.create(
      workflow_id="wf_abc123xyz",
      documents={
          "start_document-block-1": document,
      },
      json_inputs={
          "start-json-block-1": {"customer_id": "cust_123", "priority": "high"},
      }
  )

  print(f"Run started: {run.id}")
  print(f"Lifecycle: {run.lifecycle.status}")
  ```

  ```typescript TypeScript theme={null}
  import { Retab } from "@retab/node";

  const client = new Retab({ apiKey: process.env.RETAB_API_KEY });

  const document = {
    filename: "invoice.pdf",
    url: "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf",
  };

  // Run with documents only
  const run = await client.workflows.runs.create(
    "wf_abc123xyz",
    {
      "start_document-block-1": document,
    },
  );

  // Run with documents and JSON inputs
  const run2 = await client.workflows.runs.create(
    "wf_abc123xyz",
    {
      "start_document-block-1": document,
    },
    {
      "start-json-block-1": { customer_id: "cust_123", priority: "high" },
    },
  );

  console.log(`Run started: ${run.id}`);
  console.log(`Lifecycle: ${run.lifecycle.status}`);
  console.log(`Second run started: ${run2.id}`);
  ```

  ```go Go theme={null}
  package main

  import (
  	"context"
  	"fmt"
  	"log"

  	retab "github.com/retab-dev/retab/clients/go"
  )

  func main() {
  	ctx := context.Background()

  	client, err := retab.NewClient("")
  	if err != nil {
  		log.Fatal(err)
  	}

  	// Run with documents only
  	document := retab.MIMEData{
  		Filename: "invoice.pdf",
  		URL:      "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf",
  	}

  	run, err := client.Workflows.Runs.Create(ctx, &retab.WorkflowRunsCreateParams{
  		WorkflowID: "wf_abc123xyz",
  		Documents: &map[string]any{
  			"start_document-block-1": document,
  		},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	// Run with documents and JSON inputs
  	run2, err := client.Workflows.Runs.Create(ctx, &retab.WorkflowRunsCreateParams{
  		WorkflowID: "wf_abc123xyz",
  		Documents: &map[string]any{
  			"start_document-block-1": document,
  		},
  		JSONInputs: &map[string]any{
  			"start-json-block-1": map[string]any{
  				"customer_id": "cust_123",
  				"priority":    "high",
  			},
  		},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	fmt.Printf("Run started: %s\n", run.ID)
  	fmt.Printf("Lifecycle: %v\n", run.Lifecycle.Status())
  	_ = run2
  }
  ```

  ```ruby Ruby theme={null}
  require 'retab'

  client = Retab::Client.new(api_key: ENV['RETAB_API_KEY'])

  document = {
    filename: 'invoice.pdf',
    url: 'https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf',
  }

  # Run with documents only
  run = client.workflows.runs.create(
    workflow_id: 'wf_abc123xyz',
    documents: {
      'start_document-block-1' => document,
    },
  )

  # Run with documents and JSON inputs
  run = client.workflows.runs.create(
    workflow_id: 'wf_abc123xyz',
    documents: {
      'start_document-block-1' => document,
    },
    json_inputs: {
      'start-json-block-1' => { customer_id: 'cust_123', priority: 'high' },
    },
  )

  puts "Run started: #{run.id}"
  puts "Lifecycle: #{run.lifecycle.status}"
  ```

  ```rust Rust theme={null}
  use retab::models::CreateWorkflowRunRequest;
  use retab::resources::workflow_runs::CreateParams;
  use retab::{MimeData, Retab};
  use std::collections::HashMap;

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = Retab::new(std::env::var("RETAB_API_KEY")?);
      let document = MimeData::new(
          "invoice.pdf",
          "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf",
      );

      // Run with documents only
      let request = CreateWorkflowRunRequest::new("wf_abc123xyz")
          .with_document("start_document-block-1", document);
      let run = client
          .workflows().runs()
          .create(CreateParams::new(request))
          .await?;

      // Run with JSON inputs
      let mut json_inputs: HashMap<String, serde_json::Value> = HashMap::new();
      json_inputs.insert(
          "start-json-block-1".into(),
          serde_json::json!({"customer_id": "cust_123", "priority": "high"}),
      );
      let _run = client
          .workflows().runs()
          .create(CreateParams::new(CreateWorkflowRunRequest {
              workflow_id: "wf_abc123xyz".into(),
              documents: None,
              json_inputs: Some(json_inputs),
              version: None,
              metadata: None,
          }))
          .await?;

      println!("Run started: {}", run.id);
      Ok(())
  }
  ```

  ```php PHP theme={null}
  <?php
  require 'vendor/autoload.php';

  use Retab\Client;

  $client = new Client(apiKey: getenv('RETAB_API_KEY'));

  $run = $client->workflows()->runs()->create(
      workflowId: 'wf_abc123xyz',
      documents: [
          'start_document-block-1' => [
              'filename' => 'invoice.pdf',
              'url' => 'https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf',
          ],
      ],
      jsonInputs: [
          'start-json-block-1' => ['customer_id' => 'cust_123', 'priority' => 'high'],
      ],
  );
  print_r($run);
  ```

  ```csharp C# theme={null}
  using System;
  using System.Collections.Generic;
  using Retab;
  using RetabClient = Retab.Retab;

  var apiKey = Environment.GetEnvironmentVariable("RETAB_API_KEY")!;
  var client = new RetabClient(apiKey);

  var result = await client.Workflows.Runs.CreateAsync(
      new WorkflowRunsCreateOptions
      {
          WorkflowId = "wf_abc123xyz",
          Documents = new Dictionary<string, WorkflowRunDocumentInput>
          {
              ["start_document-block-1"] = MimeData.FromUrl(new Uri("https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf")),
          },
      }
  );
  Console.WriteLine(result);
  ```

  ```java Java theme={null}
  import com.retab.RetabClient;

  public final class Example {
    public static void main(String[] args) throws Exception {
      RetabClient client = new RetabClient(System.getenv("RETAB_API_KEY"));

      var result = client.workflows().runs().create("wf_abc123", null, null, null, null);
      System.out.println(result);
    }
  }
  ```

  ```curl cURL theme={null}
  # Run with documents only
  curl -X 'POST' \
    'https://api.retab.com/v1/workflows/runs' \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer <your-api-key>' \
    -d '{
      "workflow_id": "wf_abc123xyz",
      "documents": {
        "start_document-block-1": {
          "filename": "invoice.pdf",
          "url": "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf"
        }
      }
    }'

  # Run with documents and JSON inputs
  curl -X 'POST' \
    'https://api.retab.com/v1/workflows/runs' \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer <your-api-key>' \
    -d '{
      "workflow_id": "wf_abc123xyz",
      "documents": {
        "start_document-block-1": {
          "filename": "invoice.pdf",
          "url": "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf"
        }
      },
      "json_inputs": {
        "start-json-block-1": {
          "customer_id": "cust_123",
          "priority": "high"
        }
      }
    }'

  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "id": "run_abc123xyz",
    "workflow": {
      "workflow_id": "wf_abc123xyz",
      "version_id": "ver_abc123xyz"
    },
    "trigger": { "type": "api" },
    "lifecycle": { "status": "running" },
    "timing": {
      "created_at": "2024-01-15T10:30:00Z",
      "started_at": "2024-01-15T10:30:00Z",
      "completed_at": null
    },
    "inputs": {
      "documents": {
        "start_document-block-1": {
          "id": "file_123",
          "filename": "invoice.pdf",
          "mime_type": "application/pdf"
        }
      },
      "json_data": {}
    }
  }
  ```

  ```json 400 theme={null}
  {
    "detail": "Missing input documents for start_document blocks: Invoice Input, Receipt Input"
  }
  ```

  ```json 404 theme={null}
  {
    "detail": "Workflow not found"
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /v1/workflows/runs
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://api.retab.com
security: []
paths:
  /v1/workflows/runs:
    post:
      tags:
        - Workflows
        - Workflow Runs
      summary: Create Workflow Run
      description: Create a fresh workflow run.
      operationId: create_workflow_run
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateWorkflowRunRequest'
        required: true
      responses:
        '202':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorkflowRun'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    CreateWorkflowRunRequest:
      properties:
        workflow_id:
          type: string
          title: Workflow Id
          description: Workflow id for the fresh run.
        documents:
          additionalProperties:
            $ref: '#/components/schemas/MIMEData'
          type: object
          title: Documents
          description: Mapping of start_document block IDs to their input documents.
          default: {}
        json_inputs:
          additionalProperties: true
          type: object
          title: Json Inputs
          description: Mapping of start-json block IDs to their input JSON data.
          default: {}
        version:
          type: string
          title: Version
          description: >-
            Workflow version to run: 'production', 'draft', or a pinned version
            id like 'ver_...'. Only valid for fresh-run creation.
          default: production
          examples:
            - production
            - draft
            - ver_abc123def456
        metadata:
          anyOf:
            - additionalProperties:
                type: string
              type: object
            - type: 'null'
          title: Metadata
          description: User-defined metadata to associate with this workflow run.
      type: object
      required:
        - workflow_id
      title: CreateWorkflowRunRequest
      description: >-
        Create a new workflow run from a workflow id, an optional version
        selector, and optional inputs.
    WorkflowRun:
      properties:
        id:
          type: string
          title: Id
          description: Unique ID for this run
        workflow_id:
          type: string
          title: Workflow Id
          description: ID of the workflow that was run
        workflow_version_id:
          type: string
          title: Workflow Version Id
          description: Content-addressed workflow version used for this run.
        trigger:
          $ref: '#/components/schemas/TriggerInfo'
          description: What started this run
        lifecycle:
          oneOf:
            - $ref: '#/components/schemas/PendingRun'
            - $ref: '#/components/schemas/RunningRun'
            - $ref: '#/components/schemas/AwaitingReviewRun'
            - $ref: '#/components/schemas/CompletedTerminal'
            - $ref: '#/components/schemas/ErrorTerminal'
            - $ref: '#/components/schemas/CancelledTerminal'
          title: Lifecycle
          description: Lifecycle state of the run.
          discriminator:
            propertyName: status
            mapping:
              awaiting_review:
                $ref: '#/components/schemas/AwaitingReviewRun'
              cancelled:
                $ref: '#/components/schemas/CancelledTerminal'
              completed:
                $ref: '#/components/schemas/CompletedTerminal'
              error:
                $ref: '#/components/schemas/ErrorTerminal'
              pending:
                $ref: '#/components/schemas/PendingRun'
              running:
                $ref: '#/components/schemas/RunningRun'
        timing:
          $ref: '#/components/schemas/RunTiming'
          description: All timing information
        inputs:
          $ref: '#/components/schemas/RunInputs'
          description: Input payloads supplied at run creation time
          default:
            documents: {}
            json_data: {}
        metadata:
          anyOf:
            - additionalProperties:
                type: string
              type: object
            - type: 'null'
          title: Metadata
          description: User-defined metadata associated with this workflow run.
      type: object
      required:
        - id
        - lifecycle
        - timing
        - trigger
        - workflow_id
        - workflow_version_id
      title: WorkflowRun
      description: A single execution of a workflow.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
          default: []
      type: object
      title: HTTPValidationError
    MIMEData:
      properties:
        filename:
          type: string
          title: Filename
          description: The filename of the file
          examples:
            - file.pdf
            - image.png
            - data.txt
        url:
          type: string
          title: Url
          description: The URL of the file in base64 format
          examples:
            - data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...
      additionalProperties: false
      type: object
      required:
        - filename
        - url
      title: MIMEData
      description: A file represented by its `filename` and a base64 data `url`.
    TriggerInfo:
      properties:
        type:
          type: string
          enum:
            - manual
            - api
            - schedule
            - webhook
            - email
            - custom
            - restart
          title: Type
          description: What started this run
      type: object
      required:
        - type
      title: TriggerInfo
      description: |-
        Public summary of what started a run: just the trigger category.

        The full per-variant detail (schedule_id, parent_run_id, sender, ...) is
        kept internally on `StoredWorkflowRun.trigger` but intentionally not
        exposed in the public API surface.
    PendingRun:
      properties:
        status:
          type: string
          const: pending
          title: Status
          default: pending
      type: object
      title: PendingRun
      description: The run has been created but execution has not started.
    RunningRun:
      properties:
        status:
          type: string
          const: running
          title: Status
          default: running
      type: object
      title: RunningRun
      description: The run is currently executing.
    AwaitingReviewRun:
      properties:
        status:
          type: string
          const: awaiting_review
          title: Status
          default: awaiting_review
        waiting_for_block_ids:
          items:
            type: string
          type: array
          title: Waiting For Block Ids
          description: Block IDs that are waiting for review
          default: []
      type: object
      title: AwaitingReviewRun
      description: The run is paused on at least one gated block.
    CompletedTerminal:
      properties:
        status:
          type: string
          const: completed
          title: Status
          default: completed
      type: object
      title: CompletedTerminal
      description: The run finished successfully.
    ErrorTerminal:
      properties:
        status:
          type: string
          const: error
          title: Status
          default: error
        message:
          type: string
          title: Message
          description: Human-readable error message
        stage:
          anyOf:
            - type: string
              enum:
                - input_collection
                - registry_lookup
                - document_fetch
                - execution
                - output_storage
                - routing
                - history_payload
            - type: 'null'
          title: Stage
          description: Which execution stage failed
        category:
          anyOf:
            - type: string
              enum:
                - transient
                - permanent
                - quota
            - type: 'null'
          title: Category
          description: Error category for retry decisions
        details:
          anyOf:
            - $ref: '#/components/schemas/ErrorDetails'
            - type: 'null'
          description: Detailed error context including stack trace
        failing_step_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Failing Step Id
          description: >-
            Step ID of the failing step, when the failure was attributable to a
            specific step
      type: object
      required:
        - message
      title: ErrorTerminal
      description: The run failed. All loose error fields are bundled here.
    CancelledTerminal:
      properties:
        status:
          type: string
          const: cancelled
          title: Status
          default: cancelled
        reason:
          anyOf:
            - type: string
            - type: 'null'
          title: Reason
          description: Human-readable reason, when known
      type: object
      title: CancelledTerminal
      description: The run was cancelled before reaching a natural terminal state.
    RunTiming:
      properties:
        created_at:
          type: string
          format: date-time
          title: Created At
          description: When the run record was created
        started_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Started At
          description: When the run started executing
        completed_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Completed At
          description: When the run finished executing
      type: object
      title: RunTiming
      description: |-
        Timing information for a run.

        Three event timestamps that consumers cannot reconstruct on their own.
        Wall-clock duration is a trivial `completed_at - started_at` subtraction
        done client-side; it is not stored or exposed.
    RunInputs:
      properties:
        documents:
          additionalProperties:
            $ref: '#/components/schemas/FileRef'
          type: object
          title: Documents
          description: start_document block ID -> input document reference
          default: {}
        json_data:
          additionalProperties: true
          type: object
          title: Json Data
          description: start-json block ID -> input JSON data
          default: {}
      type: object
      title: RunInputs
      description: Input payloads supplied at run creation time.
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
        input:
          title: Input
          default: null
        ctx:
          type: object
          title: Context
          default: {}
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    ErrorDetails:
      properties:
        message:
          anyOf:
            - type: string
            - type: 'null'
          title: Message
          description: >-
            Human-readable error message. Free-text; the structured fields below
            are the machine-readable counterpart.
        stack_trace:
          anyOf:
            - type: string
            - type: 'null'
          title: Stack Trace
          description: Full stack trace
        block_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Block Id
          description: ID of the block that failed
        block_name:
          anyOf:
            - type: string
            - type: 'null'
          title: Block Name
          description: Name/label of the block that failed
        error_code:
          anyOf:
            - type: string
            - type: 'null'
          title: Error Code
          description: Error code if available
        context:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Context
          description: Additional context about the error
      type: object
      title: ErrorDetails
      description: |-
        Detailed error information for debugging.

        Captures stack traces and context about where and why an error occurred.
    FileRef:
      properties:
        id:
          type: string
          title: Id
          description: ID of the file
        filename:
          type: string
          title: Filename
          description: Filename of the file
        mime_type:
          type: string
          title: Mime Type
          description: MIME type of the file
      type: object
      required:
        - filename
        - id
        - mime_type
      title: FileRef
      description: Public/shared file reference used across SDK and customer-facing APIs.
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````