# Schema authoring

> Write JSON Schemas that extract reliably, save them as versioned schemas and use them from code.

A schema says which fields you want and what shape the result has. Parsefox uses
[JSON Schema](https://json-schema.org/) (draft 2020-12) with a few rules that keep
extraction predictable.

## Ways to get a schema

- **Templates**: built-in schemas for common documents (invoice, receipt, purchase
  order, bill of lading, bank statement and more). `GET /v1/templates` lists them,
  `GET /v1/templates/{id}` returns the schema. Extract with `template_id`, or copy one
  in the console and adjust it. Templates can improve over time and cannot be pinned,
  so for production save the template as your own schema (in the console, or
  `POST /v1/schemas` with the template's `schema` and `instructions`) and pin its
  version.
- **Suggest from examples**: in the console under **Schemas → Suggest from examples**,
  upload one to five sample documents and Parsefox proposes fields that appear in
  them, with where each was found. This uses live models and costs a few cents at
  most.
- **Write your own** in the console's field editor or as JSON, and save it with
  `POST /v1/schemas`.
- **Inline**: send `schema` (and optional `instructions`) with each extraction. Handy
  when schemas are generated from your own models, but saved schemas are easier to
  review, version and test.

## Example

```json
{
  "type": "object",
  "properties": {
    "invoice_number": {
      "type": "string",
      "description": "Invoice identifier as printed; keep leading zeros."
    },
    "invoice_date": { "type": ["string", "null"], "description": "Date of issue." },
    "total": { "type": "number", "description": "Total amount due, including tax." },
    "currency": { "type": ["string", "null"], "description": "ISO 4217 code, such as EUR." },
    "items": {
      "type": "array",
      "description": "One entry per invoice line.",
      "items": {
        "type": "object",
        "properties": {
          "description": { "type": "string" },
          "quantity": { "type": ["number", "null"] },
          "amount": { "type": "number", "description": "Line total." }
        },
        "required": ["description", "amount"]
      }
    }
  },
  "required": ["invoice_number", "total"]
}
```

## Rules

- The root is an `object` with at least one property.
- Every node has an explicit `type`: `string`, `number`, `integer`, `boolean`,
  `object` or `array`. A nullable field uses `["string", "null"]`; unions of two
  non-null types are not supported.
- Objects list their `properties` (no open objects: `additionalProperties` may only be
  `false`). Arrays define `items`.
- Not supported: `$ref`, `$dynamicRef`, `oneOf`, `anyOf`, `allOf`, `not`, `if` /
  `then` / `else`, `patternProperties`, `prefixItems`, `dependentSchemas`,
  `unevaluatedProperties`.
- At most 6 levels of nesting, 100 properties per object and 256 KiB in total.
- Fields not listed in `required` may be `null` when the document does not contain
  them.

Breaking a rule returns `422 invalid_schema` with a message that names the problem.

## Writing good descriptions

The `description` of each field is the most effective way to steer extraction:

- Say what the field is in the document's terms: "Total amount due, including tax",
  not "total".
- Say how to treat formats: "Copy the date as printed", "ISO 4217 code".
- Say what to do when it's absent or ambiguous: "null if no PO number is printed".
- Use schema-level `instructions` (up to 16,000 characters) for rules that apply to
  the whole document, such as "Amounts are in the currency printed in the header".

## Saved schemas and versions

Saved schemas have an id (`sch_…`) and immutable, numbered versions.

```bash
# Create (version 1)
curl "$PARSEFOX_BASE_URL/v1/schemas" \
  -H "Authorization: Bearer $PARSEFOX_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Supplier invoice", "schema": {…}, "instructions": "Totals include tax."}'

# Publish version 2; base_version protects against overwriting someone else's change
curl "$PARSEFOX_BASE_URL/v1/schemas/sch_8f73a8efa4f34f87/versions" \
  -H "Authorization: Bearer $PARSEFOX_API_KEY" -H "Content-Type: application/json" \
  -d '{"schema": {…}, "base_version": 1}'
```

- Extract with `schema_id` to use the latest version, or add `schema_version` to pin
  one. **Pin in production**: a new version then never changes your results until you
  update the number.
- `base_version` is optional; when the latest version is newer, the request fails with
  `409 schema_conflict` instead of silently replacing it.
- `PATCH /v1/schemas/{id}` renames, describes or archives a schema. Archived schemas
  still work for pinned extractions.
- Schemas are shared by test and live mode, so test with the exact id and version you
  will use live.
- Each job records the schema id and version it used; filter runs with
  `GET /v1/extractions?schema_id=…&schema_version=…`.

## From your own models

Many libraries emit JSON Schema. Check the output against the rules above; for
example, Pydantic's `model_json_schema()` produces `$ref` for nested models, so inline
them or write the nested object directly.
