# SDK Lua

Il rock `tomba` è il client Lua ufficiale per l'[API Tomba](/introduction). Tutti i metodi sono su un unico oggetto client, e ogni metodo invia una richiesta.

## Requisiti

- Lua 5.1, 5.2 o 5.3. Il rockspec consente Lua 5.1 o successivo, ma il rock `xml` da cui dipende `lua-requests` richiede una versione precedente alla 5.4.
- [LuaRocks](https://luarocks.org/) e un compilatore C++, per compilare le dipendenze `lua-requests` e `lua-cjson`.

## Installa

```bash
luarocks install xml CFLAGS="-O2 -fPIC -std=gnu++14"
luarocks install tomba
```

Il primo comando compila il rock `xml` in modalità C++14. Senza di esso, `luarocks install tomba` non riesce con i compilatori che usano C++17 per impostazione predefinita, come GCC 11 e successivi, perché `xml` non compila come C++17.

## 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 `Tomba:init(key, secret)`, e il client li invia come header `X-Tomba-Key` e `X-Tomba-Secret`. `init` genera un errore se uno dei due valori è più corto di 39 caratteri. La scadenza e la rotazione delle chiavi sono trattate in [Autenticazione](/authentication).

## Prima richiesta

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

```lua
local Tomba = require("tomba")

local tomba = Tomba:init(os.getenv("TOMBA_API_KEY"), os.getenv("TOMBA_SECRET_KEY"))

local result = tomba:email_finder("stripe.com", "Jane", "Doe")
print(result.data.data.email)
```

Ogni metodo restituisce una tabella con due campi: `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`. I valori JSON `null` vengono decodificati come `cjson.null`.

## Errori

Il modo in cui si manifesta un errore dipende dal metodo HTTP:

- I metodi `GET` generano un errore Lua quando lo stato non è 200. Il messaggio di errore è il corpo grezzo della risposta, preceduto dal file e dal numero di riga dell'SDK.
- I metodi `POST`, `PUT` e `DELETE` non generano errori per gli errori dell'API. Restituiscono la tabella del risultato con qualsiasi stato, quindi controlla `result.data.errors`.

Intercetta gli errori dei metodi `GET` con `pcall` e decodifica il corpo:

```lua
local Tomba = require("tomba")
local cjson = require("cjson")

local tomba = Tomba:init(os.getenv("TOMBA_API_KEY"), os.getenv("TOMBA_SECRET_KEY"))

local ok, result = pcall(tomba.email_finder, tomba, "stripe.com", "Jane", "Doe")
if ok then
    print(result.data.data.email)
else
    -- The error message is the response body, prefixed with the SDK's file and line.
    local decoded, body = pcall(cjson.decode, tostring(result):match("{.*") or "")
    if decoded and type(body) == "table" and body.errors then
        print(body.errors.code, body.errors.type, body.errors.message)
    else
        print(result)
    end
end
```

`errors.code` è lo stato HTTP. 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) presenti nella risposta, indicizzati per nome dell'header, con valori stringa: `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` e `ratelimit`.

Un `429` su un metodo `GET` genera un errore senza gli header della risposta. Attendi prima di riprovare, come descritto in [Gestisci le risposte 429](/rate-limits#handle-429-responses).

Le richieste vanno in timeout dopo 120 secondi; il timeout non è configurabile.

## Riferimento dei metodi

Chiama ogni metodo sul client con i due punti, ad esempio `tomba:email_finder(...)`. `opts` è una tabella facoltativa.

| Metodo                                                                          | Endpoint                                                                        |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `account()`                                                                     | [`GET /me`](/api/account#get-account)                                           |
| `usage()`                                                                       | [`GET /usage`](/api/account#retrieve-api-usage)                                 |
| `logs(params)`                                                                  | [`GET /logs`](/api/account#retrieve-api-logs)                                   |
| `domain_search(domain, opts)`, con `opts.enrich_mobile` e `opts.webhook_url` | [`GET /domain-search`](/api/finder#domain-search)                               |
| `email_finder(domain, first_name, last_name, opts)`, con `opts.webhook_url`    | [`GET /email-finder`](/api/finder#email-finder)                                 |
| `author_finder(url, opts)`                                                      | [`GET /author-finder`](/api/finder#author-finder)                               |
| `linkedin_finder(url, opts)`                                                    | [`GET /linkedin`](/api/finder#linkedin-finder)                                  |
| `enrichment(email, opts)`                                                       | [`GET /enrich`](/api/finder#email-enrichment)                                   |
| `email_format(domain)`                                                          | [`GET /email-format`](/api/finder#email-format)                                 |
| `get_location(domain)`                                                          | [`GET /location`](/api/finder#location)                                         |
| `count(domain)`                                                                 | [`GET /email-count`](/api/finder#email-count)                                   |
| `email_verifier(email, opts)`                                                   | [`GET /email-verifier`](/api/verifier#email-verifier)                           |
| `email_sources(email)`                                                          | [`GET /email-sources`](/api/email#email-sources)                                |
| `person_find(email)`                                                            | [`GET /people/find`](/api/enrichment#person-api)                                |
| `company_find(domain)`                                                          | [`GET /companies/find`](/api/enrichment#company-api)                            |
| `combined_find(email)`                                                          | [`GET /combined/find`](/api/enrichment#combined-api)                            |
| `phone_finder(params)`                                                          | [`GET /phone-finder`](/api/phone#phone-finder)                                  |
| `phone_validator(phone, country_code)`                                          | [`GET /phone-validator`](/api/phone#phone-validator)                            |
| `status(domain)`                                                                | [`GET /domain-status`](/api/domain#domain-status)                               |
| `autocomplete(search)`                                                          | [`GET /domain-suggestions`](/api/domain-suggestions#get-domain-suggestions)     |
| `similar(domain)`                                                               | [`GET /similar`](/api/domain#similar)                                           |
| `technology(domain)`                                                            | [`GET /technology`](/api/domain#technology)                                     |
| `companies_search(body)`                                                        | [`POST /reveal/search`](/api/reveal#search-companies)                           |
| `list_flags(params)`                                                            | [`GET /flag`](/api/flag#list-my-flags)                                          |
| `create_flag(body)`                                                             | [`POST /flag`](/api/flag#flag-incorrect-data)                                   |
| `list_keys()`                                                                   | [`GET /keys`](/api/keys#retrieve-api-keys)                                      |
| `get_key(key_id)`                                                               | [`GET /keys/{id}`](/api/keys#retrieve-a-single-api-key)                         |
| `create_key()`                                                                  | [`POST /keys`](/api/keys#create-an-api-key)                                     |
| `reset_key(key_id)`                                                             | [`PUT /keys/{id}`](/api/keys#reset-an-api-key)                                  |
| `delete_key(key_id)`                                                            | [`DELETE /keys/{id}`](/api/keys#delete-an-api-key)                              |
| `list_leads(params)`                                                            | [`GET /leads`](/api/leads#retrieve-leads)                                       |
| `get_lead(lead_id)`                                                             | [`GET /leads/{id}`](/api/leads#retrieve-a-single-lead)                          |
| `create_lead(body)`                                                             | [`POST /leads`](/api/leads#create-a-lead)                                       |
| `update_lead(lead_id, body)`                                                    | [`PUT /leads/{id}`](/api/leads#update-a-lead)                                   |
| `delete_lead(lead_id)`                                                          | [`DELETE /leads/{id}`](/api/leads#delete-a-lead)                                |
| `list_leads_lists()`                                                            | [`GET /leads_lists`](/api/lead-lists#retrieve-leads-lists)                      |
| `get_leads_list(list_id)`                                                       | [`GET /leads_lists/{id}`](/api/lead-lists#retrieve-a-single-leads-list)         |
| `create_leads_list(body)`                                                       | [`POST /leads_lists`](/api/lead-lists#create-leads-list)                        |
| `update_leads_list(list_id, body)`                                              | [`PUT /leads_lists/{id}`](/api/lead-lists#update-leads-list)                    |
| `delete_leads_list(list_id)`                                                    | [`DELETE /leads_lists/{id}`](/api/lead-lists#delete-leads-list)                 |
| `list_attributes()`                                                             | [`GET /attributes`](/api/lead-attributes#retrieve-lead-attributes)              |
| `get_attribute(attribute_id)`                                                   | [`GET /attributes/{id}`](/api/lead-attributes#retrieve-a-single-lead-attribute) |
| `create_attribute(body)`                                                        | [`POST /attributes`](/api/lead-attributes#create-a-lead-attribute)              |
| `update_attribute(attribute_id, body)`                                          | [`PUT /attributes/{id}`](/api/lead-attributes#update-a-lead-attribute)          |
| `delete_attribute(attribute_id)`                                                | [`DELETE /attributes/{id}`](/api/lead-attributes#delete-a-lead-attribute)       |
| `list_bulks(bulk_type, params)`                                                 | [`GET /bulk/{type}`](/api/bulks)                                                |
| `create_bulk(bulk_type, data)`                                                  | [`POST /bulk/{type}`](/api/bulks)                                               |
| `get_bulk(bulk_type, id)`                                                       | [`GET /bulk/{type}/{id}`](/api/bulks)                                           |
| `launch_bulk(bulk_type, id)`                                                    | [`PUT /bulk/{type}/{id}`](/api/bulks)                                           |
| `bulk_progress(bulk_type, id)`                                                  | [`GET /bulk/{type}/{id}/progress`](/api/bulks)                                  |
| `bulk_download(bulk_type, id)`                                                  | [`GET /bulk/{type}/{id}/download`](/api/bulks)                                  |
| `rename_bulk(bulk_type, id, name)`                                              | [`PUT /bulk/{type}/{id}/rename`](/api/bulks)                                    |
| `archive_bulk(bulk_type, id)`                                                   | [`DELETE /bulk/{type}/{id}/archive`](/api/bulks)                                |
| `delete_bulk(bulk_type, 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).

## Codice sorgente

[github.com/tomba-io/lua](https://github.com/tomba-io/lua), con licenza Apache-2.0 secondo il suo rockspec.
