> ## 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 File from URL

> Create a file collection by pointing anyformat at an HTTPS URL

<Note>
  Use this endpoint when the source document already lives at an HTTPS URL — for example, a presigned S3 link or a hosted asset. anyformat fetches the bytes server-side; you do not stream the file yourself. To upload bytes directly, use [Upload File](/api-reference/files/create) instead.
</Note>

## When to use this

* The document is in a bucket you can presign (S3, GCS, R2, etc.) and you'd rather hand anyformat the link than route the bytes through your own backend.
* The document lives at a public HTTPS URL.
* You want one round-trip instead of a multipart upload.

## Constraints

|                   |                                                                                                                                                                                                                                                 |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Scheme**        | `https://` only — `http://` is rejected at the gateway with `400`.                                                                                                                                                                              |
| **Fetch timeout** | 10 seconds per network phase (connect, read, write, pool).                                                                                                                                                                                      |
| **Size cap**      | 20 MB (mirrors the multipart upload cap).                                                                                                                                                                                                       |
| **Redirects**     | Not followed. A `3xx` from the supplied URL is treated as a guard rejection and surfaces as a `400` — your URL must serve the bytes directly (no CDN redirects, no URL shorteners).                                                             |
| **SSRF guard**    | URLs whose hostname resolves to a non-globally-routable IP (per IANA `is_global`: loopback, RFC1918, link-local incl. cloud-metadata `169.254.169.254`, IPv6 ULA, multicast, reserved, IPv4-mapped IPv6) are rejected before any fetch attempt. |

## What happens after the 201

The URL endpoint returns immediately with `"status": "pending"` and fetches the bytes asynchronously, server-side. **The `status` field on the file listing reflects extraction state, not upload state** — a subsequent `GET /v2/workflows/{workflow_id}/files/` will continue to report `pending` until a workflow run is triggered against the returned `collection_id`, even after the asynchronous fetch has finished and the bytes are in storage. Polling the file listing for an "upload-complete" transition will not work.

The intended next step is to start a run on the returned `collection_id` straight away (see [Run Workflow](/api-reference/workflows/run)). The file's `status` then moves through `queued`, `in_progress`, and `processed` as the extraction progresses, and the standard polling pattern on `GET .../files/` reports those transitions.

## Request body

| Field          | Type   | Required | Description                                                                                   |
| -------------- | ------ | -------- | --------------------------------------------------------------------------------------------- |
| `url`          | string | Yes      | HTTPS URL anyformat will fetch the file bytes from.                                           |
| `filename`     | string | Yes      | Filename to record on the uploaded file.                                                      |
| `content_type` | string | No       | MIME type of the file. Leave empty (or omit) to use the URL's response `Content-Type` header. |

<RequestExample>
  ```bash curl theme={null}
  curl -X POST 'https://api.anyformat.ai/v2/workflows/550e8400-e29b-41d4-a716-446655440000/files/from-url/' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -H 'Content-Type: application/json' \
    -d '{
      "url": "https://my-bucket.s3.amazonaws.com/invoices/april.pdf?X-Amz-Signature=...",
      "filename": "april.pdf",
      "content_type": "application/pdf"
    }'
  ```

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

  workflow_id = "550e8400-e29b-41d4-a716-446655440000"
  url = f"https://api.anyformat.ai/v2/workflows/{workflow_id}/files/from-url/"
  headers = {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json",
  }

  response = requests.post(url, headers=headers, json={
      "url": "https://my-bucket.s3.amazonaws.com/invoices/april.pdf?X-Amz-Signature=...",
      "filename": "april.pdf",
      "content_type": "application/pdf",
  })
  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const workflowId = '550e8400-e29b-41d4-a716-446655440000';

  const response = await fetch(`https://api.anyformat.ai/v2/workflows/${workflowId}/files/from-url/`, {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      url: 'https://my-bucket.s3.amazonaws.com/invoices/april.pdf?X-Amz-Signature=...',
      filename: 'april.pdf',
      content_type: 'application/pdf',
    }),
  });

  const data = await response.json();
  console.log(data);
  ```

  ```typescript TypeScript theme={null}
  interface FileItem {
    filename: string;
    status: string;
  }

  interface CreateCollectionResponse {
    id: string;
    name: string | null;
    files: FileItem[];
    workflow_id: string;
  }

  const workflowId = '550e8400-e29b-41d4-a716-446655440000';

  const response = await fetch(`https://api.anyformat.ai/v2/workflows/${workflowId}/files/from-url/`, {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      url: 'https://my-bucket.s3.amazonaws.com/invoices/april.pdf?X-Amz-Signature=...',
      filename: 'april.pdf',
      content_type: 'application/pdf',
    }),
  });

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

  const data: CreateCollectionResponse = await response.json();
  console.log(data.id);
  ```
</RequestExample>

<ResponseExample>
  ```json Response (201 Created) theme={null}
  {
    "id": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
    "name": null,
    "files": [
      {
        "filename": "april.pdf",
        "status": "pending"
      }
    ],
    "workflow_id": "550e8400-e29b-41d4-a716-446655440000"
  }
  ```
</ResponseExample>

## Error responses

| Status | When                                                                                                                                                                                                                                       |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `400`  | URL uses a disallowed scheme (`http://`, `file://`, …), resolves to a non-public IP, returns a `3xx` redirect, or returns a body larger than the 20 MB cap — anything the SSRF guard or fetcher treats as structurally unacceptable input. |
| `422`  | The upstream URL prevented processing — connection timed out, hostname did not resolve, or the target returned a `4xx`/`5xx` response.                                                                                                     |


## OpenAPI

````yaml POST /v2/workflows/{workflow_id}/files/from-url/
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:
  /v2/workflows/{workflow_id}/files/from-url/:
    post:
      tags:
        - files
      summary: Create file collection from URL
      description: |-
        Create a file collection by pointing the backend at a URL.

        Use this when the source document already lives at an HTTPS URL (for
        example, a presigned S3 link or a hosted asset). The backend fetches
        the bytes server-side — the caller does not stream them.

        The fetch is bounded by a 10-second timeout and a byte cap that
        mirrors Django's ``DATA_UPLOAD_MAX_MEMORY_SIZE`` (20 MB by default).

        Error statuses:
        - ``400`` for caller-input errors the backend won't accept: oversize
          response (``RemoteFileFetchTooLarge``) and SSRF-blocked URL
          (``RemoteFileUrlBlocked``). Mirrors the ``content_base64`` path's
          ``RequestDataTooBig`` → 400 mapping for uniform wire shape.
        - ``422`` when the upstream URL prevented processing: timeout,
          DNS failure, or non-2xx response from the target.
      operationId: v2_create_workflow_file_from_url
      parameters:
        - name: workflow_id
          in: path
          required: true
          schema:
            type: string
            title: Workflow Id
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateFileCollectionFromUrlRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateCollectionResponse'
          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, file, or collection 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:
    CreateFileCollectionFromUrlRequest:
      properties:
        url:
          type: string
          title: Url
          description: HTTPS URL the backend will fetch the file bytes from.
          examples:
            - https://example.com/invoices/april.pdf
        filename:
          type: string
          title: Filename
          description: Filename to record on the uploaded file.
          examples:
            - april.pdf
        content_type:
          type: string
          title: Content Type
          description: >-
            MIME type of the file. Leave empty to use the URL's response
            Content-Type header.
          default: ''
          examples:
            - application/pdf
      type: object
      required:
        - url
        - filename
      title: CreateFileCollectionFromUrlRequest
      description: |-
        Payload for creating a file collection from a single remote URL.

        Single URL per request keeps the wire shape predictable; SDKs that need
        batches wrap the call. ``content_type`` may be empty — the backend
        falls back to the response's ``Content-Type`` header in that case.

        Only HTTPS URLs are accepted. The backend additionally runs a DNS+IP
        SSRF guard before the fetch — URLs whose hostname resolves to a
        non-globally-routable IP (per IANA ``is_global``: loopback, RFC1918,
        link-local incl. cloud-metadata 169.254.169.254, IPv6 ULA, multicast,
        reserved, IPv4-mapped IPv6) are refused. Enforcing the scheme at the
        gateway means malformed requests fail fast without traversing the
        backend.
    CreateCollectionResponse:
      properties:
        id:
          type: string
          title: Id
          description: Unique identifier of the newly created file collection.
          examples:
            - 069dcc2c-e14c-7606-8000-2ee4fb17b4e1
        name:
          anyOf:
            - type: string
            - type: 'null'
          title: Name
          description: Human-readable name for the collection.
        files:
          items:
            $ref: '#/components/schemas/FileItem'
          type: array
          title: Files
          description: List of files included in the collection, with their upload status.
        workflow_id:
          type: string
          title: Workflow Id
          description: The UUID of the workflow this collection belongs to.
          examples:
            - 0686bb97-8c30-70f0-8000-97669e000eb8
        rejected:
          items:
            $ref: '#/components/schemas/RejectedFileItem'
          type: array
          title: Rejected
          description: >-
            Files the backend refused to accept — unsupported extension at
            slot-time or disguised bytes at register-time. Empty when every file
            uploaded cleanly.
      type: object
      required:
        - id
        - files
        - workflow_id
      title: CreateCollectionResponse
      description: >-
        Response from creating a file collection. Contains the collection ID and
        the status of each uploaded file.
    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
    FileItem:
      properties:
        filename:
          type: string
          title: Filename
          description: Name of the uploaded file.
          examples:
            - invoice.pdf
        status:
          type: string
          title: Status
          description: >-
            Initial status of the file at the moment the response is returned.
            Multipart upload (`POST .../files/`) returns `uploaded` or `failed`
            synchronously. URL ingestion (`POST .../files/from-url/`) returns
            `pending` while the server fetches the bytes asynchronously. The
            file listing's `status` field reflects extraction state, not upload
            state — trigger a workflow run on the returned collection to drive
            the file through the `queued` / `in_progress` / `processed`
            lifecycle.
          examples:
            - uploaded
      type: object
      required:
        - filename
        - status
      title: FileItem
      description: A single file within a collection, showing its name and upload status.
    RejectedFileItem:
      properties:
        filename:
          type: string
          title: Filename
          description: Name of the rejected file.
          examples:
            - trojan.pdf
        reason:
          type: string
          title: Reason
          description: Human-readable reason from the backend upload validator.
          examples:
            - >-
              File contents are not a supported file type (detected:
              application/x-msdownload).
      type: object
      required:
        - filename
        - reason
      title: RejectedFileItem
      description: |-
        A file the backend rejected either upfront (unsupported filename) or
        after inspecting its bytes (disguised content). No ``FileCollection``
        was created for these; the raw bytes (if any reached S3) age out via
        the ``upload-status=pending`` lifecycle rule within 24 h.
    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

````