# Extract your first document

Nugget turns documents into structured values with evidence. This guide uses the
same organization key for upload, extraction, and polling. Release **v3** still
uses **`/v1/...`** URL paths.

## Before you start

Obtain an organization API key from your Nugget dashboard. For a hosted account,
configure that organization's provider credentials (BYOK) before using a model.
Self-hosted provider access is configured by your deployment operator.

Set `NUGGET_BASE_URL` to your deployment's HTTPS origin (without `/v1`) and
`NUGGET_API_KEY` to your organization key. Keep the key server-side. The
`x-api-key` header is required on every operation below.

Model availability is organization-specific. Discover it rather than copying a
model ID from an old example:

```bash
curl --fail-with-body "$NUGGET_BASE_URL/v1/models" \
  -H "x-api-key: $NUGGET_API_KEY"
```

Choose a returned `id` and set `NUGGET_MODEL` to that exact value.

## Complete Python workflow

Install `httpx`. This runnable example creates a tiny CSV fixture in memory,
uploads it, submits a typed JSON extraction request, and polls for at most five
minutes. CSV and XLSX evidence may have no bounding box.

```python
import os
import time
import uuid
from urllib.parse import urljoin, urlsplit

import httpx

base = os.environ["NUGGET_BASE_URL"].rstrip("/")
model = os.environ["NUGGET_MODEL"]
headers = {"x-api-key": os.environ["NUGGET_API_KEY"]}

with httpx.Client(headers=headers, timeout=60, follow_redirects=False) as client:
    upload = client.post(
        base + "/v1/uploads",
        files={"file": ("invoice.csv", b"customer,total\nAcme,125.50\n", "text/csv")},
    )
    upload.raise_for_status()
    file_id = upload.json()["file_id"]
    creation_key = str(uuid.uuid4())  # Persist and reuse for retries of this creation.
    response = client.post(base + "/v1/extractions", headers={"Idempotency-Key": creation_key}, json={
        "file_id": file_id,
        "model": model,
        "execution": "async",
        "schema": {
            "type": "object",
            "properties": {
                "customer": {"type": "string"},
                "total": {"type": "number"},
            },
        },
    })
    response.raise_for_status()
    assert response.status_code == 202
    accepted = response.json()
    status_url = urljoin(base + "/", accepted["status_url"])
    if (urlsplit(status_url).scheme, urlsplit(status_url).netloc) != (urlsplit(base).scheme, urlsplit(base).netloc):
        raise ValueError("Unexpected polling host")
    deadline = time.monotonic() + 300
    while time.monotonic() < deadline:
        response = client.get(status_url)
        response.raise_for_status()
        job = response.json()
        if job["status"] == "failed":
            raise RuntimeError(job["error"])
        if job["status"] == "succeeded":
            result = job["result"]
            print(result["data"]["customer"])
            print(result["provenance"].get("/customer"))
            break
        time.sleep(2)
    else:
        raise TimeoutError(f"Stop polling; retain this URL to resume: {status_url}")
```

This example deliberately stops on HTTP failures instead of blindly retrying
job creation. Production retry guidance is in [Jobs and retries](/guides/jobs).
An HTTP 200 polling response can still contain a **failed job**.

## Complete TypeScript workflow

With Node 22+, save this as `quickstart.ts` and run it with `npx tsx quickstart.ts`.
Use the same environment variables as the Python example. This uses built-in
`fetch`; generated-client configuration is in the [agent guide](/guides/agents).

```typescript
import process from "node:process";
import { randomUUID } from "node:crypto";

async function extract() {
  const base = new URL(process.env.NUGGET_BASE_URL!);
  const headers = { "x-api-key": process.env.NUGGET_API_KEY! };
  const form = new FormData();
  form.append("file", new Blob(["customer,total\nAcme,125.50\n"], { type: "text/csv" }), "invoice.csv");
  const upload = await fetch(new URL("/v1/uploads", base), {
    method: "POST", headers, body: form, redirect: "error", signal: AbortSignal.timeout(60000),
  });
  if (!upload.ok) throw Error(`Upload failed: ${upload.status}`);
  const { file_id } = await upload.json();
  const creationKey = randomUUID(); // Persist and reuse if this response is lost.
  const accepted = await fetch(new URL("/v1/extractions", base), {
    method: "POST", redirect: "error", signal: AbortSignal.timeout(60000),
    headers: { ...headers, "Content-Type": "application/json", "Idempotency-Key": creationKey },
    body: JSON.stringify({ file_id, model: process.env.NUGGET_MODEL, execution: "async",
      schema: { type: "object", properties: { customer: { type: "string" } } } }),
  });
  if (accepted.status !== 202) throw Error(`Creation failed: ${accepted.status}`);
  const { status_url } = await accepted.json();
  const polling = new URL(status_url, base);
  if (polling.origin !== base.origin) throw Error("Unexpected polling origin");
  const deadline = Date.now() + 300000;
  while (Date.now() < deadline) {
    const response = await fetch(polling, { headers, redirect: "error", signal: AbortSignal.timeout(Math.min(60000, Math.max(1, deadline - Date.now()))) });
    if (!response.ok) throw Error(`Polling failed: ${response.status}`);
    const job = await response.json();
    if (job.status === "failed") throw Error(JSON.stringify(job.error));
    if (job.status === "succeeded") {
      console.log(job.result.data.customer, job.result.provenance["/customer"]);
      return;
    }
    await new Promise(resolve => setTimeout(resolve, 2000));
  }
  throw Error(`Polling deadline reached; retain this URL: ${polling}`);
}
void extract();
```

## Submit with curl

After uploading, set `FILE_ID` to the returned `file_id`. With `jq` installed:

```bash
jq -n --arg file_id "$FILE_ID" --arg model "$NUGGET_MODEL" \
  '{file_id:$file_id,model:$model,execution:"async",schema:{type:"object",properties:{customer:{type:"string"}}}}' |
curl --fail-with-body "$NUGGET_BASE_URL/v1/extractions" \
  -H "x-api-key: $NUGGET_API_KEY" -H 'Content-Type: application/json' --data-binary @-
```

The response is **202 Accepted**, not completed extraction. Resolve its
`status_url` against your deployment and GET it using the same key.

## Fast inline work or explicit jobs

OCR, classification, and Locate accept `execution: "auto"` (the default) or
`"async"`. Always inspect the status before interpreting the response body:

```python
response = client.post(base + "/v1/ocr", json={"file_id": file_id, "execution": "auto"})
response.raise_for_status()
if response.status_code == 202:
    accepted = response.json()  # retain job_id and poll status_url
else:
    ocr = response.json()       # completed OcrResponse
```

The fragment above assumes an open authenticated `client`. Extraction currently
queues in both modes. A callback also selects async execution. Client metadata
alone does not.

## Next steps

- [Operation selection](/guides/operations): choose the right endpoint.
- [Schemas and provenance](/guides/schema): understand values, errors, and evidence.
- [Retention](/guides/retention): understand source and result cleanup.
- [ReDoc reference](/redoc): complete argument and response schemas.
- [OpenAPI](/openapi.json): machine-readable contract for this deployment.
