# 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` header on every request (except the no-account demo below). Keys you create in the dashboard look like `in_sub<16 hex>_fl`; the dashboard's own session key looks like `in_<32 chars>_fl`.  
**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 and the explicit acceptance of AGB and AVV.
A VAT ID (`vat_id`) or German tax number (`tax_number`) is **optional on the Free
plan**; if you send one it is verified (format, VIES, duplicate check). It becomes
mandatory before your first paid booking:

```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",
    "agb_accepted": true,
    "avv_accepted": true
  }'
```

`agb_accepted`/`avv_accepted` are a hard gate — no account is created without
both. You then receive a confirmation e-mail (link valid 24 h, single use); login
answers 403 `EMAIL_NOT_VERIFIED` until the link is opened. Then log in to get a
session and create your first API key (fastest: dashboard → *Start* → step 1,
the key is inserted into every code example there):

```bash
# 1) Log in — -c stores the session cookie in the cookie jar cookies.txt
curl -c cookies.txt -X POST https://api.invoxapi.de/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "you@example.com", "password": "..."}'
# 2) Create the API key — -b sends the session cookie from cookies.txt
curl -b cookies.txt -X POST https://api.invoxapi.de/v1/auth/portal/api-keys
# → {"key_id": 1, "api_key": "in_…_fl", "prefix": "…"} — api_key is shown ONCE
# 3) Use it for every endpoint below
export INVOX_API_KEY="<api_key from step 2>"
```

The free quota is counted per calendar month. When it is used up, the API
answers `402 QUOTA_EXCEEDED` with `"period": "monthly"` and an `upgrade_url`
(dashboard → *Abrechnung*); plans and prices: https://invoxapi.de/e-invoicing/de/preise

**Billing:** `GET /v1/plans` lists the available tiers (`free`, `starter`, `professional`, `business`, `oem`; Enterprise on request);
`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
export INVOX_API_KEY="<Ihr Schlüssel aus dem Dashboard>"   # einmal je Terminal
curl -O https://invoxapi.de/dashboard/rechnung-beispiel.xml
curl -X POST https://api.invoxapi.de/v1/validate \
  -H "X-API-Key: $INVOX_API_KEY" \
  -F "file=@rechnung-beispiel.xml"
```

The dashboard (*Start* and *Entwickler → Schlüssel*) shows this call with your key
already inserted, in curl, Python, JavaScript, PHP, C# and Java.

**Minimal Python example:**

```python
import os
import httpx

with open("rechnung-beispiel.xml", "rb") as f:
    resp = httpx.post(
        "https://api.invoxapi.de/v1/validate",
        headers={"X-API-Key": os.environ["INVOX_API_KEY"]},
        files={"file": ("rechnung-beispiel.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` (empty for some `invalid` results); the exact rule set is in `ruleset_version`, e.g. `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-15",
  "severity": "error",
  "message": "[BR-DE-15] Das Element \"Buyer reference\" (BT-10) muss übermittelt werden.",
  "human_message": "Die Käuferreferenz (BT-10) fehlt. XRechnung verlangt sie in jeder Rechnung: …",
  "fix_hint": "Fragen Sie Ihren Rechnungsempfänger nach dem richtigen Wert: …",
  "bt_number": "BT-10",
  "xpath": null,
  "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: $INVOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"violations": [{"rule_id":"BR-DE-15","severity":"error","message":"..."}]}'
```

---

## 5. Retrieve Evidence Records

Every validation with a production key produces an evidence record (sandbox keys produce none). Store the `request_id` from the validation response.

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

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

# PDF evidence report (for auditors)
curl -H "X-API-Key: $INVOX_API_KEY" \
  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?include_preview=false" \
  -H "X-API-Key: $INVOX_API_KEY" \
  -F "file=@invoice.xml" \
  -F 'violations_json=[{"rule_id":"BR-DE-15","severity":"error","message":"..."}]'
```

`include_preview` is a **query parameter** (a form field of that name is ignored). 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: $INVOX_API_KEY" \
  -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`
- **Headers on `POST /v1/validate`:** `X-RateLimit-Limit`, `X-RateLimit-Remaining` (rest of
  the current minute) and `X-Quota-Remaining` (credits left this month; absent on unlimited plans)
- **Quota:** every plan includes a number of standard checks per month (`GET /v1/plans`,
  `included_standard_checks`; 1 standard check = `credits_per_standard_check` = 5 credits,
  a PDF check counts 3).
  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 |
| 402 | `PLAN_UPGRADE_REQUIRED` | Function not part of your plan (e.g. `/v1/validate/batch` from Professional) |
| 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` |
