# SDK de R

El paquete `tomba` es el cliente oficial de R para la [API de Tomba](/introduction). Cada función recibe un objeto cliente `Tomba` y envía una solicitud. Esta página describe la versión 1.1.0, que está disponible en GitHub.

## Requisitos

- R 3.5.0 o posterior, tal como se declara en `DESCRIPTION`.
- Los paquetes `httr` y `jsonlite`, instalados como dependencias.

## Instalación

```r
install.packages("remotes")
remotes::install_github("tomba-io/r")
```

CRAN tiene la versión 1.0.1. Solo incluye `account`, `autocomplete`, `count`, `domain_search`, `email_finder`, `email_sources`, `email_verifier`, `logs`, `status` y `usage`, y estas funciones devuelven directamente el cuerpo de la respuesta, sin el envoltorio de `data` y `rate_limit` que se describe más abajo.

## 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 o establécelos en `~/.Renviron`:

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

El paquete no lee variables de entorno por sí mismo. Pasa los valores como `Tomba(key = ..., 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:

```r
library(tomba)

client <- Tomba(key = Sys.getenv("TOMBA_API_KEY"), secret = Sys.getenv("TOMBA_SECRET_KEY"))

result <- email_finder(client, domain = "stripe.com", fname = "Jane", lname = "Doe")
print(result$data$data$email)
```

Todas las funciones devuelven una lista con dos elementos: `data`, el cuerpo de la respuesta analizado con `jsonlite::fromJSON`, 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

Cuando la API responde con un estado 400 o superior, la función señala un error de R cuyo mensaje es `Tomba API error <status>: <response body>`. Captúralo con `tryCatch`:

```r
library(tomba)

client <- Tomba(key = Sys.getenv("TOMBA_API_KEY"), secret = Sys.getenv("TOMBA_SECRET_KEY"))

result <- tryCatch(
  email_finder(client, domain = "stripe.com", fname = "Jane", lname = "Doe"),
  error = function(e) {
    message(conditionMessage(e))
    NULL
  }
)
if (!is.null(result)) print(result$data$data$email)
```

El cuerpo de la respuesta del mensaje es el error JSON, `{"errors":{"type":…,"message":…,"code":…}}`. Cada `errors.type` se describe en [Errores](/error-handling#error-types). `person_find`, `company_find` y `combined_find` no señalan ningún error cuando no se encuentra nada: esos endpoints responden con el estado 200 y un cuerpo `errors`, así que comprueba `result$data$errors`.

## Límites de solicitudes y reintentos

El paquete no reintenta. `result$rate_limit` es una lista con nombres de los [encabezados de límites de solicitudes](/rate-limits#rate-limit-headers) de la respuesta que estén presentes, con valores de tipo carácter: `x-second-rate-limit`, `x-minute-rate-limit`, `x-daily-rate-limit`, `x-minute-request-left`, `x-daily-request-left`, `x-minute-reset-seconds`, `x-daily-reset-seconds`, `retry-after`, `ratelimit-policy` y `ratelimit`.

Un `429` señala un error sin los encabezados de la respuesta. 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; el tiempo de espera no se puede configurar.

## Referencia de métodos

Todas las funciones reciben el cliente como `obj`, su primer argumento.

| Función                                                               | Endpoint                                                                    |
| ---------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `account(obj)`                                                         | [`GET /me`](/api/account#get-account)                                       |
| `usage(obj)`                                                           | [`GET /usage`](/api/account#retrieve-api-usage)                             |
| `logs(obj, page = NULL, limit = NULL)`                                 | [`GET /logs`](/api/account#retrieve-api-logs)                               |
| `domain_search(obj, domain, enrich_mobile = NULL, webhook_url = NULL)` | [`GET /domain-search`](/api/finder#domain-search)                           |
| `email_finder(obj, domain, fname, lname, webhook_url = NULL)`          | [`GET /email-finder`](/api/finder#email-finder)                             |
| `author_finder(obj, url, webhook_url = NULL)`                          | [`GET /author-finder`](/api/finder#author-finder)                           |
| `linkedin_finder(obj, url, webhook_url = NULL)`                        | [`GET /linkedin`](/api/finder#linkedin-finder)                              |
| `email_format(obj, domain)`                                            | [`GET /email-format`](/api/finder#email-format)                             |
| `get_location(obj, domain)`                                            | [`GET /location`](/api/finder#location)                                     |
| `count(obj, domain)`                                                   | [`GET /email-count`](/api/finder#email-count)                               |
| `email_verifier(obj, email, webhook_url = NULL)`                       | [`GET /email-verifier`](/api/verifier#email-verifier)                       |
| `email_sources(obj, email)`                                            | [`GET /email-sources`](/api/email#email-sources)                            |
| `person_find(obj, email)`                                              | [`GET /people/find`](/api/enrichment#person-api)                            |
| `company_find(obj, domain)`                                            | [`GET /companies/find`](/api/enrichment#company-api)                        |
| `combined_find(obj, email)`                                            | [`GET /combined/find`](/api/enrichment#combined-api)                        |
| `phone_finder(obj, email, webhook_url = NULL)`                         | [`GET /phone-finder`](/api/phone#phone-finder)                              |
| `phone_validator(obj, phone, country_code = NULL)`                     | [`GET /phone-validator`](/api/phone#phone-validator)                        |
| `status(obj, domain)`                                                  | [`GET /domain-status`](/api/domain#domain-status)                           |
| `autocomplete(obj, search)`                                            | [`GET /domain-suggestions`](/api/domain-suggestions#get-domain-suggestions) |
| `similar_domains(obj, domain)`                                         | [`GET /similar`](/api/domain#similar)                                       |
| `technology_check(obj, domain)`                                        | [`GET /technology`](/api/domain#technology)                                 |
| `companies_search(obj, data = list())`                                 | [`POST /reveal/search`](/api/reveal#search-companies)                       |
| `list_flags(obj, page = NULL, limit = NULL)`                           | [`GET /flag`](/api/flag#list-my-flags)                                      |
| `list_keys(obj)`                                                       | [`GET /keys`](/api/keys#retrieve-api-keys)                                  |
| `get_key(obj, id)`                                                     | [`GET /keys/{id}`](/api/keys#retrieve-a-single-api-key)                     |
| `create_key(obj, data = list())`                                       | [`POST /keys`](/api/keys#create-an-api-key)                                 |
| `reset_key(obj, id)`                                                   | [`PUT /keys/{id}`](/api/keys#reset-an-api-key)                              |
| `delete_key(obj, id)`                                                  | [`DELETE /keys/{id}`](/api/keys#delete-an-api-key)                          |
| `list_leads(obj, page = NULL, limit = NULL, domain = NULL)`            | [`GET /leads`](/api/leads#retrieve-leads)                                   |
| `get_lead(obj, lead_id)`                                               | [`GET /leads/{id}`](/api/leads#retrieve-a-single-lead)                      |
| `create_lead(obj, data = list())`                                      | [`POST /leads`](/api/leads#create-a-lead)                                   |
| `update_lead(obj, lead_id, data = list())`                             | [`PUT /leads/{id}`](/api/leads#update-a-lead)                               |
| `delete_lead(obj, lead_id)`                                            | [`DELETE /leads/{id}`](/api/leads#delete-a-lead)                            |
| `list_leads_lists(obj)`                                                | [`GET /leads_lists`](/api/lead-lists#retrieve-leads-lists)                  |
| `create_leads_list(obj, data = list())`                                | [`POST /leads_lists`](/api/lead-lists#create-leads-list)                    |
| `update_leads_list(obj, id, data = list())`                            | [`PUT /leads_lists/{id}`](/api/lead-lists#update-leads-list)                |
| `delete_leads_list(obj, id)`                                           | [`DELETE /leads_lists/{id}`](/api/lead-lists#delete-leads-list)             |
| `list_lead_attributes(obj)`                                            | [`GET /attributes`](/api/lead-attributes#retrieve-lead-attributes)          |
| `create_lead_attribute(obj, data = list())`                            | [`POST /attributes`](/api/lead-attributes#create-a-lead-attribute)          |
| `update_lead_attribute(obj, id, data = list())`                        | [`PUT /attributes/{id}`](/api/lead-attributes#update-a-lead-attribute)      |
| `delete_lead_attribute(obj, id)`                                       | [`DELETE /attributes/{id}`](/api/lead-attributes#delete-a-lead-attribute)   |
| `list_bulks(obj, bulk_type, page = NULL, limit = NULL)`                | [`GET /bulk/{type}`](/api/bulks)                                            |
| `create_bulk(obj, bulk_type, data = list())`                           | [`POST /bulk/{type}`](/api/bulks)                                           |
| `get_bulk(obj, bulk_type, bulk_id)`                                    | [`GET /bulk/{type}/{id}`](/api/bulks)                                       |
| `launch_bulk(obj, bulk_type, bulk_id)`                                 | [`PUT /bulk/{type}/{id}`](/api/bulks)                                       |
| `bulk_progress(obj, bulk_type, bulk_id)`                               | [`GET /bulk/{type}/{id}/progress`](/api/bulks)                              |
| `rename_bulk(obj, bulk_type, bulk_id, name)`                           | [`PUT /bulk/{type}/{id}/rename`](/api/bulks)                                |
| `archive_bulk(obj, bulk_type, bulk_id)`                                | [`DELETE /bulk/{type}/{id}/archive`](/api/bulks)                            |
| `delete_bulk(obj, 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).

## Código fuente

[github.com/tomba-io/r](https://github.com/tomba-io/r) (Apache-2.0).
