Files
zugferd-service/src/main.py
T
m3ta-chironandClaude Fable 5.2 4ff994a299 feat(logging): honor the LOG_LEVEL environment variable
LOG_LEVEL was documented but never read; the level was fixed at INFO.
The JSON handler now sits on the "src" package logger so all service
modules share format and level. Invalid values fall back to INFO.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 18:32:58 +01:00

200 lines
5.5 KiB
Python

"""FastAPI application for ZUGFeRD invoice processing."""
import argparse
import base64
import json
import logging
import os
from datetime import datetime
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from src.extractor import ExtractionError, extract_from_xml, extract_invoice
from src.models import (
ExtractRequest,
ExtractResponse,
HealthResponse,
ValidateRequest,
ValidateResponse,
)
from src.validator import validate_invoice
class JSONFormatter(logging.Formatter):
def format(self, record):
log_data = {
"timestamp": datetime.utcnow().isoformat() + "Z",
"level": record.levelname,
"message": record.getMessage(),
}
if hasattr(record, "data"):
log_data["data"] = record.data
return json.dumps(log_data)
def get_log_level() -> str:
"""Read the log level from the LOG_LEVEL environment variable.
Returns:
Upper-case level name; 'INFO' when unset or not a valid level
"""
level = os.environ.get("LOG_LEVEL", "INFO").strip().upper()
if level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
return "INFO"
return level
def configure_logging() -> None:
"""Attach the JSON handler to the 'src' package logger and set its level.
Configuring the package logger makes all service modules (extractor,
validator, ...) log in the same format and at the same level.
"""
package_logger = logging.getLogger("src")
if not package_logger.handlers:
handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())
package_logger.addHandler(handler)
package_logger.setLevel(get_log_level())
# Fixed name: __name__ is '__main__' when started via `python -m src.main`
logger = logging.getLogger("src.main")
configure_logging()
app = FastAPI(
title="ZUGFeRD Service",
version="1.0.0",
description="REST API for ZUGFeRD invoice extraction and validation",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.exception_handler(ExtractionError)
async def extraction_error_handler(request: Request, exc: ExtractionError):
return JSONResponse(
status_code=400,
content={
"error": exc.error_code,
"message": exc.message,
"details": exc.details,
},
)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
if isinstance(exc.detail, dict) and "error" in exc.detail:
return JSONResponse(
status_code=exc.status_code,
content={
"error": exc.detail.get("error"),
"message": exc.detail.get("message"),
},
)
return JSONResponse(
status_code=exc.status_code,
content={
"error": "http_error",
"message": str(exc.detail),
},
)
@app.exception_handler(Exception)
async def generic_error_handler(request: Request, exc: Exception):
logger.error(f"Internal error: {exc}")
return JSONResponse(
status_code=500,
content={
"error": "internal_error",
"message": "An internal error occurred",
},
)
@app.get("/health", response_model=HealthResponse)
async def health_check() -> HealthResponse:
"""Health check endpoint.
Returns:
HealthResponse with status and version.
"""
return HealthResponse(status="healthy", version="1.0.0")
@app.post("/extract", response_model=ExtractResponse)
async def extract_pdf(request: ExtractRequest) -> ExtractResponse:
"""Extract e-invoice data from a PDF or a plain invoice XML.
Args:
request: ExtractRequest with pdf_base64 or xml_base64 field
Returns:
ExtractResponse with extraction results
"""
try:
file_bytes = base64.b64decode(request.xml_base64 or request.pdf_base64 or "")
except Exception:
raise HTTPException(
status_code=400,
detail={"error": "invalid_base64", "message": "Invalid base64 encoding"},
)
if request.xml_base64 is not None:
return extract_from_xml(file_bytes)
return extract_invoice(file_bytes)
@app.post("/validate", response_model=ValidateResponse)
async def validate_invoice_endpoint(request: ValidateRequest) -> ValidateResponse:
"""Validate ZUGFeRD invoice data.
Args:
request: ValidateRequest with xml_data, pdf_text, checks
Returns:
ValidateResponse with validation results
"""
result = validate_invoice(request)
return ValidateResponse(result=result)
def run(host: str = "0.0.0.0", port: int = 5000) -> None:
"""Run the FastAPI application.
Priority: CLI args > env vars > defaults
Args:
host: Host to bind to (default from env HOST or 0.0.0.0).
port: Port to listen on (default from env PORT or 5000).
"""
parser = argparse.ArgumentParser(description="ZUGFeRD REST API Service")
parser.add_argument(
"--host",
default=os.environ.get("HOST", host),
help="Host to bind to (default: 0.0.0.0)",
)
parser.add_argument(
"--port",
type=int,
default=int(os.environ.get("PORT", port)),
help="Port to listen on (default: 5000)",
)
args = parser.parse_args()
uvicorn.run(
app, host=args.host, port=args.port, log_level=get_log_level().lower()
)