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

# Generate

> Generates a JSON Schema from scratch by inferring structure from the content of the provided example documents.

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

  document = MIMEData(
      filename="passport.jpeg",
      url="https://storage.googleapis.com/retab-docs/passport.jpeg",
  )

  response = client.schemas.generate(
      documents=[document],
      model="retab-small",      # or any model your plan supports
  )

  print("Generated JSON Schema:")
  print(response)
  ```

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

  config();

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

  const document = {
    filename: "passport.jpeg",
    url: "https://storage.googleapis.com/retab-docs/passport.jpeg",
  };

  const result = await client.schemas.generate([document], "retab-small");
  ```

  ```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: "passport.jpeg",
  		URL:      "https://storage.googleapis.com/retab-docs/passport.jpeg",
  	}

  	result, err := client.Schemas.Generate(ctx, &retab.SchemasGenerateParams{
  		Documents: []any{document},
  		Model:     ptr("retab-small"),
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	fmt.Println("Generated JSON Schema:")
  	fmt.Println(*result)
  }
  ```

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

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

  document = {
    filename: 'passport.jpeg',
    url: 'https://storage.googleapis.com/retab-docs/passport.jpeg',
  }

  response = client.schemas.generate(
    documents: [document],
    model: 'retab-small',
  )

  puts 'Generated JSON Schema:'
  puts response
  ```

  ```rust Rust theme={null}
  use retab::resources::schemas::GenerateParams;
  use retab::{MimeData, Retab};

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = Retab::new(std::env::var("RETAB_API_KEY")?);
      let document = MimeData::new(
          "passport.jpeg",
          "https://storage.googleapis.com/retab-docs/passport.jpeg",
      );

      let mut params = GenerateParams::new(vec![document]);
      params.body.model = Some("retab-small".into());

      let response = client.schemas().generate(params).await?;

      println!("Generated JSON Schema:");
      println!("{:?}", response);
      Ok(())
  }
  ```

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

  use Retab\Client;

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

  $result = $client->schemas()->generate(
      documents: [[
          'filename' => 'passport.jpeg',
          'url' => 'https://storage.googleapis.com/retab-docs/passport.jpeg',
      ]],
  );
  print_r($result);
  ```

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

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

  var result = await client.Schemas.GenerateAsync(new SchemasGenerateOptions());
  Console.WriteLine(result);
  ```

  ```java Java theme={null}
  import com.retab.RetabClient;

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

      var result = client.schemas().generate(null, "retab-1.5", "Extract the invoice fields", null);
      System.out.println(result);
    }
  }
  ```

  ```curl cURL theme={null}
  curl https://api.retab.com/v1/schemas/generate \
    -H "Authorization: Bearer $RETAB_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "documents": [
        {
          "filename": "passport.jpeg",
          "url": "https://storage.googleapis.com/retab-docs/passport.jpeg"
        }
      ],
      "model": "retab-small"
    }'

  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "title": "Invoice Document Schema",
    "description": "A schema for storing structured data extracted from invoice documents, including parties, line items, and payment details.",
    "type": "object",
    "X-SchemaType": "generic",
    "properties": {
      "invoice_number": {
        "type": "string",
        "description": "Unique identifier for the invoice."
      },
      "date_of_issue": {
        "type": "string",
        "description": "Date when the invoice was issued."
      },
      "date_due": {
        "type": "string",
        "description": "Date when the invoice payment is due."
      },
      "seller": {
        "$ref": "#/$defs/party"
      },
      "bill_to": {
        "$ref": "#/$defs/party"
      },
      "ship_to": {
        "$ref": "#/$defs/party"
      },
      "line_items": {
        "type": "array",
        "description": "List of items or services billed on the invoice.",
        "items": {
          "$ref": "#/$defs/line_item"
        }
      },
      "subtotal": {
        "type": "number",
        "description": "Subtotal amount before taxes or discounts."
      },
      "total": {
        "type": "number",
        "description": "Total amount due."
      },
      "amount_due": {
        "type": "number",
        "description": "Amount due for payment."
      },
      "currency": {
        "type": "string",
        "description": "Currency code (e.g., USD, EUR)."
      }
    },
    "required": [
      "invoice_number",
      "date_of_issue",
      "date_due",
      "seller",
      "bill_to",
      "ship_to",
      "line_items",
      "subtotal",
      "total",
      "amount_due",
      "currency"
    ],
    "additionalProperties": false,
    "$defs": {
      "party": {
        "type": "object",
        "description": "Information about a party involved in the invoice (seller, buyer, or recipient).",
        "properties": {
          "name": {
            "type": "string",
            "description": "Name of the party."
          },
          "address": {
            "type": "string",
            "description": "Full address of the party."
          },
          "email": {
            "type": "string",
            "description": "Email address of the party."
          },
          "tax_id": {
            "type": "string",
            "description": "Tax identification number or EIN."
          }
        },
        "required": ["name", "address", "email", "tax_id"],
        "additionalProperties": false
      },
      "line_item": {
        "type": "object",
        "description": "A single item or service listed on the invoice.",
        "properties": {
          "description": {
            "type": "string",
            "description": "Description of the item or service."
          },
          "service_period": {
            "type": "string",
            "description": "Service period or date range for the item."
          },
          "quantity": {
            "type": "number",
            "description": "Quantity of the item or service."
          },
          "unit_price": {
            "type": "number",
            "description": "Unit price of the item or service."
          },
          "amount": {
            "type": "number",
            "description": "Total amount for this line item."
          }
        },
        "required": [
          "description",
          "service_period",
          "quantity",
          "unit_price",
          "amount"
        ],
        "additionalProperties": false
      }
    }
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /v1/schemas/generate
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://api.retab.com
security: []
paths:
  /v1/schemas/generate:
    post:
      tags:
        - Schemas
      summary: Generate Schema From Examples
      description: >-
        Generates a JSON Schema from scratch by inferring structure from the
        content of the provided example documents.
      operationId: generate_schema_from_examples
      parameters:
        - in: header
          name: Idempotency-Key
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Idempotency-Key
          required: false
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateSchemaRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SchemaGeneration'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    GenerateSchemaRequest:
      properties:
        documents:
          items:
            $ref: '#/components/schemas/MIMEData'
          type: array
          title: Documents
        model:
          type: string
          title: Model
          default: retab-small
        instructions:
          anyOf:
            - type: string
            - type: 'null'
          title: Instructions
        background:
          type: boolean
          title: Background
          description: >-
            If true, run asynchronously: returns immediately with status
            'queued'. Poll GET /v1/schemas/generate/{schema_generation_id} until
            status is terminal.
          default: false
      type: object
      required:
        - documents
      title: GenerateSchemaRequest
      description: >-
        Body to generate a JSON schema from example `documents`, optionally
        steered by `instructions`.
    SchemaGeneration:
      properties:
        object:
          type: string
          title: Object
          default: schema
        created_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Created At
        json_schema:
          additionalProperties: true
          type: object
          title: Json Schema
          default: {}
        strict:
          type: boolean
          title: Strict
          default: true
        id:
          type: string
          title: Id
          description: Unique identifier of the schema generation.
        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.
      type: object
      required:
        - id
      title: SchemaGeneration
      description: Public generated schema response.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
          default: []
      type: object
      title: HTTPValidationError
    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`.
    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
    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
          default: null
        ctx:
          type: object
          title: Context
          default: {}
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````