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

# Extract Data

> Extract structured data from documents using AI

## Endpoint

```
POST /extract/{document_id}
```

Extract structured information from an uploaded document using a defined schema. Choose between Basic, VLM, or Advanced extraction modes based on your accuracy and speed requirements.

## Authentication

<ParamField header="X-API-Key" type="string" required>
  API key for authentication. Your unique API key.
</ParamField>

## Path Parameters

<ParamField path="document_id" type="string" required>
  UUID of the uploaded document. Obtained from the `/upload` endpoint.
</ParamField>

## Request Body

<ParamField body="schema" type="object">
  JSON Schema defining the structure of data to extract. Uses `named_entities` format. Optional, but strongly recommended for structured output.

  ```json theme={null}
  {
    "named_entities": {
      "field_name": {
        "type": "string|number|boolean|array|object",
        "description": "Field description for AI context"
      }
    },
    "required": ["field1", "field2"]
  }
  ```
</ParamField>

<ParamField body="prompt" type="string">
  Additional instructions for extraction. Optional but recommended for complex documents.

  Default: `"No additional instructions provided."`
</ParamField>

<ParamField body="model" type="string">
  For **Basic Extraction** only. Specify the AI model to use:

  * `google-gemini-3-flash` (6 credits/page) - Most accurate
  * `google-gemini-2.5-flash` (4 credits/page) - Balanced
  * `qwen-3-vl` (2 credits/page) - Fastest

  If provided, uses Basic extraction mode (single model, no confidence scores).
</ParamField>

<ParamField body="extraction_mode" type="string">
  For **VLM Extraction** only. Set to:

  * `vlm` (10 credits/page) - Vision-based extraction for scanned docs

  For **Advanced extraction** (15 credits/page): Don't set this parameter AND don't set `model`.\
  For **Basic extraction**: Set `model` parameter instead.
</ParamField>

<ParamField body="review_threshold" type="number" default="80">
  Confidence threshold (0-100) for automatic review flagging. Only applies to Advanced/VLM modes.

  Fields with confidence below this threshold are flagged for review if they're marked as `required` in the schema.
</ParamField>

<ParamField body="include_citations" type="boolean" default="false">
  Enable citation/source matching for extracted fields. Only available in Advanced mode; don't set `model` or `extraction_mode` when this is `true`.
</ParamField>

<ParamField body="agentic_ocr" type="boolean" default="false">
  Use the higher OCR tier for Advanced mode parsing. This is ignored by Basic and VLM extraction.
</ParamField>

<ParamField body="confidence_instruction" type="string">
  Additional instructions for confidence scoring in Advanced mode.
</ParamField>

## Response

<ResponseField name="document_id" type="string">
  UUID of the processed document.
</ResponseField>

<ResponseField name="results" type="object">
  Extracted data matching your schema structure. Fields are ordered according to schema definition.
</ResponseField>

<ResponseField name="needs_review" type="boolean">
  Whether this extraction requires human review. `true` if any required fields have confidence below the review threshold.
</ResponseField>

<ResponseField name="needs_review_metadata" type="object">
  Metadata about fields needing review. Only present in Advanced/VLM modes.

  <Expandable title="Metadata Structure">
    <ResponseField name="confidence_scores" type="object">
      Confidence scores (0-100) for each extracted field. Calculated as:\
      `0.4 * lexical_similarity + 0.6 * semantic_similarity`
    </ResponseField>

    <ResponseField name="review_flags" type="object">
      Boolean flags indicating which fields need review.
    </ResponseField>
  </Expandable>
</ResponseField>

## Examples

### Basic Extraction

Fast, single-model extraction for simple documents:

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.documind.cloud/api/v1/extract/550e8400-e29b-41d4-a716-446655440000 \
    -H 'X-API-Key: YOUR_API_KEY' \
    -H 'Content-Type: application/json' \
    -d '{
      "schema": {
        "named_entities": {
          "invoice_number": {
            "type": "string",
            "description": "The invoice number"
          },
          "total_amount": {
            "type": "number",
            "description": "Total invoice amount"
          }
        },
        "required": ["invoice_number"]
      },
      "prompt": "Extract invoice details",
      "model": "google-gemini-2.5-flash"
    }'
  ```

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

  extract_request = {
      "schema": {
          "named_entities": {
              "invoice_number": {
                  "type": "string",
                  "description": "The invoice number"
              },
              "total_amount": {
                  "type": "number",
                  "description": "Total invoice amount"
              },
              "vendor_name": {
                  "type": "string",
                  "description": "Name of the vendor"
              }
          },
          "required": ["invoice_number", "total_amount"]
      },
      "prompt": "Extract all invoice information accurately",
      "model": "google-gemini-2.5-flash"  # 4 credits per page
  }

  response = requests.post(
      f"https://api.documind.cloud/api/v1/extract/{document_id}",
      headers={
          "X-API-Key": API_KEY,
          "Content-Type": "application/json"
      },
      json=extract_request
  )

  result = response.json()
  ```

  ```javascript Node.js theme={null}
  const extractionConfig = {
    schema: {
      named_entities: {
        invoice_number: {
          type: "string",
          description: "The invoice number"
        },
        total_amount: {
          type: "number",
          description: "Total invoice amount"
        }
      },
      required: ["invoice_number"]
    },
    prompt: "Extract invoice details",
    model: "google-gemini-2.5-flash"
  };

  const response = await fetch(
    `https://api.documind.cloud/api/v1/extract/${documentId}`,
    {
      method: 'POST',
      headers: {
        'X-API-Key': process.env.API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(extractionConfig)
    }
  );

  const result = await response.json();
  ```
</RequestExample>

<ResponseExample>
  ```json Basic Extraction Response theme={null}
  {
    "document_id": "550e8400-e29b-41d4-a716-446655440000",
    "results": {
      "invoice_number": "INV-2024-001",
      "total_amount": 1250.00,
      "vendor_name": "Acme Corporation"
    },
    "needs_review": false,
    "needs_review_metadata": {}
  }
  ```
</ResponseExample>

### Advanced Extraction

Multi-model validation with confidence scores:

<RequestExample>
  ```python Python theme={null}
  advanced_extract = {
      "schema": {
          "named_entities": {
              "invoice_number": {
                  "type": "string",
                  "description": "The invoice number"
              },
              "line_items": {
                  "type": "array",
                  "description": "Invoice line items",
                  "items": {
                      "type": "object",
                      "named_entities": {
                          "description": {
                              "type": "string",
                              "description": "Item description"
                          },
                          "amount": {
                              "type": "number",
                              "description": "Line total"
                          }
                      }
                  }
              }
          },
          "required": ["invoice_number", "line_items"]
      },
      "prompt": "Extract all invoice details with high accuracy",
      # Advanced mode: don't set 'model' or 'extraction_mode' - 15 credits per page
      "review_threshold": 85,
      "include_citations": true,
      "confidence_instruction": "Use stricter confidence for totals and payment terms."
  }

  response = requests.post(
      f"https://api.documind.cloud/api/v1/extract/{document_id}",
      headers={
          "X-API-Key": API_KEY,
          "Content-Type": "application/json"
      },
      json=advanced_extract
  )

  result = response.json()

  # Check if review is needed
  if result["needs_review"]:
      print("Some fields need review:")
      for field, needs_review in result["needs_review_metadata"]["review_flags"].items():
          if needs_review:
              confidence = result["needs_review_metadata"]["confidence_scores"][field]
              print(f"  - {field}: {confidence:.1f}% confidence")
  ```
</RequestExample>

<ResponseExample>
  ```json Advanced Extraction Response theme={null}
  {
    "document_id": "550e8400-e29b-41d4-a716-446655440000",
    "results": {
      "invoice_number": "INV-2024-001",
      "line_items": [
        {
          "description": "Professional Services",
          "amount": 1000.00
        },
        {
          "description": "Software License",
          "amount": 250.00
        }
      ]
    },
    "needs_review": true,
    "needs_review_metadata": {
      "confidence_scores": {
        "invoice_number": 95.2,
        "line_items": {
          "0": {
            "description": 88.5,
            "amount": 92.1
          },
          "1": {
            "description": 72.3,
            "amount": 95.8
          }
        }
      },
      "review_flags": {
        "invoice_number": false,
        "line_items": {
          "0": {
            "description": false,
            "amount": false
          },
          "1": {
            "description": true,
            "amount": false
          }
        }
      }
    }
  }
  ```
</ResponseExample>

## Extraction Mode Comparison

| Feature               | Basic             | VLM                         | Advanced                            |
| --------------------- | ----------------- | --------------------------- | ----------------------------------- |
| **Credits/Page**      | 2-6               | 10                          | 15                                  |
| **Speed**             | Fastest           | Fast                        | Moderate                            |
| **Accuracy**          | Good              | Very Good                   | Highest                             |
| **Confidence Scores** | No                | Yes                         | Yes                                 |
| **Review Flagging**   | No                | Yes                         | Yes                                 |
| **Citation Matching** | No                | No                          | Optional                            |
| **Agentic OCR**       | No                | No                          | Optional                            |
| **Best For**          | Simple docs       | Scanned images              | Critical data                       |
| **How to use**        | Set `model` param | Set `extraction_mode="vlm"` | Don't set model or extraction\_mode |

## Schema Guidelines

### Field Types

<AccordionGroup>
  <Accordion title="String Fields">
    ```json theme={null}
    "customer_name": {
      "type": "string",
      "description": "Full name of the customer"
    }
    ```

    Use for text data: names, addresses, identifiers.
  </Accordion>

  <Accordion title="Number Fields">
    ```json theme={null}
    "total_amount": {
      "type": "number",
      "description": "Total invoice amount in USD"
    }
    ```

    For numeric values: amounts, quantities, percentages.
  </Accordion>

  <Accordion title="Array Fields">
    ```json theme={null}
    "line_items": {
      "type": "array",
      "description": "List of invoice line items",
      "items": {
        "type": "object",
        "named_entities": {
          "description": {"type": "string"},
          "quantity": {"type": "number"}
        }
      }
    }
    ```

    For repeating data: tables, lists, multiple entries.
  </Accordion>

  <Accordion title="Nested Objects">
    ```json theme={null}
    "billing_address": {
      "type": "object",
      "description": "Customer billing address",
      "named_entities": {
        "street": {"type": "string"},
        "city": {"type": "string"},
        "zip": {"type": "string"}
      }
    }
    ```

    For structured data groups.
  </Accordion>
</AccordionGroup>

### Best Practices

1. **Descriptive Field Names**: Use clear, meaningful names (`invoice_date` not `date1`)
2. **Detailed Descriptions**: Help the AI understand context and format
3. **Mark Critical Fields**: Add to `required` array for automatic review
4. **Consistent Naming**: Use snake\_case throughout your schema

## Error Responses

### 402 Payment Required

```json theme={null}
{
  "detail": "Insufficient credits. Please upgrade your plan or wait for your daily credits to refresh."
}
```

Check your credit balance before processing large batches.

### 403 Forbidden

```json theme={null}
{
  "detail": "You don't have access to this document"
}
```

Document belongs to another user or organization.

### 500 Internal Server Error

```json theme={null}
{
  "detail": "Failed to extract information. Please contact support."
}
```

Extraction processing failed. Retry or contact support if it persists.

## Next Steps

<CardGroup cols={2}>
  <Card title="Review Workflow" icon="flag" href="/api/review/understanding-reviews">
    Handle documents that need review
  </Card>

  <Card title="Polling Pattern" icon="rotate" href="/api/review/polling-pattern">
    Implement review polling for automation
  </Card>

  <Card title="List Extractions" icon="list" href="/api/data/list-extractions">
    Query extraction results
  </Card>
</CardGroup>
