# SDK Python

`tomba-io` è il client Python ufficiale per l'[API Tomba](/introduction). Ogni area dell'API è una classe di servizio, e ogni metodo invia una richiesta.

## Requisiti

- Python 3.8 o successivo. Il pacchetto non dichiara una versione minima; la sua CI testa Python da 3.8 a 3.12.
- [`requests`](https://pypi.org/project/requests/), installato come dipendenza.

## Installa

```bash
pip install tomba-io
```

Il nome da importare è `tomba`.

## Autenticati

Crea una chiave API e copia il tuo secret nella pagina [API keys](https://app.tomba.io/api), poi esportali entrambi:

```bash
export TOMBA_API_KEY="ta_xxxx"
export TOMBA_SECRET_KEY="ts_xxxx"
```

L'SDK non legge le variabili d'ambiente. Passa i valori a `set_key()` e `set_secret()`, e il client li invia come header `X-Tomba-Key` e `X-Tomba-Secret`. La scadenza e la rotazione delle chiavi sono trattate in [Autenticazione](/authentication).

## Prima richiesta

Trova l'indirizzo email di una persona in un'azienda:

```python
import os

from tomba import Client, Finder

client = Client()
client.set_key(os.environ["TOMBA_API_KEY"]).set_secret(os.environ["TOMBA_SECRET_KEY"])

result = Finder(client).email_finder("stripe.com", "Jane", "Doe")
print(result["data"]["data"]["email"])
```

Ogni metodo restituisce un dict con due chiavi: `data`, il corpo JSON decodificato, e `rate_limit`. L'API racchiude il payload in un proprio oggetto `data` ([Formato della risposta](/introduction#response-format)), quindi l'indirizzo si trova in `result["data"]["data"]["email"]`.

## Errori

L'SDK solleva `TombaException` quando l'API risponde con uno stato 400 o superiore, quando la richiesta non riesce e, prima di inviare una richiesta, quando un argomento obbligatorio è `None`.

| Attributo  | Valore                                                                                                  |
| ---------- | ------------------------------------------------------------------------------------------------------ |
| `code`     | Lo stato HTTP. `0` quando non è stata ricevuta alcuna risposta, ad esempio per un argomento mancante o un errore di rete. |
| `message`  | L'`errors.message` dell'API, o l'errore sottostante.                                                   |
| `response` | Il corpo dell'errore decodificato, `{"errors": {"type": …, "message": …, "code": …}}`, o `None`.                 |

```python
import os

from tomba import Client, Finder, TombaException

client = Client()
client.set_key(os.environ["TOMBA_API_KEY"]).set_secret(os.environ["TOMBA_SECRET_KEY"])

try:
    result = Finder(client).email_finder("stripe.com", "Jane", "Doe")
except TombaException as error:
    print(error.code, error.message)
    if error.response:
        print(error.response["errors"]["type"])
else:
    print(result["data"]["data"]["email"])
```

`Enrichment.person()`, `company()` e `combined()` non sollevano eccezioni quando non trovano nulla: questi endpoint rispondono con stato 200 e un corpo `errors`, quindi controlla `result["data"].get("errors")`. Ogni `errors.type` è descritto in [Errori](/error-handling#error-types).

## Limiti di frequenza e nuovi tentativi

L'SDK non riprova le richieste. `result["rate_limit"]` contiene gli [header dei limiti di frequenza](/rate-limits#rate-limit-headers) della risposta come `second_limit`, `minute_limit`, `daily_limit`, `minute_remaining`, `daily_remaining`, `minute_reset`, `daily_reset`, `retry_after`, `policy` e `rate_limit`. I numeri sono interi, e un header assente o pari a `0` diventa `None`.

Un `429` solleva `TombaException` con `code` 429, senza l'header `Retry-After`. Attendi prima di riprovare, come descritto in [Gestisci le risposte 429](/rate-limits#handle-429-responses).

Le richieste vanno in timeout dopo 120 secondi. Modifica il timeout con `client.set_timeout(seconds)`.

## Riferimento dei metodi

Crea ogni servizio con il client, ad esempio `Finder(client)`. Ogni classe si può importare da `tomba`. Gli ID sono stringhe.

| Metodo                                                                                                                     | Endpoint                                                                    |
| -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `Account.get_account()`                                                                                                    | [`GET /me`](/api/account#get-account)                                       |
| `Usage.get_usage()`                                                                                                        | [`GET /usage`](/api/account#retrieve-api-usage)                             |
| `Logs.get_logs(page=None, limit=None)`                                                                                     | [`GET /logs`](/api/account#retrieve-api-logs)                               |
| `Domain.domain_search(domain, page=None, limit=None, department=None, country=None, enrich_mobile=None, webhook_url=None)` | [`GET /domain-search`](/api/finder#domain-search)                           |
| `Finder.email_finder(domain, first_name, last_name, webhook_url=None)`                                                     | [`GET /email-finder`](/api/finder#email-finder)                             |
| `Finder.author_finder(url, webhook_url=None)`                                                                              | [`GET /author-finder`](/api/finder#author-finder)                           |
| `Finder.linkedin_finder(url)`                                                                                              | [`GET /linkedin`](/api/finder#linkedin-finder)                              |
| `Finder.enrichment(email, webhook_url=None)`                                                                               | [`GET /enrich`](/api/finder#email-enrichment)                               |
| `Finder.format(domain)`, `Format.email_format(domain)`                                                                     | [`GET /email-format`](/api/finder#email-format)                             |
| `Finder.location(domain)`, `Location.get_location(domain)`                                                                 | [`GET /location`](/api/finder#location)                                     |
| `Count.email_count(domain)`                                                                                                | [`GET /email-count`](/api/finder#email-count)                               |
| `Verifier.email_verifier(email, enrich_mobile=None, webhook_url=None)`                                                     | [`GET /email-verifier`](/api/verifier#email-verifier)                       |
| `Sources.email_sources(email)`                                                                                             | [`GET /email-sources`](/api/email#email-sources)                            |
| `Enrichment.person(email, webhook_url=None)`                                                                               | [`GET /people/find`](/api/enrichment#person-api)                            |
| `Enrichment.company(domain)`                                                                                               | [`GET /companies/find`](/api/enrichment#company-api)                        |
| `Enrichment.combined(email)`                                                                                               | [`GET /combined/find`](/api/enrichment#combined-api)                        |
| `Phone.finder(email=None, domain=None, linkedin=None, full=None, webhook_url=None)`                                        | [`GET /phone-finder`](/api/phone#phone-finder)                              |
| `Phone.validator(phone)`                                                                                                   | [`GET /phone-validator`](/api/phone#phone-validator)                        |
| `Status.domain_status(domain)`                                                                                             | [`GET /domain-status`](/api/domain#domain-status)                           |
| `Status.auto_complete(query)`                                                                                              | [`GET /domain-suggestions`](/api/domain-suggestions#get-domain-suggestions) |
| `Similar.websites(domain)`                                                                                                 | [`GET /similar`](/api/domain#similar)                                       |
| `Technology.list(domain)`                                                                                                  | [`GET /technology`](/api/domain#technology)                                 |
| `Reveal.search_companies(**params)`                                                                                        | [`POST /reveal/search`](/api/reveal#search-companies)                       |
| `Flag.list_flags(page=None, limit=None)`                                                                                   | [`GET /flag`](/api/flag#list-my-flags)                                      |
| `Keys.get_keys()`                                                                                                          | [`GET /keys`](/api/keys#retrieve-api-keys)                                  |
| `Keys.get_key(id)`                                                                                                         | [`GET /keys/{id}`](/api/keys#retrieve-a-single-api-key)                     |
| `Keys.create_key(**params)`                                                                                                | [`POST /keys`](/api/keys#create-an-api-key)                                 |
| `Keys.reset_key(id)`                                                                                                       | [`PUT /keys/{id}`](/api/keys#reset-an-api-key)                              |
| `Keys.delete_key(id)`                                                                                                      | [`DELETE /keys/{id}`](/api/keys#delete-an-api-key)                          |
| `Leads.list_leads(page=None, limit=None, domain=None)`                                                                     | [`GET /leads`](/api/leads#retrieve-leads)                                   |
| `Leads.get_lead(lead_id)`                                                                                                  | [`GET /leads/{id}`](/api/leads#retrieve-a-single-lead)                      |
| `Leads.create_lead(**params)`                                                                                              | [`POST /leads`](/api/leads#create-a-lead)                                   |
| `Leads.update_lead(lead_id, **params)`                                                                                     | [`PUT /leads/{id}`](/api/leads#update-a-lead)                               |
| `Leads.delete_lead(lead_id)`                                                                                               | [`DELETE /leads/{id}`](/api/leads#delete-a-lead)                            |
| `LeadsLists.get_lists()`                                                                                                   | [`GET /leads_lists`](/api/lead-lists#retrieve-leads-lists)                  |
| `LeadsLists.create_list(**params)`                                                                                         | [`POST /leads_lists`](/api/lead-lists#create-leads-list)                    |
| `LeadsLists.update_list_id(id, **params)`                                                                                  | [`PUT /leads_lists/{id}`](/api/lead-lists#update-leads-list)                |
| `LeadsLists.delete_list_id(id)`                                                                                            | [`DELETE /leads_lists/{id}`](/api/lead-lists#delete-leads-list)             |
| `LeadsAttributes.get_lead_attributes()`                                                                                    | [`GET /attributes`](/api/lead-attributes#retrieve-lead-attributes)          |
| `LeadsAttributes.create_lead_attribute(**params)`                                                                          | [`POST /attributes`](/api/lead-attributes#create-a-lead-attribute)          |
| `LeadsAttributes.update_lead_attribute(id, **params)`                                                                      | [`PUT /attributes/{id}`](/api/lead-attributes#update-a-lead-attribute)      |
| `LeadsAttributes.delete_lead_attribute(id)`                                                                                | [`DELETE /attributes/{id}`](/api/lead-attributes#delete-a-lead-attribute)   |
| `Bulk.list_bulks(bulk_type, page=None, limit=None)`                                                                        | [`GET /bulk/{type}`](/api/bulks)                                            |
| `Bulk.create_bulk(bulk_type, **params)`                                                                                    | [`POST /bulk/{type}`](/api/bulks)                                           |
| `Bulk.get_bulk(bulk_type, bulk_id)`                                                                                        | [`GET /bulk/{type}/{id}`](/api/bulks)                                       |
| `Bulk.launch_bulk(bulk_type, bulk_id)`                                                                                     | [`PUT /bulk/{type}/{id}`](/api/bulks)                                       |
| `Bulk.bulk_progress(bulk_type, bulk_id)`                                                                                   | [`GET /bulk/{type}/{id}/progress`](/api/bulks)                              |
| `Bulk.download_bulk(bulk_type, bulk_id)`                                                                                   | [`GET /bulk/{type}/{id}/download`](/api/bulks)                              |
| `Bulk.rename_bulk(bulk_type, bulk_id, name)`                                                                               | [`PUT /bulk/{type}/{id}/rename`](/api/bulks)                                |
| `Bulk.archive_bulk(bulk_type, bulk_id)`                                                                                    | [`DELETE /bulk/{type}/{id}/archive`](/api/bulks)                            |
| `Bulk.delete_bulk(bulk_type, bulk_id)`                                                                                     | [`DELETE /bulk/{type}/{id}/delete`](/api/bulks)                             |

`bulk_type` è il segmento `{type}` elencato in [Tipi di job in blocco](/bulks#bulk-types); l'ordine delle chiamate è descritto in [Ciclo di vita](/bulks#lifecycle). `create_bulk` invia un corpo JSON, quindi non può creare job che richiedono il caricamento di un file CSV, come i job [Email Finder](/bulks#email-finder). `download_bulk` restituisce il file dei risultati, un CSV, come byte in `result["data"]`.

## Codice sorgente

[github.com/tomba-io/python](https://github.com/tomba-io/python) (Apache-2.0). Le note di rilascio sono in [CHANGELOG.md](https://github.com/tomba-io/python/blob/master/CHANGELOG.md).
