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

# Create Extraction

> Run a structured extraction on a document.

Extracts structured data from the `document` according to the supplied
`json_schema`, using the requested `model`. Returns the extraction
with its `output`, consensus details, and usage on `201`. When
`stream` is `true`, partial results are streamed back as they are produced.

Extract structured data from a document against a JSON schema and persist the result as an `Extraction` resource that can later be retrieved via `GET /v1/extractions/{extraction_id}` or listed via `GET /v1/extractions`.

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

  client = Retab()

  document = MIMEData(
      filename="Invoice.pdf",
      url="https://my-bucket.s3.us-east-1.amazonaws.com/documents/Invoice.pdf",
  )
  schema = {
      "type": "object",
      "properties": {
          "invoice_number": {"type": "string"},
          "total": {"type": "number"},
      },
      "required": ["invoice_number", "total"],
  }

  extraction = client.extractions.create(
      document=document,
      json_schema=schema,
      model="retab-small",
      n_consensus=1,
      metadata={"source": "docs"},
  )

  print(f"Extraction ID: {extraction.id}")
  print(f"Filename: {extraction.file.filename}")
  print(extraction.output)
  ```

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

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

  const document = {
    filename: "Invoice.pdf",
    url: "https://my-bucket.s3.us-east-1.amazonaws.com/documents/Invoice.pdf",
  };

  const extraction = await client.extractions.create(
    document,
    { type: "object", properties: {} },
    "retab-small",
    undefined,
    1,
    { source: "docs" }
  );

  console.log(`Extraction ID: ${extraction.id}`);
  console.log(extraction.output);
  ```

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

  import (
  	"context"
  	"fmt"
  	"log"

  	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)
  	}

  	document := retab.MIMEData{
  		Filename: "Invoice.pdf",
  		URL:      "https://my-bucket.s3.us-east-1.amazonaws.com/documents/Invoice.pdf",
  	}

  	extraction, err := client.Extractions.Create(ctx, &retab.ExtractionsCreateParams{
  		Document: document,
  		JSONSchema: map[string]any{
  			"type": "object",
  			"properties": map[string]any{
  				"invoice_number": map[string]any{"type": "string"},
  				"total":          map[string]any{"type": "number"},
  			},
  			"required": []string{"invoice_number", "total"},
  		},
  		Model:      ptr("retab-small"),
  		NConsensus: ptr(1),
  		Metadata:   &map[string]string{"source": "docs"},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	fmt.Printf("Extraction ID: %s\n", extraction.ID)
  	fmt.Println(extraction.Output)
  }
  ```

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

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

  document = {
    filename: 'Invoice.pdf',
    url: 'https://my-bucket.s3.us-east-1.amazonaws.com/documents/Invoice.pdf',
  }

  schema = {
    type: 'object',
    properties: {
      invoice_number: { type: 'string' },
      total: { type: 'number' },
    },
    required: ['invoice_number', 'total'],
  }

  extraction = client.extractions.create(
    document: document,
    json_schema: schema,
    model: 'retab-small',
    n_consensus: 1,
    metadata: { 'source' => 'docs' },
  )

  puts "Extraction ID: #{extraction.id}"
  puts "Filename: #{extraction.file.filename}"
  puts extraction.output
  ```

  ```rust Rust theme={null}
  use retab::resources::extractions::CreateParams;
  use retab::{MimeData, Retab};
  use serde_json::json;

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

      let schema = json!({
          "type": "object",
          "properties": {
              "invoice_number": {"type": "string"},
              "total": {"type": "number"},
          },
          "required": ["invoice_number", "total"],
      });
      let schema_map = schema.as_object().unwrap().clone().into_iter().collect();
      let document = MimeData::new(
          "Invoice.pdf",
          "https://my-bucket.s3.us-east-1.amazonaws.com/documents/Invoice.pdf",
      );

      let mut params = CreateParams::new(document, schema_map);
      params.body.model = Some("retab-small".into());
      params.body.n_consensus = Some(1);
      params.body.metadata = Some([("source".to_string(), "docs".to_string())].into_iter().collect());

      let extraction = client.extractions().create(params).await?;

      println!("Extraction ID: {}", extraction.id);
      println!("Filename: {}", extraction.file.filename);
      println!("{:?}", extraction.output);
      Ok(())
  }
  ```

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

  use Retab\Client;

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

  $result = $client->extractions()->create(
      document: [
          'filename' => 'Invoice.pdf',
          'url' => 'https://my-bucket.s3.us-east-1.amazonaws.com/documents/Invoice.pdf',
      ],
      jsonSchema: ['type' => 'object', 'properties' => []],
  );
  print_r($result);
  ```

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

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

  var document = MimeData.FromUrl(
      new Uri("https://my-bucket.s3.us-east-1.amazonaws.com/documents/Invoice.pdf"));

  var result = await client.Extractions.CreateAsync(new ExtractionsCreateOptions
  {
      Document = document,
      JsonSchema = new Dictionary<string, object>
      {
          ["type"] = "object",
          ["properties"] = new Dictionary<string, object>
          {
              ["invoice_number"] = new Dictionary<string, object> { ["type"] = "string" },
              ["total"] = new Dictionary<string, object> { ["type"] = "number" },
          },
          ["required"] = new List<string> { "invoice_number", "total" },
      },
      Model = "retab-small",
      NConsensus = 1,
      Metadata = new Dictionary<string, string> { ["source"] = "docs" },
  });
  Console.WriteLine(result);
  ```

  ```java Java theme={null}
  import com.retab.RetabClient;
  import com.retab.models.MimeData;
  import java.net.URI;
  import java.util.List;
  import java.util.Map;

  public final class Example {
    public static void main(String[] args) throws Exception {
      RetabClient client = new RetabClient(System.getenv("RETAB_API_KEY"));

      MimeData document =
          MimeData.fromUrl(
              URI.create("https://my-bucket.s3.us-east-1.amazonaws.com/documents/Invoice.pdf"));

      Map<String, Object> jsonSchema =
          Map.of(
              "type", "object",
              "properties",
                  Map.of(
                      "invoice_number", Map.of("type", "string"),
                      "total", Map.of("type", "number")),
              "required", List.of("invoice_number", "total"));

      var result =
          client
              .extractions()
              .create(
                  document,
                  jsonSchema,
                  "retab-small",
                  null,
                  1L,
                  Map.of("source", "docs"),
                  null,
                  null,
                  null,
                  null,
                  null);
      System.out.println(result);
    }
  }
  ```

  ```curl cURL theme={null}
  curl -X POST \
    'https://api.retab.com/v1/extractions' \
    -H "Authorization: Bearer $RETAB_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "document": {
      "filename": "Invoice.pdf",
      "url": "https://my-bucket.s3.us-east-1.amazonaws.com/documents/Invoice.pdf"
    },
    "model": "retab-small",
    "json_schema": {
      "type": "object",
      "properties": {
        "invoice_number": {"type": "string"},
        "total": {"type": "number"}
      },
      "required": ["invoice_number", "total"]
    },
    "n_consensus": 1,
    "metadata": {"source": "docs"}
  }'
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "id": "extr_01G34H8J2K",
    "file": {
      "id": "file_6dd6eb00688ad8d1",
      "filename": "Invoice.pdf",
      "mime_type": "application/pdf"
    },
    "model": "retab-small",
    "json_schema": {
      "type": "object",
      "properties": {
        "invoice_number": { "type": "string" },
        "total": { "type": "number" }
      }
    },
    "n_consensus": 1,
    "output": {
      "invoice_number": "INV-2024-0042",
      "total": 1234.56
    },
    "consensus": {
      "choices": [],
      "likelihoods": {
        "invoice_number": 0.98,
        "total": 0.97
      }
    },
    "metadata": {
      "source": "docs"
    },
    "usage": {
      "prompt_tokens": 2760,
      "completion_tokens": 20,
      "total_tokens": 2780
    },
    "created_at": "2024-03-15T10:30:00Z"
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /v1/extractions
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://api.retab.com
security: []
paths:
  /v1/extractions:
    post:
      tags:
        - Extractions
      summary: Create Extraction
      description: >-
        Run a structured extraction on a document.


        Extracts structured data from the `document` according to the supplied

        `json_schema`, using the requested `model`. Returns the extraction

        with its `output`, consensus details, and usage on `201`. When

        `stream` is `true`, partial results are streamed back as they are
        produced.
      operationId: create_extraction
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateExtractionRequest'
        required: true
      responses:
        '200':
          description: Streaming extraction chunks
          content:
            application/stream+json:
              schema: {}
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Extraction'
        '202':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Extraction'
      security:
        - HTTPBearer: []
components:
  schemas:
    CreateExtractionRequest:
      properties:
        document:
          $ref: '#/components/schemas/MIMEData'
        json_schema:
          additionalProperties: true
          type: object
          title: Json Schema
          description: JSON schema describing the structured output
        model:
          type: string
          title: Model
          description: The model to use for the extraction
          default: retab-small
        instructions:
          anyOf:
            - type: string
            - type: 'null'
          title: Instructions
          description: >-
            Free-form instructions appended to the system prompt to steer the
            extraction.
        n_consensus:
          type: integer
          title: N Consensus
          description: >-
            Number of consensus extraction runs to perform. Uses deterministic
            single-pass when set to 1.
          default: 1
        metadata:
          anyOf:
            - additionalProperties:
                type: string
              type: object
            - type: 'null'
          title: Metadata
          description: User-defined metadata to associate with this extraction
        additional_messages:
          anyOf:
            - items:
                additionalProperties: true
                type: object
              type: array
            - type: 'null'
          title: Additional Messages
          description: Additional chat messages forwarded to the extraction model.
        bust_cache:
          type: boolean
          title: Bust Cache
          description: If true, skip the LLM cache and force a fresh completion
          default: false
        stream:
          type: boolean
          title: Stream
          default: false
        background:
          type: boolean
          title: Background
          description: >-
            If true, run asynchronously: returns immediately with status
            'queued' and an empty output. Poll GET /v1/<primitive>/{id} until
            status is terminal. Mutually exclusive with stream.
          default: false
        chunking_keys:
          anyOf:
            - additionalProperties:
                type: string
              type: object
            - type: 'null'
          title: Chunking Keys
      type: object
      required:
        - document
        - json_schema
      title: CreateExtractionRequest
      description: >-
        Request to run a structured extraction on a single document.


        Extends the base extraction request with the `document` to process
        (either

        inline content or a reference to a previously uploaded file) and a
        `stream`

        flag that controls whether results are returned incrementally.
    Extraction:
      properties:
        id:
          type: string
          title: Id
          description: Unique identifier of the extraction
        file:
          $ref: '#/components/schemas/FileRef'
          description: Information about the extracted file
        model:
          type: string
          title: Model
          description: Model used for the extraction
        json_schema:
          additionalProperties: true
          type: object
          title: Json Schema
          description: JSON schema used for the extraction
        n_consensus:
          type: integer
          title: N Consensus
          description: Number of consensus votes used
          default: 1
        instructions:
          anyOf:
            - type: string
            - type: 'null'
          title: Instructions
          description: Free-form instructions supplied with the extraction request.
        output:
          additionalProperties: true
          type: object
          title: Output
          description: The extracted structured data
        status:
          type: string
          enum:
            - pending
            - queued
            - in_progress
            - completed
            - failed
            - cancelled
          title: Status
          description: >-
            Lifecycle status. The synchronous path returns 'completed'.
            Background runs progress pending -> queued -> in_progress ->
            completed | failed | cancelled.
          default: pending
        error:
          anyOf:
            - $ref: '#/components/schemas/PrimitiveError'
            - type: 'null'
          description: >-
            Error details when a background run fails; null otherwise. Always
            present so consumers can read it without an existence check.
        consensus:
          anyOf:
            - $ref: '#/components/schemas/ExtractionConsensus'
            - type: 'null'
          description: Consensus metadata for multi-vote extraction runs
        metadata:
          anyOf:
            - additionalProperties:
                type: string
              type: object
            - type: 'null'
          title: Metadata
        usage:
          anyOf:
            - $ref: '#/components/schemas/RetabUsage'
            - type: 'null'
          description: Usage information for the extraction
        created_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Created At
      type: object
      required:
        - file
        - id
        - json_schema
        - model
        - output
      title: Extraction
      description: A stored extraction record from the Retab API.
    MIMEData:
      properties:
        filename:
          type: string
          title: Filename
          description: The filename of the file
          examples:
            - file.pdf
            - image.png
            - data.txt
        url:
          type: string
          title: Url
          description: The URL of the file in base64 format
          examples:
            - data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...
      additionalProperties: false
      type: object
      required:
        - filename
        - url
      title: MIMEData
      description: A file represented by its `filename` and a base64 data `url`.
    FileRef:
      properties:
        id:
          type: string
          title: Id
          description: ID of the file
        filename:
          type: string
          title: Filename
          description: Filename of the file
        mime_type:
          type: string
          title: Mime Type
          description: MIME type of the file
      type: object
      required:
        - filename
        - id
        - mime_type
      title: FileRef
      description: Public/shared file reference used across SDK and customer-facing APIs.
    PrimitiveError:
      properties:
        code:
          type: string
          title: Code
          description: Machine-readable error code.
        message:
          type: string
          title: Message
          description: Human-readable error message.
        details:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Details
          description: Optional structured error context.
      type: object
      required:
        - code
        - message
      title: PrimitiveError
    ExtractionConsensus:
      properties:
        choices:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Choices
          description: >-
            Alternative extraction vote outputs used to build the consolidated
            result.
          default: []
        likelihoods:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Likelihoods
          description: >-
            Consensus likelihood tree mirroring the extraction output. Scalar
            leaves carry per-value voter-agreement in [0, 1]; list leaves carry
            one entry per matched list item.
      type: object
      title: ExtractionConsensus
    RetabUsage:
      properties:
        credits:
          type: number
          title: Credits
          description: Credits consumed for processing
      type: object
      required:
        - credits
      title: RetabUsage
      description: Usage information for document processing.
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````