# Customer API Quickstart — INVOX v0.1

**Audience:** Developer integrating INVOX into an ERP, DMS, or accounting system  
**Base URL:** `https://api.invoxapi.de` (production, EU-hosted)  
**Authentication:** `X-API-Key: in_<32chars>_fl` header on every request (except the no-account demo below)  
**Reference:** [OpenAPI](https://api.invoxapi.de/openapi.json) · [Swagger UI](https://api.invoxapi.de/docs) · [Postman collection](https://api.invoxapi.de/postman/INVOX.postman_collection.json)

---

## Try it first — no account, no key

`POST /v1/demo/validate` runs the real validation engine on a small XML invoice
(max. 50 KB, 5 requests per hour per IP, no signed proof, nothing stored).
The sample below is the same valid XRechnung 3.0 UBL invoice the website uses:

```bash
curl -s https://invoxapi.de/dashboard/rechnung-beispiel.xml -o rechnung.xml
python3 -c 'import json;print(json.dumps({"xml": open("rechnung.xml").read()}))' \
  | curl -s -X POST "https://api.invoxapi.de/v1/demo/validate?lang=de" \
      -H "Content-Type: application/json" --data-binary @-
# → {"verdict": "valid", "format_detected": "XRECHNUNG_3_UBL", "ruleset_version": "3.0.2", "errors": [], ...}
```

Remove the `<cbc:BuyerReference>` line and send it again: the answer is `"verdict": "invalid"`
with rule `BR-DE-15`, `bt_number` `BT-10`, a plain-language `human_message` and a
`fix_hint` (what to ask the recipient for — INVOX never invents the value).

---

## 0. Get an API Key

`POST /v1/auth/register` is open self-service registration — **no invitation
or registration code is needed** (keine Einladung nötig). You only need your
company name, e-mail, a password, your VAT ID (or German tax number) and the
explicit acceptance of AGB and AVV:

```bash
curl -X POST https://api.invoxapi.de/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "you@example.com",
    "password": "at least 8 characters",
    "tenant_name": "Your Company GmbH",
    "vat_id": "DE123456789",
    "agb_accepted": true,
    "avv_accepted": true
  }'
```

`agb_accepted`/`avv_accepted` are a hard gate — no account is created without
both. Then log in to get a session and create your first API key:

```bash
curl -X POST https://api.invoxapi.de/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "you@example.com", "password": "..."}'
# → sets a session cookie; use it (or X-Session-Token) against /v1/auth/portal/api-keys
# to create the actual X-API-Key used for every endpoint below.
```

**Billing:** `GET /v1/plans` lists the available tiers (Free/Starter/Pro/Business);
`POST /v1/billing/subscribe` with `{"plan_id": "starter", "interval": "month"}`
starts a Stripe Checkout session for a paid plan. The Free plan needs no card.

---

## 1. Test Connectivity

```bash
curl https://api.invoxapi.de/v1/health
# → {"status":"ok","service":"invox"}
```

No API key required for `/v1/health`.

---

## 2. Validate an Invoice

```bash
curl -X POST https://api.invoxapi.de/v1/validate \
  -H "X-API-Key: in_your32charkey_fl" \
  -F "file=@invoice.xml"
```

**Minimal Python example:**

```python
import httpx

with open("invoice.xml", "rb") as f:
    resp = httpx.post(
        "https://api.invoxapi.de/v1/validate",
        headers={"X-API-Key": "in_your32charkey_fl"},
        files={"file": ("invoice.xml", f, "application/xml")},
    )

result = resp.json()
print(result["verdict"])       # "valid" | "invalid" | "manual_review_required" | "validation_failed"
print(result["request_id"])    # UUID — store this for evidence retrieval
print(result["errors"])        # list of Violation objects
```

**Response fields:**

| Field | Type | Description |
|---|---|---|
| `request_id` | string | UUID identifying this validation run — store it |
| `verdict` | string | `valid` / `invalid` / `manual_review_required` / `validation_failed` |
| `format_detected` | string | e.g. `XRECHNUNG_3_UBL`, `ZUGFERD_2_EN16931` |
| `profile` | string | e.g. `XRechnung-3.0.2` |
| `rule_version` | string | Rule set version applied |
| `checksum_sha256` | string | SHA-256 of your document (for your own audit) |
| `errors` | array | Error-level violations — invoice is not compliant |
| `warnings` | array | Warning-level violations — review recommended |
| `autofix_candidates` | array | Violations where an automatic fix is suggested |
| `evidence_hash` | string | SHA-256 of the audit chain entry |

---

## 3. Understand Error Verdicts

### `invalid`
Your invoice has at least one error-level violation. The `errors` array contains structured
`Violation` objects:

```json
{
  "rule_id": "BR-DE-1",
  "severity": "error",
  "message": "Invoice number (BT-1) must be present.",
  "human_message": "Rechnungsnummer fehlt. Das Feld BT-1 muss ausgefüllt sein.",
  "bt_number": "BT-1",
  "xpath": "//cbc:ID",
  "auto_fix_possible": false
}
```

### `validation_failed`
The validation engine could not process the file. This is an infrastructure issue, not a
compliance result. Do not treat `validation_failed` as invalid. Retry once; if it persists,
write to support@invoxapi.de.

### `manual_review_required`
The format was ambiguous (e.g. the file could be either BASIC or EN16931 profile). A human
needs to decide. The file is structurally processable.

---

## 4. Get Human-Readable German Messages

The `/v1/validate` response already includes `human_message` on each violation. You can also
call `/v1/explain` to re-humanize violations you already have:

```bash
curl -X POST https://api.invoxapi.de/v1/explain \
  -H "X-API-Key: in_your32charkey_fl" \
  -H "Content-Type: application/json" \
  -d '{"violations": [{"rule_id":"BR-DE-1","severity":"error","message":"..."}]}'
```

---

## 5. Retrieve Evidence Records

Every validation produces an evidence record. Store the `request_id` from the validation response.

```bash
# Minimal manifest
curl -H "X-API-Key: in_your32charkey_fl" \
  https://api.invoxapi.de/v1/evidence/<request_id>

# Full record (errors, NOX decision, autofix candidates)
curl -H "X-API-Key: in_your32charkey_fl" \
  https://api.invoxapi.de/v1/evidence/<request_id>/full

# PDF evidence report (for auditors)
curl -H "X-API-Key: in_your32charkey_fl" \
  https://api.invoxapi.de/v1/evidence/<request_id>/report.pdf \
  -o evidence_report.pdf
```

Evidence records are tenant-isolated — your key can only access records created with your key.

---

## 6. Get Autofix Suggestions

```bash
curl -X POST https://api.invoxapi.de/v1/autofix \
  -H "X-API-Key: in_your32charkey_fl" \
  -F "file=@invoice.xml" \
  -F 'violations_json=[{"rule_id":"BR-DE-1","severity":"error","message":"..."}]' \
  -F "include_preview=false"
```

With `include_preview=true`, the response contains `patched_xml_preview_b64` — a base64-encoded
rough preview of the invoice with fixes applied. **This is a preview only — always re-validate
after applying fixes.** The preview is generated in RAM and never stored.

---

## 7. Generate Mail Templates

```bash
curl -X POST https://api.invoxapi.de/v1/mail/compose \
  -H "X-API-Key: in_your32charkey_fl" \
  -H "Content-Type: application/json" \
  -d '{
    "template": "supplier_correction_request",
    "context": {"invoice_number": "RE-2024-001", "error_summary": "IBAN fehlt (BT-84)"},
    "recipient_email": "lieferant@example.com",
    "sender_email": "buchhaltung@yourcompany.de"
  }'
```

Returns `subject`, `body`, `mailto_url` (for Outlook/Gmail), and `eml_base64` (downloadable `.eml`).

Available templates: `supplier_correction_request`, `customer_invoice_issue`, `internal_manual_review`

---

## 8. Rate Limits and Quotas

- **Rate limit:** 60 requests/minute per API key (sliding window)
- **Exceeded:** HTTP 429 `BLOCK_RATE_LIMIT`
- **Quota:** every plan includes a number of validations per month (`GET /v1/plans`).
  The Free plan stops at its limit (HTTP 402 `QUOTA_EXCEEDED`); paid plans continue
  with the published overage price until your monthly spend cap is reached
  (HTTP 402 `SPEND_CAP_REACHED`).
- **Check your usage:** `GET /v1/usage` and `GET /v1/quota`

---

## 9. Supported Formats

| Format | Verdict available | Notes |
|---|---|---|
| XRechnung 3.0.2 UBL | ✅ YES | KoSIT Schematron rules applied |
| XRechnung 3.0.2 CII | ✅ YES | KoSIT Schematron rules applied |
| EN16931 UBL / CII | ✅ YES | Python rules + KoSIT |
| ZUGFeRD 2.x (all profiles) | ⚠️ CONDITIONAL | Requires Mustang JAR on the server |
| Factur-X 1.x (all profiles) | ⚠️ CONDITIONAL | Requires Mustang JAR on the server |
| PEPPOL BIS 3 | ⚠️ PARTIAL | Rule IDs referenced; no dedicated Schematron |

If ZUGFeRD/Factur-X returns `validation_failed` with `VALIDATOR_UNAVAILABLE`, the PDF
validator is not available at that moment — please write to support@invoxapi.de.

---

## 10. Error Codes Reference

| HTTP | error_code | Meaning |
|---|---|---|
| 401 | `MISSING_API_KEY` | No `X-API-Key` header |
| 401 | `INVALID_API_KEY` | Wrong key format or unrecognised key |
| 400 | `BLOCK_REPLAY` | Duplicate nonce or stale timestamp |
| 400 | `BLOCK_FILENAME` | Path traversal in filename |
| 400 | `BLOCK_XXE` | XML entity expansion attempt detected |
| 400 | `BLOCK_BOMB` | PDF compression bomb detected |
| 409 | `DUPLICATE_INVOICE` | Same invoice number already submitted (dedup enabled) |
| 402 | `QUOTA_EXCEEDED` / `SPEND_CAP_REACHED` | Monthly plan limit or spend cap reached |
| 413 | `BLOCK_SIZE` | File exceeds 10 MB |
| 415 | `BLOCK_CONTENT_TYPE` | Content-Type not permitted |
| 415 | `BLOCK_MAGIC` | File type not recognised from content |
| 422 | `UNKNOWN_TEMPLATE` | Mail template name not found |
| 429 | `BLOCK_RATE_LIMIT` | Rate limit exceeded |
| 503 | `DEDUP_DISABLED` | Dedup feature not enabled on this instance |
| 503 | `FEATURE_DISABLED` | This function is temporarily switched off while a problem is fixed. **No result was produced** — never treat it as valid or invalid; retry later (`Retry-After`). Current state: `GET /v1/features` |
