Unstructured API

repository·main·Indexed 21 days ago

https://github.com/unstructured-io/unstructured-api

A self-hosted RESTful service for partitioning and extracting elements from various document types using the open-source unstructured library. It converts unstructured files into structured JSON or CSV data, supporting multiple PDF/image strategies (auto, fast, hi_res, ocr_only), table and image-block extraction, and by_title chunking.

Tokens
4.6K
Snippets
19
Records
24
Agent score
75%

What's inside unstructured-api

  1. Overview of Unstructured API

    main

    The Unstructured API is a self-hosted REST API designed to partition documents using the open-source unstructured library. It automatically detects uploaded file types, selects the appropriate partitioner, and returns document elements in JSON or CSV format.

    Key Capabilities:

    • Supports all file types compatible with unstructured[all-docs].
    • Provides multiple PDF/image strategies: auto, fast, hi_res, and ocr_only.
    • Supports table and image-block extraction, OCR language selection, page breaks, and coordinates.
    • Offers by_title chunking with overlap controls.
    • Handles single-file and multi-file requests.
    • Provides API documentation at http://localhost:8000/general/docs and an OpenAPI schema at http://localhost:8000/general/openapi.json once the server is running.
  2. Available sample documents for testing

    main

    The sample-docs directory provides several file types to test the library's parsers:

    • example-10k.html: A 10-K SEC filing in HTML format (suitable for testing the HTML parser).
    • layout-parser-paper.pdf: A PDF document (suitable for testing PDF parsing and layout analysis).
    • factbook.xml and factbook.xsl: Example XML and XSL files (suitable for testing stylesheet processing).
  3. Local Quickstart for Unstructured API

    main

    To run the Unstructured API locally, ensure you have the following requirements:

    • Python 3.12
    • uv
    • System dependencies required by the specific document types you intend to process (refer to the unstructured full installation guide).

    Setup Steps:

    1. Install the locked runtime and dependencies:
      make install
    2. Start the development server:
      make run-web-app
    3. Verify the server is healthy:
      curl --fail http://localhost:8000/healthcheck

    Basic Usage Example: Partition a sample file using a POST request:

    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: application/json' \
      --form 'files=@sample-docs/family-day.eml'
    make install
    make run-web-app
    curl --fail http://localhost:8000/healthcheck
    
    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: application/json' \
      --form 'files=@sample-docs/family-day.eml'
  4. Configure Partitioning Strategies and OCR

    main

    When calling the /general/v0/general endpoint, you can customize the partitioning behavior using form parameters.

    Layout-aware Partitioning: Use strategy=hi_res for high-resolution, layout-aware partitioning (useful for complex PDFs).

    OCR Language Selection: Use the languages parameter to specify OCR languages (e.g., eng, kor). Note that ocr_languages is deprecated.

    Examples:

    High-res strategy:

    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: application/json' \
      --form 'files=@sample-docs/layout-parser-paper.pdf' \
      --form 'strategy=hi_res'

    OCR with specific languages:

    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: application/json' \
      --form 'files=@sample-docs/english-and-korean.png' \
      --form 'strategy=ocr_only' \
      --form 'languages=eng' \
      --form 'languages=kor'
    # High-res strategy
    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: application/json' \
      --form 'files=@sample-docs/layout-parser-paper.pdf' \
      --form 'strategy=hi_res'
    
    # OCR with languages
    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: application/json' \
      --form 'files=@sample-docs/english-and-korean.png' \
      --form 'strategy=ocr_only' \
      --form 'languages=eng' \
      --form 'languages=kor'
  5. Download an XBRL 10-K SEC filing

    main

    You can download an example 10-K in inline XBRL format using curl.

    Important: The SEC website requires a User-Agent header containing your organization and email address, otherwise the request will be rejected. Replace ${organization} and ${email} with your actual details.

    curl -O \
      -A '${organization} ${email}' \
      https://www.sec.gov/Archives/edgar/data/311094/000117184321001344/0001171843-21-001344.txt
  6. Download sample XBRL 10-K documents

    main

    To test the HTML parser with a real-world SEC filing, you can download an example 10-K in inline XBRL format using curl.

    Important: The SEC website requires a User-Agent header containing your organization and email address; otherwise, the request will be rejected. Replace ${organization} and ${email} with your actual details.

    curl -O \
      -A '${organization} ${email}' \
      https://www.sec.gov/Archives/edgar/data/311094/000117184321001344/0001171843-21-001344.txt
  7. Chunking and Output Formats

    main

    You can control how the document is chunked and the format of the response.

    Chunking by Title: Use chunking_strategy=by_title to group elements. You can control the size with max_characters. To reduce response size, set include_orig_elements=false to exclude original element metadata from the chunks.

    Output Formats: By default, the API returns JSON. To receive CSV, set the accept header to text/csv and the output_format form parameter to text/csv.

    Examples:

    Chunking configuration:

    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: application/json' \
      --form 'files=@sample-docs/layout-parser-paper-fast.pdf' \
      --form 'chunking_strategy=by_title' \
      --form 'max_characters=1500' \
      --form 'include_orig_elements=false'

    CSV output:

    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: text/csv' \
      --form 'files=@sample-docs/family-day.eml' \
      --form 'output_format=text/csv'
    # Chunking by title
    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: application/json' \
      --form 'files=@sample-docs/layout-parser-paper-fast.pdf' \
      --form 'chunking_strategy=by_title' \
      --form 'max_characters=1500' \
      --form 'include_orig_elements=false'
    
    # CSV output
    curl --request POST \
      --url http://localhost:8000/general/v0/general \
      --header 'accept: text/csv' \
      --form 'files=@sample-docs/family-day.eml' \
      --form 'output_format=text/csv'
  8. Run Unstructured API with Docker

    main

    You can run the API using pre-built multi-platform images (amd64 and arm64) from Quay.

    Run published image:

    docker pull quay.io/unstructured-io/unstructured-api:latest
    docker run --rm --name unstructured-api -p 8000:8000 \
      quay.io/unstructured-io/unstructured-api:latest

    Note: Pin a specific release or commit tag instead of latest for reproducible deployments.

    Build locally:

    make docker-build
    make docker-start-api
    # Run published image
    docker pull quay.io/unstructured-io/unstructured-api:latest
    docker run --rm --name unstructured-api -p 8000:8000 \
      quay.io/unstructured-io/unstructured-api:latest
    
    # Build locally
    make docker-build
    make docker-start-api
  9. Configure Unstructured API Server Environment Variables

    main

    The following environment variables can be used to configure the server behavior:

    VariableDefaultDescription
    PORT8000Port used by the container entrypoint.
    HOST0.0.0.0Interface used by the container entrypoint.
    WORKERS1Number of Uvicorn workers.
    UNSTRUCTURED_API_KEYunsetWhen set, requests must supply the same value in the unstructured-api-key header.
    UNSTRUCTURED_MEMORY_FREE_MINIMUM_MB2048Reject new work with HTTP 503 below this amount of free memory. Set to 0 to disable the check.
    ALLOWED_ORIGINSunsetComma-separated origins allowed by the optional CORS middleware.
    MAX_LIFETIME_SECONDSunsetBegin graceful shutdown after this many seconds (requires GNU timeout).

    Parallel PDF Mode (Experimental): Used to speed up hi_res workloads by splitting PDFs into page ranges and processing them via another Partition Endpoint.

    VariableDefaultDescription
    UNSTRUCTURED_PARALLEL_MODE_ENABLEDfalseSet to true to enable remote page processing.
    UNSTRUCTURED_PARALLEL_MODE_URLunsetPartition Endpoint URL that receives page ranges. Required when parallel mode is enabled.
    UNSTRUCTURED_PARALLEL_MODE_THREADS3Maximum concurrent remote requests.
    UNSTRUCTURED_PARALLEL_MODE_SPLIT_SIZE1Pages per remote request.
    UNSTRUCTURED_PARALLEL_RETRY_ATTEMPTS2Retries after the initial request for retryable errors.
  10. Handle FormData with bracketed keys (key[])

    main

    The API includes a patch for FastAPI's Request.form() to support clients (like Speakeasy) that send array-like form data using bracketed keys (e.g., key[]).

    The API automatically transforms these keys by removing the trailing [] before processing the data, allowing standard FastAPI parameter parsing to work with these explicit form structures.

  11. Initialize the Unstructured Pipeline API

    main

    The Unstructured Pipeline API is a FastAPI application designed to partition documents using the Unstructured library. It provides endpoints for document processing and includes built-in support for CORS and custom OpenAPI documentation.

    Server Configuration

    The API defines two primary server environments:

    • Hosted API: https://api.unstructured.io (ID: prod)
    • Development server: http://localhost:8000 (ID: local)

    API Documentation

    • Swagger UI: Accessible at /general/docs
    • OpenAPI JSON: Accessible at /general/openapi.json
    from fastapi import FastAPI
    
    app = FastAPI(
        title="Unstructured Pipeline API",
        summary="Partition documents with the Unstructured library",
        # ... other config
    )