Zum Inhalt springen

REST-API für Entwickler

Anleitung: Prüffehler verstehen und beheben

Feldfehler und verletzte Geschäftsregeln: wie Sie sie in der Antwort erkennen und die Anfrage korrigieren.

Inhalt

Ziel und Voraussetzungen

Die API meldet zwei Arten von Fehlern:

  • Feldfehler: Ein Feld fehlt oder hat einen ungültigen Wert. Die Rechnung wird nicht angelegt; die Antwort ist 400 mit den Feldern.
  • Geschäftsregeln: Die Felder sind gültig, aber die Rechnung verletzt eine Regel der EN 16931 oder der XRechnung, z. B. fehlt die USt-IdNr. des Verkäufers. Die Validatoren melden die Regel-ID, z. B. BR-CO-26.

Voraussetzungen: ein API-Schlüssel in der Umgebungsvariable API_KEY und invoice.json wie in Anleitung: erste E-Rechnung; curl und jq oder Python 3 mit requests.

1. Feldfehler lesen

Beispiel: das Rechnungsdatum in deutscher Schreibweise und die erste Position ohne Nettopreis:

invoice.json
{
  "issue_date": "01.10.2026",
  "items": [
    {
      "line_id": "1",
      "name": "Beratungsleistung",
      "quantity": "8",
      "unit_code": "HUR",
      "tax_category": "S",
      "tax_rate": "19.00"
    }
  ]
}
curl (Shell)
curl -sS -X POST "https://www.e-rechnungsfreund.de/api/v1/invoices/" \
  -H "Authorization: Api-Key $API_KEY" \
  -H "Content-Type: application/json" \
  -d @invoice.json
Python (requests)
import json
import os

import requests

BASE_URL = "https://www.e-rechnungsfreund.de"
HEADERS = {"Authorization": f"Api-Key {os.environ['API_KEY']}"}

with open("invoice.json", encoding="utf-8") as f:
    invoice = json.load(f)

response = requests.post(f"{BASE_URL}/api/v1/invoices/", json=invoice, headers=HEADERS, timeout=30)
if response.status_code == 400:
    problem = response.json()  # RFC 7807
    for error in problem.get("validation_errors", []):
        # "field" is the path in the request body, e.g. items.0.net_price
        print(f'{error.get("field", "(whole request)")}: {error["message"]}')
else:
    response.raise_for_status()
Beispielantwort: POST /api/v1/invoices/ → 400 Bad Request
JSON
{
  "type": "https://www.e-rechnungsfreund.de/api/errors/validationerror",
  "title": "ValidationError",
  "status": 400,
  "detail": "Invalid input.",
  "errors": {
    "issue_date": [
      "Date has wrong format. Use one of these formats instead: YYYY-MM-DD."
    ],
    "items": {
      "0": {
        "net_price": [
          "This field is required."
        ]
      }
    }
  },
  "validation_errors": [
    {
      "field": "issue_date",
      "message": "Date has wrong format. Use one of these formats instead: YYYY-MM-DD."
    },
    {
      "field": "items.0.net_price",
      "message": "This field is required."
    }
  ]
}
  • validation_errors ist eine flache Liste: field ist der Pfad im Anfragetext mit Punkten und Listenindizes (items.0.net_price = erste Position), message der Grund. Damit markieren Sie das Feld in Ihrem Formular.
  • errors enthält dieselben Meldungen, verschachtelt wie der Anfragetext.
  • Zeigen oder protokollieren Sie detail und message, werten Sie den Text aber nicht aus; er kann sich ändern.

2. Geschäftsregeln prüfen

POST /api/v1/invoices/validate_draft/ nimmt dieselben Daten wie das Anlegen einer Rechnung, erzeugt das XML, prüft es und speichert nichts. Der Aufruf zählt in kein Kontingent. Beispiel: invoice.json ohne die USt-IdNr. des Verkäufers:

invoice.json
{
  "seller": {
    "name": "Muster GmbH",
    "street": "Musterstraße 1",
    "postal_code": "10115",
    "city": "Berlin",
    "country_code": "DE",
    "contact_name": "Max Mustermann",
    "contact_phone": "+49 30 12345678",
    "contact_email": "rechnung@muster.example"
  }
}
curl (Shell)
curl -sS -X POST "https://www.e-rechnungsfreund.de/api/v1/invoices/validate_draft/" \
  -H "Authorization: Api-Key $API_KEY" \
  -H "Content-Type: application/json" \
  -d @invoice.json \
  | jq -r '[.kosit.errors[]?, .saxon.errors[]?] | map(.message? // .) | unique[]'
Python (requests)
import re

RULE_ID = re.compile(r"^\[([A-Za-z0-9-]+)\]")


def rule_errors(result):
    """Errors of all validators, one entry per rule: {rule ID: message}."""
    found = {}
    for validator in ("kosit", "saxon"):
        for error in (result.get(validator) or {}).get("errors", []):
            message = error["message"] if isinstance(error, dict) else str(error)
            match = RULE_ID.match(message)
            found.setdefault(match.group(1) if match else "?", message)
    return found


check = requests.post(f"{BASE_URL}/api/v1/invoices/validate_draft/", json=invoice, headers=HEADERS, timeout=120)
check.raise_for_status()  # 400 = field errors as in step 1
errors = rule_errors(check.json())
for rule_id, message in errors.items():
    print(rule_id, message)
Beispielantwort: POST /api/v1/invoices/validate_draft/ → 200 OK
JSON
{
  "kosit": {
    "is_valid": false,
    "applicable": true,
    "errors": [
      {
        "message": "[BR-S-02]-An Invoice that contains an Invoice line (BG-25) where the Invoiced item VAT category code (BT-151) is \"Standard rated\" shall contain the Seller VAT Identifier (BT-31), the Seller tax registration identifier (BT-32) and/or the Seller tax representative VAT identifier (BT-63).",
        "affected_codes": [
          "BG-25",
          "BT-151",
          "BT-31",
          "BT-32",
          "BT-63",
          "BR-S-02"
        ]
      },
      {
        "message": "[BR-CO-26]-In order for the buyer to automatically identify a supplier, the Seller identifier (BT-29), the Seller legal registration identifier (BT-30) and/or the Seller VAT identifier (BT-31) shall be present.",
        "affected_codes": [
          "BT-29",
          "BT-30",
          "BT-31",
          "BR-CO-26"
        ]
      }
    ],
    "warnings": [],
    "method": "daemon"
  },
  "saxon": {
    "is_valid": false,
    "errors": [
      {
        "message": "[BR-CO-26]-In order for the buyer to automatically identify a supplier, the Seller identifier (BT-29), the Seller legal registration identifier (BT-30) and/or the Seller VAT identifier (BT-31) shall be present.",
        "affected_codes": [
          "BT-29",
          "BT-30",
          "BT-31",
          "BR-CO-26"
        ]
      },
      {
        "message": "[BR-S-02]-An Invoice that contains an Invoice line (BG-25) where the Invoiced item VAT category code (BT-151) is \"Standard rated\" shall contain the Seller VAT Identifier (BT-31), the Seller tax registration identifier (BT-32) and/or the Seller tax representative VAT identifier (BT-63).",
        "affected_codes": [
          "BG-25",
          "BT-151",
          "BT-31",
          "BT-32",
          "BT-63",
          "BR-S-02"
        ]
      }
    ],
    "warnings": [],
    "method": "saxon (xslt 2.0)"
  }
}
  • Der Status ist auch bei verletzten Regeln 200; das Ergebnis steht in is_valid je Validator. Maßgeblich ist kosit; saxon prüft die Regeln der EN 16931 ein zweites Mal und fehlt bei der XRechnung.
  • Jede Meldung beginnt mit der Regel-ID in eckigen Klammern. Mehrere Validatoren können dieselbe Regel melden; fassen Sie die Meldungen nach Regel-ID zusammen.
  • affected_codes nennt die betroffenen Geschäftsbegriffe (BT-/BG-Nummern), z. B. BT-31 = USt-IdNr. des Verkäufers.

Dieselbe Prüfung läuft, wenn Sie die Datei mit POST /api/v1/invoices/{invoice_id}/generate_zugferd_pdf/ erzeugen. Findet sie dort Fehler, ist die Antwort 400 mit den Meldungen in details:

Beispielantwort: POST /api/v1/invoices/{invoice_id}/generate_zugferd_pdf/ → 400 Bad Request
JSON
{
  "type": "https://www.e-rechnungsfreund.de/api/errors/badrequest",
  "title": "BadRequest",
  "status": 400,
  "detail": "Validation failed",
  "details": [
    {
      "message": "[BR-S-02]-An Invoice that contains an Invoice line (BG-25) where the Invoiced item VAT category code (BT-151) is \"Standard rated\" shall contain the Seller VAT Identifier (BT-31), the Seller tax registration identifier (BT-32) and/or the Seller tax representative VAT identifier (BT-63).",
      "affected_codes": [
        "BG-25",
        "BT-151",
        "BT-31",
        "BT-32",
        "BT-63",
        "BR-S-02"
      ]
    },
    {
      "message": "[BR-CO-26]-In order for the buyer to automatically identify a supplier, the Seller identifier (BT-29), the Seller legal registration identifier (BT-30) and/or the Seller VAT identifier (BT-31) shall be present.",
      "affected_codes": [
        "BT-29",
        "BT-30",
        "BT-31",
        "BR-CO-26"
      ]
    }
  ]
}

3. Regel nachschlagen

GET /api/v1/validation-rules/BR-CO-26/ erklärt eine Regel: Bedeutung, typische Ursachen, Behebung und den Link zur Regelseite. Der Aufruf zählt in kein Kontingent. language (de oder en) wählt die Sprache. Ist zu einer Regel keine Erklärung veröffentlicht, ist explanation null und die Antwort enthält nur die offiziellen Meldungen.

curl (Shell)
curl -sS "https://www.e-rechnungsfreund.de/api/v1/validation-rules/BR-CO-26/?language=en" \
  -H "Authorization: Api-Key $API_KEY"
Python (requests)
for rule_id in errors:
    if rule_id == "?":
        continue  # message without rule ID
    rule = requests.get(
        f"{BASE_URL}/api/v1/validation-rules/{rule_id}/",
        params={"language": "en"},
        headers=HEADERS,
        timeout=30,
    )
    if rule.status_code == 404:
        continue  # unknown rule ID
    rule.raise_for_status()
    data = rule.json()
    explanation = data["explanation"] or {}  # null if no explanation is published
    print(rule_id, explanation.get("title", ""), data["rule_url"])
    for step in explanation.get("fix_general", []):
        print("  -", step)
Beispielantwort: GET /api/v1/validation-rules/BR-CO-26/ → 200 OK

Auszug: Die Erklärung ist gekürzt; die Antwort kann auch fix_in_app und Beispiele für falsches und richtiges XML enthalten.

JSON
{
  "rule_id": "BR-CO-26",
  "found": true,
  "severity": "error",
  "affected_terms": [
    "BT-29",
    "BT-30",
    "BT-31"
  ],
  "rule_url": "https://www.e-rechnungsfreund.de/en/validation-rules/br-co-26/",
  "official_messages": [
    {
      "source": "EN 16931 (CII)",
      "language": "en",
      "message": "In order for the buyer to automatically identify a supplier, the Seller identifier (BT-29), the Seller legal registration identifier (BT-30) and/or the Seller VAT identifier (BT-31) shall be present."
    }
  ],
  "explanation": {
    "language": "en",
    "title": "Seller identification is missing (BT-29, BT-30 or BT-31)",
    "summary": "In order for the buyer to automatically identify the supplier, the invoice shall contain at least one of the following for the seller: seller identifier (BT-29), seller legal registration identifier (BT-30) or seller VAT identifier (BT-31). None of them is present.",
    "causes": [
      "The fields for identifier, registration number and VAT identifier of the seller were left empty."
    ],
    "fix_general": [
      "State at least one of: VAT identifier (BT-31), trade register or other legal registration number (BT-30), or a seller identifier such as a GLN (BT-29)."
    ]
  }
}

Alle Regeln finden Sie auch unter Prüfregeln. Für vorhandene Dateien liefert POST /api/v1/validate/ mit include_explanations=true die Erklärungen zusammen mit dem Ergebnis.

4. Korrigieren und erneut senden

Hier braucht der Verkäufer eine USt-IdNr.: Ergänzen Sie "vat_id" in seller, prüfen Sie erneut und legen Sie dann die Rechnung an.

curl (Shell)
# after adding "vat_id" to "seller" in invoice.json
curl -sS -X POST "https://www.e-rechnungsfreund.de/api/v1/invoices/validate_draft/" \
  -H "Authorization: Api-Key $API_KEY" \
  -H "Content-Type: application/json" \
  -d @invoice.json \
  | jq '{kosit: .kosit.is_valid, saxon: .saxon.is_valid}'

curl -sS -X POST "https://www.e-rechnungsfreund.de/api/v1/invoices/" \
  -H "Authorization: Api-Key $API_KEY" \
  -H "Content-Type: application/json" \
  -d @invoice.json
Python (requests)
invoice["seller"]["vat_id"] = "DE123456789"

check = requests.post(f"{BASE_URL}/api/v1/invoices/validate_draft/", json=invoice, headers=HEADERS, timeout=120)
check.raise_for_status()
if rule_errors(check.json()):
    raise SystemExit("still invalid")

created = requests.post(f"{BASE_URL}/api/v1/invoices/", json=invoice, headers=HEADERS, timeout=30)
created.raise_for_status()
print("created", created.json()["id"])
Beispielantwort: POST /api/v1/invoices/validate_draft/ → 200 OK

Auszug: ein Ergebnis je Validator.

JSON
{
  "kosit": {
    "is_valid": true,
    "errors": [],
    "warnings": [],
    "method": "daemon",
    "applicable": true
  },
  "saxon": {
    "is_valid": true,
    "errors": [],
    "warnings": [],
    "method": "saxon (xslt 2.0)"
  }
}

Vollständiges Skript auf GitHub: check_invoice.sh, check_invoice.py

Nächste Schritte