# Set up the Dynamite Docs API (instructions for coding agents)

Give your project AI document extraction and accounting data intelligence without building an OCR pipeline or training custom models. Dynamite Docs turns PDFs, scanned invoices, receipts, bank statements, and spreadsheets into clean, verified structured data (JSON, CSV, Excel, Google Sheets, or Tally XML).

Use it to automate accounts payable, feed accounting ledgers (QuickBooks, Zoho Books, Xero, Tally), extract multi-column financial tables, or run 100% private, offline inference via the local Ollama companion.

## 1. Pick the right capability

| Capability | Use it for | Modes and processing routes |
| --- | --- | --- |
| **Infer (`/api/extract/infer`)** | Propose structured fields and table rows from any document. | `hosted` for cloud GPU inference; `byok` to use your own OpenAI / Anthropic / Gemini / Mistral key (0 PE markup); `local` for 100% offline Ollama inference on loopback `http://127.0.0.1:8756`. |
| **Batch Jobs (`/api/jobs/run`)** | Process large document collections asynchronously with PostgreSQL durable queue leases, retries, and status tracking. | Backed by Cloudflare R2 file storage on Starter, Pro, and Scale plans. |
| **Outbound Webhooks (`/api/webhooks`)** | Receive signed HTTP POST notifications when an extraction completes. | Payloads signed with HMAC-SHA256 (`X-Dynamite-Signature`). Receiver can deduplicate using `X-Dynamite-Delivery-Id`. |
| **Export Formats (`/api/extractions/:id/export`)** | Download reviewed and corrected extractions. | `format=json`, `format=csv` (with UTF-8 BOM), `format=xlsx` (with auto-typed dates and currencies), or Tally XML voucher download. |
| **Google Sheets Sync (`/api/sheets/export`)** | Push extraction results directly into a Google Spreadsheet tab. | Connect via OAuth; tokens encrypted with AES-256-GCM. |

---

## 2. API Authentication

Include your API token in the `Authorization` header:

```bash
Authorization: Bearer <your_api_token>
```

> **Rules for AI agents:**
> - Never hardcode the API token in source code, commits, or chat transcripts.
> - Store it in `.env` as `DYNAMITEDOCS_API_KEY` or pass it via environment variable.
> - Ensure `.env` is listed in `.gitignore`.

---

## 3. Quick Start Examples

### A. Extract an Invoice with cURL

```bash
curl -X POST "https://www.dynamitedocs.com/api/extract/infer" \
  -H "Authorization: Bearer $DYNAMITEDOCS_API_KEY" \
  -F "file=@invoice.pdf" \
  -F "documentType=invoice"
```

### B. Python SDK / HTTP Script

```python
import os
import requests

API_KEY = os.environ.get("DYNAMITEDOCS_API_KEY")
API_URL = "https://www.dynamitedocs.com/api/extract/infer"

headers = {"Authorization": f"Bearer {API_KEY}"}
with open("statement.pdf", "rb") as f:
    response = requests.post(
        API_URL,
        headers=headers,
        files={"file": f},
        data={"documentType": "bank_statement"}
    )

data = response.json()
print("Extracted fields:", data.get("fields"))
print("Line items:", data.get("table"))
print("Confidence:", data.get("confidence"))
```

### C. Node.js / TypeScript Example

```typescript
import fs from 'node:fs';

const API_KEY = process.env.DYNAMITEDOCS_API_KEY!;
const form = new FormData();
form.append('file', new Blob([fs.readFileSync('invoice.pdf')]), 'invoice.pdf');
form.append('documentType', 'invoice');

const res = await fetch('https://www.dynamitedocs.com/api/extract/infer', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${API_KEY}`,
  },
  body: form,
});

const result = await res.json();
console.log('Invoice #:', result.fields?.invoice_number);
console.log('Total:', result.fields?.total_amount);
console.log('Math verified:', result.reconciliation?.is_balanced);
```

---

## 4. Reusable Layout Patterns ("Infer → Correct → Remember")

Dynamite Docs automatically saves layout mapping patterns when a user corrects or confirms columns:
- Propose fields and rows from new document layouts.
- When column names or math mappings are confirmed, subsequent documents from the same vendor/supplier automatically reuse the structure.
- Cell-level confidence scoring flags values below threshold (`0.90`) for human review in the Data Studio workspace.

---

## 5. Local Air-Gapped Mode (Ollama Companion)

For sensitive financial and tax documents where data must never leave the machine:
1. Run the local signed companion (`npm run local:start` or Windows companion app).
2. The companion binds to loopback `http://127.0.0.1:8756`.
3. Extraction executes locally on Ollama using Llama 3 / Mistral / Qwen models.
4. Costs 0 PE; source files stay on the local machine with browser-only storage.

---

## Resources

- Web App & Workspace: https://www.dynamitedocs.com/app
- Accuracy & Benchmark Metrics: https://www.dynamitedocs.com/document-extraction-accuracy-benchmarks
- Machine-readable llms.txt: https://www.dynamitedocs.com/llms.txt
- Support & Enterprise: support@dynamitedocs.com
