# SDK de Python

`tomba-io` es el cliente oficial de Python para la [API de Tomba](/introduction). Cada área de la API es una clase de servicio, y cada método envía una solicitud.

## Requisitos

- Python 3.8 o posterior. El paquete no declara ninguna versión mínima; su CI prueba de Python 3.8 a 3.12.
- [`requests`](https://pypi.org/project/requests/), instalado como dependencia.

## Instalación

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

El nombre de importación es `tomba`.

## Autenticación

Crea una clave API y copia tu secreto en la página [API keys](https://app.tomba.io/api), y luego exporta ambos:

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

El SDK no lee variables de entorno. Pasa los valores a `set_key()` y `set_secret()`, y el cliente los envía como los encabezados `X-Tomba-Key` y `X-Tomba-Secret`. La caducidad y la rotación de las claves se explican en [Autenticación](/authentication).

## Primera solicitud

Busca la dirección de email de una persona en una empresa:

```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"])
```

Todos los métodos devuelven un dict con dos claves: `data`, el cuerpo JSON decodificado, y `rate_limit`. La API envuelve su payload en su propio objeto `data` ([Formato de respuesta](/introduction#response-format)), así que la dirección está en `result["data"]["data"]["email"]`.

## Errores

El SDK lanza `TombaException` cuando la API responde con un estado 400 o superior, cuando la solicitud falla y, antes de enviar una solicitud, cuando un argumento obligatorio es `None`.

| Atributo  | Valor                                                                                                  |
| ---------- | ------------------------------------------------------------------------------------------------------ |
| `code`     | El estado HTTP. `0` cuando no se recibió ninguna respuesta, por ejemplo por un argumento ausente o un error de red. |
| `message`  | El `errors.message` de la API, o el error subyacente.                                                   |
| `response` | El cuerpo del error decodificado, `{"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()` y `combined()` no lanzan excepciones cuando no se encuentra nada: esos endpoints responden con el estado 200 y un cuerpo `errors`, así que comprueba `result["data"].get("errors")`. Cada `errors.type` se describe en [Errores](/error-handling#error-types).

## Límites de solicitudes y reintentos

El SDK no reintenta. `result["rate_limit"]` contiene los [encabezados de límites de solicitudes](/rate-limits#rate-limit-headers) de la respuesta como `second_limit`, `minute_limit`, `daily_limit`, `minute_remaining`, `daily_remaining`, `minute_reset`, `daily_reset`, `retry_after`, `policy` y `rate_limit`. Los números son enteros, y un encabezado ausente o `0` se convierte en `None`.

Un `429` lanza `TombaException` con `code` 429, sin el encabezado `Retry-After`. Espera antes de reintentar como se describe en [Gestionar respuestas 429](/rate-limits#handle-429-responses).

Las solicitudes agotan el tiempo de espera a los 120 segundos. Cambia el tiempo de espera con `client.set_timeout(seconds)`.

## Referencia de métodos

Crea cada servicio con el cliente, por ejemplo `Finder(client)`. Todas las clases se pueden importar desde `tomba`. Los IDs son strings.

| Método                                                                                                                     | 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` es el segmento `{type}` que se enumera en [Tipos de trabajos masivos](/bulks#bulk-types); el orden de las llamadas se describe en [Ciclo de vida](/bulks#lifecycle). `create_bulk` envía un cuerpo JSON, así que no puede crear trabajos que requieren subir un CSV, como los trabajos de [Email Finder](/bulks#email-finder). `download_bulk` devuelve el archivo de resultados, un CSV, como bytes en `result["data"]`.

## Código fuente

[github.com/tomba-io/python](https://github.com/tomba-io/python) (Apache-2.0). Las notas de la versión están en [CHANGELOG.md](https://github.com/tomba-io/python/blob/master/CHANGELOG.md).
