# Python SDK

`tomba-io` 是 [Tomba API](/introduction) 的官方 Python 客户端。每个 API 功能区对应一个服务类，每个方法发送 1 个请求。

## 要求

- Python 3.8 或更高版本。该包未声明最低版本；其 CI 在 Python 3.8 至 3.12 上进行测试。
- [`requests`](https://pypi.org/project/requests/)，作为依赖项安装。

## 安装

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

导入名称为 `tomba`。

## 认证

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

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

SDK 不会读取环境变量。请将这些值传给 `set_key()` 和 `set_secret()`，客户端会将它们作为 `X-Tomba-Key` 和 `X-Tomba-Secret` 请求头发送。密钥过期和轮换请参阅[认证](/authentication)。

## 首个请求

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

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

每个方法都返回一个包含 2 个键的 dict：`data`（解码后的 JSON 响应体）和 `rate_limit`。API 会将其有效负载包装在自己的 `data` 对象中（[响应格式](/introduction#response-format)），因此地址位于 `result["data"]["data"]["email"]`。

## 错误

API 以 400 或更高的状态码响应时、请求失败时，SDK 会抛出 `TombaException`；必填参数为 `None` 时，SDK 会在发送请求之前抛出该异常。

| 属性  | 值                                                                                                  |
| ---------- | ------------------------------------------------------------------------------------------------------ |
| `code`     | HTTP 状态码。未收到响应时为 `0`，例如缺少参数或发生网络错误。 |
| `message`  | API 返回的 `errors.message`，或底层错误。                                                   |
| `response` | 解码后的错误响应体 `{"errors": {"type": …, "message": …, "code": …}}`，或 `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()` 和 `combined()` 在未找到结果时不会抛出异常：这些端点会返回状态码 200 和 `errors` 响应体，因此请检查 `result["data"].get("errors")`。每种 `errors.type` 的说明请参阅[错误](/error-handling#error-types)。

## 速率限制和重试

SDK 不会重试。`result["rate_limit"]` 以 `second_limit`、`minute_limit`、`daily_limit`、`minute_remaining`、`daily_remaining`、`minute_reset`、`daily_reset`、`retry_after`、`policy` 和 `rate_limit` 的形式保存响应中的[速率限制响应头](/rate-limits#rate-limit-headers)。数值为整数，缺失或为 `0` 的响应头会变为 `None`。

`429` 会抛出 `code` 为 429 的 `TombaException`，其中不包含 `Retry-After` 响应头。请按照[处理 429 响应](/rate-limits#handle-429-responses)中的说明等待后再重试。

请求在 120 秒后超时。可使用 `client.set_timeout(seconds)` 更改超时时间。

## 方法参考

使用客户端创建每个服务，例如 `Finder(client)`。所有类都可以从 `tomba` 导入。ID 为字符串。

| 方法                                                                                                                     | 端点                                                                    |
| -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `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` 是[批量类型](/bulks#bulk-types)中列出的 `{type}` 路径段；调用顺序请参阅[生命周期](/bulks#lifecycle)。`create_bulk` 发送 JSON 请求体，因此无法创建需要上传 CSV 的任务，例如[邮箱查找器](/bulks#email-finder)任务。`download_bulk` 以字节形式在 `result["data"]` 中返回结果文件（CSV）。

## 源代码

[github.com/tomba-io/python](https://github.com/tomba-io/python)（Apache-2.0）。发行说明见 [CHANGELOG.md](https://github.com/tomba-io/python/blob/master/CHANGELOG.md)。
