> ## 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.

# Export Runs

> Build CSV content for workflow run exports.

Export run results for one block as structured CSV. Useful for pulling extract or classify outputs out of Retab in bulk for downstream analytics, BI tools, or spreadsheets.

You pick:

* **Which workflow + which block** to export (`workflow_id`, `block_id`).
* **What to export** for that block (`export_source`):
  * `"outputs"` (default) — what the block produced.
  * `"inputs"` — what the block received.
* **Which runs** to include — either a fixed list (`selected_run_ids`) or all runs that match the filters (`status`, `exclude_status`, `from_date`, `to_date`, `trigger_type`).
* **Column ordering** via `preferred_columns`. Columns you don't list still appear, in the order the block emits them.

The response carries the CSV as a string plus the row / column counts. Write it directly to a file or hand it to your CSV reader of choice.

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

  client = Retab()

  # Export every successful run's extract output
  export = client.workflows.runs.export(
      workflow_id="wf_abc123xyz",
      block_id="extract-1",
      export_source="outputs",
      status="completed",
      from_date="2026-04-01",
      to_date="2026-04-30",
      preferred_columns=["invoice_number", "total", "vendor.name"],
  )

  print(f"{export.rows} rows, {export.columns} columns")
  with open("invoices.csv", "w") as f:
      f.write(export.csv_data)

  # Export a hand-picked set of runs
  export = client.workflows.runs.export(
      workflow_id="wf_abc123xyz",
      block_id="extract-1",
      selected_run_ids=["run_abc123", "run_def456"],
  )
  ```

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

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

  const exportResult = await client.workflows.runs.export("wf_abc123xyz", "extract-1", "outputs", undefined, undefined, "completed", undefined, "2026-04-01", "2026-04-30", undefined, ["invoice_number", "total", "vendor.name"]);

  console.log(`${exportResult.rows} rows, ${exportResult.columns} columns`);
  writeFileSync("invoices.csv", exportResult.csvData);
  ```

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

  import (
  	"context"
  	"fmt"
  	"log"
  	"os"

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

  func ptr[T any](v T) *T { return &v }

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

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

  	exportResult, err := client.Workflows.Runs.Export(ctx, &retab.WorkflowRunsExportParams{
  		WorkflowID:       "wf_abc123xyz",
  		BlockID:          "extract-1",
  		ExportSource:     ptr(retab.WorkflowExportPayloadRequestExportSourceOutputs),
  		Status:           ptr(retab.WorkflowExportPayloadRequestExcludeStatusCompleted),
  		FromDate:         ptr("2026-04-01"),
  		ToDate:           ptr("2026-04-30"),
  		PreferredColumns: []string{"invoice_number", "total", "vendor.name"},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	fmt.Printf("%d rows, %d columns\n", exportResult.Rows, exportResult.Columns)
  	if err := os.WriteFile("invoices.csv", []byte(exportResult.CsvData), 0o644); err != nil {
  		log.Fatal(err)
  	}
  }
  ```

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

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

  export = client.workflows.runs.export(
    workflow_id: 'wf_abc123xyz',
    block_id: 'extract-1',
    export_source: 'outputs',
    status: 'completed',
    from_date: '2026-04-01',
    to_date: '2026-04-30',
    preferred_columns: ['invoice_number', 'total', 'vendor.name'],
  )

  puts "#{export.rows} rows, #{export.columns} columns"
  File.write('invoices.csv', export.csv_data)
  ```

  ```rust Rust theme={null}
  use retab::enums::{WorkflowExportPayloadRequestExportSource, WorkflowExportPayloadRequestStatus};
  use retab::models::WorkflowExportPayloadRequest;
  use retab::resources::workflow_runs::ExportParams;
  use retab::Retab;
  use std::fs::write;

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = Retab::new(std::env::var("RETAB_API_KEY")?);

      let mut body = WorkflowExportPayloadRequest::new("wf_abc123xyz", "extract-1");
      body.export_source = Some(WorkflowExportPayloadRequestExportSource::Outputs);
      body.status = Some(WorkflowExportPayloadRequestStatus::Completed);
      body.from_date = Some("2026-04-01".into());
      body.to_date = Some("2026-04-30".into());
      body.preferred_columns = Some(vec![
          "invoice_number".into(),
          "total".into(),
          "vendor.name".into(),
      ]);

      let export = client
          .workflows().runs()
          .export(ExportParams::new(body))
          .await?;

      println!("{} rows, {} columns", export.rows, export.columns);
      write("invoices.csv", export.csv_data)?;
      Ok(())
  }
  ```

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

  use Retab\Client;

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

  $result = $client->workflows()->runs()->export(
      workflowId: 'wf_abc123',
      blockId: 'blk_extract_1',
  );
  print_r($result);
  ```

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

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

  var result = await client.Workflows.Runs.ExportAsync(new WorkflowRunsExportOptions());
  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().export("wf_abc123", "block_abc123", null, null, null, null, null, null, null, null, null, null, null, null);
      System.out.println(result);
    }
  }
  ```

  ```curl cURL theme={null}
  curl -X 'POST' \
    'https://api.retab.com/v1/workflows/runs/export' \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer <your-api-key>' \
    -d '{
      "workflow_id": "wf_abc123xyz",
      "block_id": "extract-1",
      "export_source": "outputs",
      "status": "completed",
      "from_date": "2026-04-01",
      "to_date": "2026-04-30",
      "preferred_columns": ["invoice_number", "total", "vendor.name"]
    }'
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "csv_data": "run_id,invoice_number,total,vendor.name\nrun_abc123,INV-2026-001,1234.56,Acme Corp\nrun_def456,INV-2026-002,987.00,Globex\n",
    "rows": 2,
    "columns": 4
  }
  ```

  ```json 400 theme={null}
  {
    "detail": "Block extract-1 has no exportable outputs"
  }
  ```

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


## OpenAPI

````yaml POST /v1/workflows/runs/export
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://api.retab.com
security: []
paths:
  /v1/workflows/runs/export:
    post:
      tags:
        - Workflows
        - Workflow Runs
      summary: Get Workflow Export Payload
      description: Build CSV content for workflow run exports.
      operationId: get_workflow_export_payload
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WorkflowExportPayloadRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorkflowExportPayloadResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    WorkflowExportPayloadRequest:
      properties:
        workflow_id:
          type: string
          title: Workflow Id
          description: Workflow ID to export
        block_id:
          type: string
          title: Block Id
          description: Block ID to export
        export_source:
          type: string
          enum:
            - outputs
            - inputs
          title: Export Source
          description: Use block outputs or inputs
          default: outputs
        selected_run_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Selected Run Ids
          description: Run IDs filter (null means all runs)
        selected_doc_types:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Selected Doc Types
          description: Doc type filter (null/empty means all)
        status:
          anyOf:
            - type: string
              enum:
                - pending
                - queued
                - running
                - completed
                - error
                - failed
                - awaiting_review
                - cancelled
            - type: 'null'
          title: Status
          description: Optional status filter (intersects with completed-only export scope)
        exclude_status:
          anyOf:
            - type: string
              enum:
                - pending
                - queued
                - running
                - completed
                - error
                - failed
                - awaiting_review
                - cancelled
            - type: 'null'
          title: Exclude Status
          description: >-
            Optional status exclusion filter (intersects with completed-only
            export scope)
        from_date:
          anyOf:
            - type: string
            - type: 'null'
          title: From Date
          description: Optional start date filter (YYYY-MM-DD)
        to_date:
          anyOf:
            - type: string
            - type: 'null'
          title: To Date
          description: Optional end date filter (YYYY-MM-DD)
        trigger_type:
          anyOf:
            - type: string
              enum:
                - manual
                - api
                - schedule
                - webhook
                - email
                - restart
            - type: 'null'
          title: Trigger Type
          description: Optional trigger type filter
        preferred_columns:
          items:
            type: string
          type: array
          title: Preferred Columns
          description: Preferred data column order
          default: []
        delimiter:
          type: string
          title: Delimiter
          description: >-
            CSV field delimiter. Default is ';' (the Excel EU-locale default);
            pass ',' for RFC 4180 compatibility. Cell values are always quoted
            when they contain the delimiter, the line terminator, or the quote
            character, with embedded quotes doubled per RFC 4180.
          default: ;
        line_delimiter:
          type: string
          title: Line Delimiter
          description: CSV line delimiter
          default: |+

        quote:
          type: string
          title: Quote
          description: CSV quote character
          default: '"'
      type: object
      required:
        - block_id
        - workflow_id
      title: WorkflowExportPayloadRequest
      description: >-
        Body describing which block outputs (or inputs) across a workflow's runs
        to export as CSV, with optional run, doc-type, and status filters.
    WorkflowExportPayloadResponse:
      properties:
        csv_data:
          type: string
          title: Csv Data
          description: CSV content
        rows:
          type: integer
          title: Rows
          description: Data row count
        columns:
          type: integer
          title: Columns
          description: Column count including fixed columns
      type: object
      required:
        - columns
        - csv_data
        - rows
      title: WorkflowExportPayloadResponse
      description: The exported data as CSV, with its row and column counts.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
          default: []
      type: object
      title: HTTPValidationError
    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
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````