# Lua SDK

`tomba` rock 是 [Tomba API](/introduction) 的官方 Lua 客户端。所有方法都位于同一个客户端对象上，每个方法发送 1 个请求。

## 要求

- Lua 5.1、5.2 或 5.3。rockspec 允许 Lua 5.1 或更高版本，但 `lua-requests` 所依赖的 `xml` rock 要求低于 5.4 的版本。
- [LuaRocks](https://luarocks.org/) 和一个 C++ 编译器，用于构建依赖项 `lua-requests` 和 `lua-cjson`。

## 安装

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

第 1 条命令以 C++14 模式构建 `xml` rock。如果不执行它，`luarocks install tomba` 会在默认使用 C++17 的编译器（例如 GCC 11 及更高版本）上失败，因为 `xml` 无法以 C++17 编译。

## 认证

在 [API keys](https://app.tomba.io/api) 页面创建 API 密钥并复制您的 Secret，然后将它们都导出：

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

SDK 不会读取环境变量。将这些值传给 `Tomba:init(key, secret)`，客户端会将它们作为 `X-Tomba-Key` 和 `X-Tomba-Secret` 请求头发送。如果其中任一值短于 39 个字符，`init` 会抛出错误。有关密钥过期和轮换，请参阅[认证](/authentication)。

## 首个请求

查找某家公司中某个人的邮箱地址：

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

每个方法都返回一个包含 2 个字段的表：`data`（解码后的 JSON 响应体）和 `rate_limit`。API 会将有效负载包装在它自己的 `data` 对象中（[响应格式](/introduction#response-format)），因此邮箱地址位于 `result.data.data.email`。JSON 中的 `null` 值会被解码为 `cjson.null`。

## 错误

失败的表现形式取决于 HTTP 方法：

- 当状态码不是 200 时，`GET` 方法会抛出 Lua 错误。错误消息是原始响应体，前面带有 SDK 的文件名和行号。
- `POST`、`PUT` 和 `DELETE` 方法在发生 API 错误时不会抛出错误。无论状态码是什么，它们都会返回结果表，因此需检查 `result.data.errors`。

使用 `pcall` 捕获 `GET` 错误并解码响应体：

```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` 是 HTTP 状态码。每个 `errors.type` 的说明请参阅[错误](/error-handling#error-types)。

## 速率限制和重试

SDK 不会重试。`result.rate_limit` 保存响应中存在的[速率限制响应头](/rate-limits#rate-limit-headers)，以标头名称为键，值为字符串：`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` 和 `ratelimit`。

`GET` 方法收到 `429` 时会抛出不包含响应头的错误。按照[处理 429 响应](/rate-limits#handle-429-responses)中的说明，等待一段时间后再重试。

请求在 120 秒后超时；超时时间不可配置。

## 方法参考

使用冒号在客户端上调用每个方法，例如 `tomba:email_finder(...)`。`opts` 是一个可选的表。

| 方法                                                                          | 端点                                                                        |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `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)`，支持 `opts.enrich_mobile` 和 `opts.webhook_url` | [`GET /domain-search`](/api/finder#domain-search)                               |
| `email_finder(domain, first_name, last_name, opts)`，支持 `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` 是[批量类型](/bulks#bulk-types)中列出的 `{type}` 路径段；调用顺序请参阅[生命周期](/bulks#lifecycle)。`create_bulk` 发送 JSON 请求体，因此无法创建需要上传 CSV 的任务，例如[邮箱查找器](/bulks#email-finder)任务。

## 源代码

[github.com/tomba-io/lua](https://github.com/tomba-io/lua)，其 rockspec 中声明的许可证为 Apache-2.0。
