# SDK Python (https://docs.getbeel.com/it/api/sdk-python)

Il client Python ufficiale, tipizzato, con una sola dipendenza (httpx).

`getbeel` copre tutta l'[API](/it/api/reference). Aggiunge un `Idempotency-Key` a ogni `POST` che lo supporta, riprova i limiti di frequenza e gli errori del server, lancia errori tipizzati, scorre le liste e verifica le firme dei webhook. Python 3.9+.

```bash
pip install getbeel
```

## Crea e invia una fattura [#crea-e-invia-una-fattura]

```python
from getbeel import Getbeel

client = Getbeel()  # legge GETBEEL_API_KEY; oppure Getbeel(api_key="gb_test_...")

bozza = client.invoices.create(
    tipo_documento="TD01",
    currency="EUR",
    customer={
        "denominazione": "Bianchi S.p.A.",
        "partita_iva": "01234567890",
        "country": "IT",
        "codice_destinatario": "ABCDE12",
    },
    lines=[{"description": "Consulenza, ottobre", "quantity": "1", "unit_price": "1000.00", "vat_rate": "22.00"}],
)

inviata = client.invoices.send(bozza["id"])  # mostra la bozza e chiedi l'OK prima
```

Le risposte sono dizionari con i campi del [riferimento API](/it/api/reference). I corpi si passano come dizionario, come argomenti con nome o in entrambi i modi. Il parametro `from` si scrive `from_`.

Opzioni: `Getbeel(api_key=None, base_url=None, company=None, timeout=60.0, max_retries=2, http_client=None)`; `base_url` predefinito: `GETBEEL_BASE_URL`, poi `https://www.getbeel.com/api/v1`.

## Risorse [#risorse]

`me()`, `invoices`, `recurring_invoices`, `received_invoices`, `bank_statements` (`upload` accetta un percorso, dei byte o un file), `bank_transactions`, `reconciliations`, `unmatched`, `bank_connections`, `connections`, `companies`, `taxes` (`calendar`, `calendar_ics`, `vat_position`, `vat_registers`, `vat_settlement`, `report`, `accountant_export`), `filings` (`prepare`, `list`, `get`, `file`, `upload_receipt`). I nomi dei metodi sono quelli dell'[SDK TypeScript](/it/api/sdk-typescript) in snake_case.

## Idempotenza ed errori [#idempotenza-ed-errori]

```python
from getbeel import GetbeelError, NotFoundError

client.invoices.send(bozza["id"], idempotency_key=f"send-{bozza['id']}")

try:
    client.invoices.get("inesistente")
except NotFoundError as e:
    print(e.code, e.message)
except GetbeelError as e:
    print(e.status, e.type, e.code, e.param, e.request_id)
```

Ogni `POST` che supporta l'idempotenza riceve un `Idempotency-Key` casuale, lo stesso nei nuovi tentativi automatici e riportato in `e.idempotency_key` se fallisce. Quei `POST` e le letture vengono riprovati `max_retries` volte su `408`, `429` (dopo `Retry-After`), `5xx`, errori di rete e `409 idempotency_key_in_use`; gli altri `POST` solo su `429`. Sottoclassi: `InvalidRequestError`, `AuthenticationError`, `PermissionDeniedError`, `NotFoundError`, `ConflictError`, `RateLimitError`, `APIError`, `APIConnectionError`.

## Paginazione e aziende clienti [#paginazione-e-aziende-clienti]

```python
for fattura in client.invoices.iter_all(status="delivered"):
    print(fattura["number"])

bianchi = client.with_company("COMPANY_ID")  # header Getbeel-Company
bianchi.invoices.list()
```

## Webhook [#webhook]

```python
from getbeel import webhooks, WebhookSignatureError

try:
    event = webhooks.construct_event(corpo_grezzo, headers["Getbeel-Signature"], os.environ["GETBEEL_WEBHOOK_SECRET"])
except WebhookSignatureError:
    ...  # rispondi 400
```

`webhooks.verify(payload, header, secret)` restituisce `True` o `False`; le firme più vecchie di 5 minuti sono rifiutate. Vedi [Webhook](/it/api/webhooks).
