Data Extraction
Define a schema once, then extract structured data from any text —consistently, every time.
Snippet setup
The Python and TypeScript snippets on this page set BASE_URL to the host of the base URL and read your key from AI_2KW_API_KEY. Python: import os, requests, BASE_URL = "https://api.2kw.ai", api_key = os.environ["AI_2KW_API_KEY"] and headers = {"Authorization": f"Bearer {api_key}"}. TypeScript: const BASE_URL = "https://api.2kw.ai" and const apiKey = process.env.AI_2KW_API_KEY.
Quick Start
Define a schema
Create a schema — a standard JSON Schema describing the fields you want to extract:
{
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string", "format": "email" },
"phone": { "type": "string" }
},
"required": ["name"]
}
Commit and label
Hit Commit to lock in an immutable version. The latest label updates automatically — create custom labels like production to pin versions for consumers.
Extract
curl -X POST https://api.2kw.ai/v1/extractions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk_your_api_key" \
-d '{
"schemaId": "your-schema-id",
"inputText": "Contact: John Doe, john@example.com, 555-1234",
"model": "gpt-5.1"
}'
Response:
{
"status": "COMPLETED",
"result": {
"structuredOutput": {
"name": "John Doe",
"email": "john@example.com",
"phone": "555-1234"
}
}
}
Schema in, structured data out. The rest of this page covers running extractions, re-running and listing them; Schemas covers versions and labels, and Large documents how long inputs are handled.
How It Works
2kw.ai takes a standard JSON Schema definition and uses it to extract structured output from unstructured text. You define the fields, types, and constraints — 2kw.ai returns validated, schema-conformant JSON.
The workflow is: define schema → commit version → send text → receive structured output.
Schemas use JSON Schema
If you've used JSON Schema before, you already know the format. If not —it's just a way to describe what fields you expect, their types, and which ones are required.
Running Extractions
Synchronous
POST /v1/extractions
The standard extraction endpoint. Send text and, for inputs that fit a synchronous run, get the structured data back in the same response. Larger inputs are handed to background processing automatically; see the responses below the example.
Send schemaId, model (a platform model name such as gpt-5.1, or provider/model for your own provider) and the input: inputText, up to 10 inputImages, or both. schemaVersionId pins a version; without it the latest active one runs. Every field: API reference.
Request
curl -X POST https://api.2kw.ai/v1/extractions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk_your_api_key" \
-d '{
"schemaId": "your-schema-id",
"inputText": "Invoice #INV-2024-001 from Acme Corp. Total: $1,250.00",
"model": "gpt-5.1"
}'
Responses. Always read status before you read the result:
| HTTP status | status | Meaning |
|---|---|---|
201 Created | COMPLETED | The extraction ran; result.structuredOutput holds the data |
201 Created | FAILED | The extraction ran and failed; errorMessage says why |
202 Accepted | PENDING | The input was too large for a synchronous run and was queued in the background. The response carries a Location header and Retry-After: 5; poll it as described under Asynchronous |
A failed extraction is still a 201, so checking the HTTP status alone is not enough:
const response = await fetch(`${BASE_URL}/v1/extractions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
},
body: JSON.stringify({ schemaId, inputText, model }),
});
if (!response.ok) {
throw new Error(`Request rejected: ${response.status}`);
}
const data = await response.json();
if (data.status === "COMPLETED") {
console.log(data.result.structuredOutput);
} else if (data.status === "FAILED") {
throw new Error(data.errorMessage ?? "Extraction failed");
} else {
// PENDING: poll GET /v1/extractions/{id} until COMPLETED or FAILED
console.log("Queued, poll", response.headers.get("Location"));
}
Extracting from Images
You can also extract structured data from images (up to 10 per request). Each image must be base64-encoded with its MIME type:
Image extraction
curl -X POST https://api.2kw.ai/v1/extractions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk_your_api_key" \
-d '{
"schemaId": "your-schema-id",
"inputImages": [
{
"data": "iVBORw0KGgoAAAANSUhEUg...",
"mimeType": "image/png"
}
],
"model": "gpt-5.1"
}'
Supported image MIME types: image/png, image/jpeg, image/gif, image/webp. You can combine inputText and inputImages in a single request.
Asynchronous
POST /v1/extractions/async
For large inputs, submit an extraction for background processing. You get back a 202 Accepted with a Location header to poll:
HTTP/1.1 202 Accepted
Location: /v1/extractions/{id}
Retry-After: 5
Poll the Location URL until status changes from PENDING/PROCESSING to COMPLETED or FAILED.
Estimate Tokens First
POST /v1/extractions/estimate
Before running an extraction, you can estimate the cost. Send the same schema and input text you'd use for a real extraction:
The request takes schemaId, inputText and optionally schemaVersionId. Every field: API reference.
Response:
{
"inputTokens": 4200,
"estimatedOutputTokens": 350,
"strategy": "SINGLE_SHOT"
}
The strategy field tells you which processing path will be used (SINGLE_SHOT, CHUNKED, or ASYNC); see Large documents.
Extraction Response
The full extraction response includes structuredOutput, process metadata, and resultMetadata with dedup stats and grounding scores:
{
"id": "extraction-uuid",
"status": "COMPLETED",
"strategy": "CHUNKED",
"result": {
"structuredOutput": {
"company": "ACME GmbH",
"parts": [
{ "sourceFile": "gear.geo", "material": "1.4301", "quantity": 5 },
{ "sourceFile": "shaft.geo", "material": "Steel", "quantity": 2 }
]
},
"metadata": {
"inputTokens": 12500,
"outputTokens": 340,
"durationMs": 4200,
"model": "gpt-5.1",
"chunksProcessed": 2
},
"resultMetadata": {
"dedup": {
"applied": true,
"itemsRemoved": 1,
"itemsMerged": 0,
"resequenced": true,
"originalItemCount": 3,
"finalItemCount": 2
},
"postValidation": {
"applied": true,
"hallucinatedItemsRemoved": 0,
"requiredFieldsRestored": 0,
"removedItemKeys": []
},
"scoring": {
"methods": ["grounding"],
"grounding": { "score": 0.91 },
"fields": {
"company": {
"grounding": { "score": 1.0, "basis": "exact_match" }
}
},
"items": {
"parts[0]": {
"grounding": { "score": 0.92 },
"fields": {
"sourceFile": { "grounding": { "score": 1.0, "basis": "exact_match" } },
"material": { "grounding": { "score": 1.0, "basis": "exact_match" } },
"quantity": { "grounding": { "score": 0.5, "basis": "unverifiable" } }
}
},
"parts[1]": {
"grounding": { "score": 0.95 },
"fields": {
"sourceFile": { "grounding": { "score": 1.0, "basis": "exact_match" } },
"material": { "grounding": { "score": 0.9, "basis": "normalized_match" } },
"quantity": { "grounding": { "score": 0.5, "basis": "unverifiable" } }
}
}
}
}
}
}
}
The example is shortened to the grounding scores. A current result also carries resultMetadata.schemaValidation (Schema Validation), resultMetadata.rules (Business Rules) and the confidence fields shown under Composite Confidence.
Re-running Extractions
POST /v1/extractions/{id}/rerun
Need to retry an extraction with the same config? Hit the rerun endpoint. Creates a new extraction —the original stays untouched.
The re-run copies the original's schema version, input text and model, and it runs the same
way the original did: an extraction that was queued asynchronously is queued again and comes
back PENDING, a synchronous one is executed inline and comes back with its result.
Not every extraction can be re-run:
| Response | When |
|---|---|
404 Not Found | No such extraction in your organization |
409 Conflict | The extraction is still PENDING or PROCESSING |
409 Conflict | The extraction was vision-only —images are not stored and cannot be replayed |
409 Conflict | The schema version it ran against has since been deleted |
COMPLETED and FAILED extractions are eligible. Each re-run is billed as a new extraction.
POST /v1/extractions/rerun
Re-run up to 100 extractions in one call. Select them either by ID or with the filters of
GET /v1/extractions (status, schemaVersionId, search), not both:
curl -X POST https://api.2kw.ai/v1/extractions/rerun \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{"status": "FAILED", "schemaVersionId": "<schemaVersionId>"}'
The call answers 202 Accepted with one outcome per selected extraction. Every eligible one
is queued as a new extraction with status PENDING, whatever mode the original ran in; poll
its rerunId. The rules above decide eligibility, but an ineligible extraction does not fail
the call: it comes back SKIPPED with a reason, an unknown ID comes back NOT_FOUND, and
the rest are queued all the same.
{
"queued": 1,
"skipped": 1,
"results": [
{ "extractionId": "ext_1", "outcome": "QUEUED", "rerunId": "ext_9", "reason": null },
{ "extractionId": "ext_2", "outcome": "SKIPPED", "rerunId": null,
"reason": "Extraction is still in progress. Wait for it to finish before re-running it." }
]
}
| Response | When |
|---|---|
400 Bad Request | Neither or both of ids and a filter were given, or the filter matches more than 100 extractions |
402 Payment Required | The batch needs more usage than the organisation has left; nothing was queued |
Listing and Filtering
GET /v1/extractions
Filter with status (PENDING, PROCESSING, COMPLETED or FAILED), schemaVersionId and search (by model name). Page with page (0-based) and size (default 20). Every field: API reference.
Use Cases
- Contact extraction —names, emails, phone numbers from unstructured text
- Invoice processing —invoice numbers, dates, amounts, line items from documents
- Resume parsing —skills, experience, education from CVs
- Document analysis —key fields from contracts, reports, forms
- Data entry automation —turn free-text notes into structured database records