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

# Upload and Run

> Upload a document packet and start a run in a single call

*Rate limit tier: **submission** (60 req/min) — see [Rate limits](/api-reference-v3/introduction#rate-limits).*

Uploads 1–10 files as a single [document packet](/concepts/document-packets) and immediately enqueues a [run](/concepts/runs-and-results) on the workflow's latest version — the one-shot composition of [Upload](/api-reference-v3/workflows/upload) and [Run packet](/api-reference-v3/document-packets/run). This is the shortest path from bytes to structured data.

The `202` response returns the new `run_id`. Poll [`GET /v3/runs/{run_id}/`](/api-reference-v3/runs/get) until `status` is terminal — the results arrive inline on that same read. For production integrations, prefer [webhooks](/api-reference/webhooks/overview) over polling.

Send the files as multipart form data under the `files` field (repeat it for a multi-file packet); files above the per-file size cap are rejected at slot mint (before any bytes reach S3). Packet creation is all-or-nothing.

<Note>
  **Retries are safe with `Idempotency-Key`.** Retrying with the same key replays the original packet **and** run — no duplicate upload, no second extraction billed. See [Idempotency](/api-reference-v3/introduction#idempotency).
</Note>

An organization without extraction credit receives `402 PAYMENT_REQUIRED`.

<RequestExample>
  ```bash curl theme={null}
  curl -X POST 'https://api.anyformat.ai/v3/workflows/0686bb97-8c30-70f0-8000-97669e000eb8/upload/run/' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -H 'Idempotency-Key: 7c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f' \
    -F 'files=@/path/to/invoice.pdf'
  ```

  ```python Python (requests) theme={null}
  import requests
  import time

  workflow_id = "0686bb97-8c30-70f0-8000-97669e000eb8"
  base = "https://api.anyformat.ai"
  headers = {"Authorization": "Bearer YOUR_API_KEY"}

  with open("invoice.pdf", "rb") as f:
      triggered = requests.post(
          f"{base}/v3/workflows/{workflow_id}/upload/run/",
          headers={**headers, "Idempotency-Key": "7c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f"},
          files=[("files", f)],
      ).json()

  run_url = f"{base}/v3/runs/{triggered['run_id']}/"
  for _ in range(100):
      run = requests.get(run_url, headers=headers).json()
      if run["status"] == "processed":
          print(run["results"])
          break
      if run["status"] in ("error", "cancelled"):
          print(f"Terminal: {run['status']}")
          break
      time.sleep(3)
  ```

  ```typescript TypeScript theme={null}
  interface RunTriggered {
    run_id: string;
    document_packet_id: string;
    workflow_id: string;
    status: 'queued' | 'in_progress' | 'processed' | 'error' | 'cancelled';
  }

  const workflowId = '0686bb97-8c30-70f0-8000-97669e000eb8';
  const formData = new FormData();
  formData.append('files', fileInput.files[0]);

  const response = await fetch(
    `https://api.anyformat.ai/v3/workflows/${workflowId}/upload/run/`,
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Idempotency-Key': crypto.randomUUID(),
      },
      body: formData,
    }
  );

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  const triggered: RunTriggered = await response.json();
  console.log(triggered.run_id);
  ```
</RequestExample>

<ResponseExample>
  ```json Response (202 Accepted) theme={null}
  {
    "run_id": "069dcc2c-e14c-7606-8000-2ee4fb17b4f9",
    "document_packet_id": "069dcc2c-e14c-7606-8000-2ee4fb17b4e1",
    "workflow_id": "0686bb97-8c30-70f0-8000-97669e000eb8",
    "status": "queued"
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /v3/workflows/{workflow_id}/upload/run/
openapi: 3.1.0
info:
  title: anyformat API
  description: >
    Document extraction and workflow automation API.


    AnyFormat lets you define extraction workflows that pull structured data
    from any document — PDFs, images, scanned files, or plain text. Upload a
    file, run it through a workflow, and get back structured fields with
    confidence scores and source evidence.


    ## Quick start


    See the [Quick start
    guide](https://docs.anyformat.ai/api-reference/introduction) for a
    walkthrough.


    ## Authentication


    All endpoints (except `/health/`) require a Bearer token in the
    `Authorization` header:


    ```

    Authorization: Bearer <your-api-key>

    ```


    Get your API key from
    [app.anyformat.ai/api-key](https://app.anyformat.ai/api-key).


    ## Versioning


    Endpoints are versioned by path prefix (`/v2/`, `/v3/`). Every response
    under

    a versioned prefix includes `X-API-Version`.
  version: 2.0.0
servers:
  - url: https://api.anyformat.ai
    description: API server
security: []
tags:
  - name: workflows
    description: >-
      Workflows define extraction templates — what fields to extract from
      documents. Create workflows, upload files, run extractions, and fetch
      results.
  - name: files
    description: >-
      File collections group uploaded documents and track their extraction
      progress. Upload files, check status, and retrieve extraction results.
  - name: suggestions
    description: >-
      AI-powered schema and workflow suggestion endpoints for the AnyFormat
      webapp. Authenticated with a Cognito JWT rather than an API key.
  - name: document-packets
    description: >-
      Document packets group uploaded documents for a workflow (v3). Address a
      packet directly to (re-)run its workflow.
  - name: runs
    description: >-
      Extraction runs — the v3 first-class result entity. Each run is a single
      execution of a workflow against a document packet; fetch its status and
      results flat by run id.
  - name: health
    description: Health check endpoints to verify API availability.
paths:
  /v3/workflows/{workflow_id}/upload/run/:
    post:
      tags:
        - workflows
      summary: Upload and run workflow
      description: |-
        Upload one document packet and run it in a single call.

        Composes `POST /v3/workflows/{workflow_id}/upload/` and
        `POST /v3/document-packets/{document_packet_id}/run/`: the files are
        grouped into ONE packet (all-or-nothing) and an extraction is enqueued
        on the workflow's latest version. Poll `GET /v3/runs/{run_id}/` until
        `status` is terminal.
      operationId: v3_upload_and_run_workflow
      parameters:
        - name: workflow_id
          in: path
          required: true
          schema:
            type: string
            title: Workflow Id
        - name: Idempotency-Key
          in: header
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            description: >-
              Optional caller-supplied key (Stripe convention). Retrying the
              request with the same key replays the original packet AND run — no
              duplicate upload, no second extraction.
            title: Idempotency-Key
          description: >-
            Optional caller-supplied key (Stripe convention). Retrying the
            request with the same key replays the original packet AND run — no
            duplicate upload, no second extraction.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/Body_v3_upload_and_run_workflow'
      responses:
        '202':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RunTriggeredV3'
          headers:
            X-RateLimit-Limit:
              description: Requests allowed per window (60s).
              schema:
                type: integer
            X-RateLimit-Remaining:
              description: Requests remaining in the current window.
              schema:
                type: integer
            X-RateLimit-Reset:
              description: Seconds until the current window resets.
              schema:
                type: integer
        '401':
          description: Authentication failed — missing, invalid, or expired API key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                AUTH_FAILED:
                  value:
                    error: Authentication failed.
                    detail: Authentication failed.
                    error_code: AUTH_FAILED
                    retryable: false
                    request_id: req_abc123
        '404':
          description: >-
            Resource not found — the workflow, document packet, or run ID does
            not exist or is not visible to this API key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                NOT_FOUND:
                  value:
                    error: Resource not found.
                    detail: Resource not found.
                    error_code: NOT_FOUND
                    retryable: false
                    request_id: req_abc123
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
        '429':
          description: >-
            Rate limited — retry after the `Retry-After` header. Default
            windows: 60 requests/minute for extraction submission, 600
            requests/minute for general endpoints.
          headers:
            Retry-After:
              description: Seconds until the next request is allowed.
              schema:
                type: integer
            X-RateLimit-Limit:
              description: Requests allowed per window (60s).
              schema:
                type: integer
            X-RateLimit-Remaining:
              description: Requests remaining in the current window.
              schema:
                type: integer
            X-RateLimit-Reset:
              description: Seconds until the current window resets.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                RATE_LIMITED:
                  value:
                    error: Rate limit exceeded — retry after backoff.
                    detail: Rate limit exceeded — retry after backoff.
                    error_code: RATE_LIMITED
                    retryable: true
                    request_id: req_abc123
      security:
        - ApiKeyAuth: []
components:
  schemas:
    Body_v3_upload_and_run_workflow:
      properties:
        files:
          items:
            type: string
            contentMediaType: application/octet-stream
          type: array
          title: Files
          description: 1..10 files forming one document packet.
      type: object
      required:
        - files
      title: Body_v3_upload_and_run_workflow
    RunTriggeredV3:
      properties:
        run_id:
          type: string
          title: Run Id
          description: Unique identifier of the new run (hyphenated UUID).
          examples:
            - 069dcc2c-e14c-7606-8000-2ee4fb17b4f9
        document_packet_id:
          type: string
          title: Document Packet Id
          description: The document packet the run executes on (hyphenated UUID).
          examples:
            - 069dcc2c-e14c-7606-8000-2ee4fb17b4e1
        workflow_id:
          type: string
          title: Workflow Id
          description: The workflow being run (hyphenated UUID).
          examples:
            - 0686bb97-8c30-70f0-8000-97669e000eb8
        status:
          $ref: '#/components/schemas/RunStatus'
          description: Status at acceptance time — normally `queued`.
          examples:
            - queued
      type: object
      required:
        - run_id
        - document_packet_id
        - workflow_id
        - status
      title: RunTriggeredV3
      description: |-
        202 response for both run triggers (`upload/run/` and
        `document-packets/{id}/run/`).
    ErrorEnvelope:
      type: object
      title: ErrorEnvelope
      description: >-
        Uniform error response. `retryable=true` means the same request may
        succeed on retry (with backoff); `retryable=false` means the caller must
        change the request before retrying.
      required:
        - error
        - detail
        - error_code
        - retryable
        - request_id
      properties:
        error:
          type: string
          description: Short human-readable summary.
        detail:
          description: >-
            Machine-readable detail. String for most errors; list of field
            errors for validation failures.
          oneOf:
            - type: string
            - type: array
              items:
                type: object
        error_code:
          type: string
          description: Stable identifier for programmatic handling.
          examples:
            - VALIDATION_ERROR
            - AUTH_FAILED
            - NOT_FOUND
            - PRECONDITION_FAILED
            - RATE_LIMITED
            - INTERNAL_ERROR
            - GATEWAY_TIMEOUT
        retryable:
          type: boolean
          description: True when the caller should retry (with backoff for 429/412/5xx).
        request_id:
          type: string
          description: Correlates this response with server logs.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    RunStatus:
      type: string
      enum:
        - queued
        - in_progress
        - processed
        - error
        - cancelled
      title: RunStatus
      description: |-
        Execution lifecycle of a run. Non-terminal: ``queued``,
        ``in_progress``. Terminal: ``processed`` (success), ``error``,
        ``cancelled``.
    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
        ctx:
          type: object
          title: Context
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    ApiKeyAuth:
      type: http
      description: >-
        API key issued from app.anyformat.ai/api-key. Send as `Authorization:
        Bearer <key>`.
      scheme: bearer

````