# Python SDK

`tomba-io`는 [Tomba API](/introduction)의 공식 Python 클라이언트입니다. 각 API 영역은 서비스 클래스이며, 각 메서드는 요청 하나를 보냅니다.

## 요구 사항

- 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 키를 만들고 시크릿 키를 복사한 다음, 두 값을 환경 변수로 내보냅니다.

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

모든 메서드는 디코딩된 JSON 본문인 `data`와 `rate_limit`, 두 키를 가진 dict를 반환합니다. API는 페이로드를 자체 `data` 객체로 감싸므로([응답 형식](/introduction#response-format)) 주소는 `result["data"]["data"]["email"]`에 있습니다.

## 오류

SDK는 API가 400 이상의 상태로 응답할 때, 요청이 실패할 때, 그리고 필수 인수가 `None`인 경우 요청을 보내기 전에 `TombaException`을 발생시킵니다.

| 속성  | 값                                                                                                  |
| ---------- | ------------------------------------------------------------------------------------------------------ |
| `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"]`에는 응답의 [속도 제한 헤더](/rate-limits#rate-limit-headers)가 `second_limit`, `minute_limit`, `daily_limit`, `minute_remaining`, `daily_remaining`, `minute_reset`, `daily_reset`, `retry_after`, `policy`, `rate_limit`로 담깁니다. 숫자는 정수이며, 없거나 `0`인 헤더는 `None`이 됩니다.

`429`는 `Retry-After` 헤더 없이 `code`가 429인 `TombaException`을 발생시킵니다. [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 본문을 보내므로 [Email Finder](/bulks#email-finder) 작업처럼 CSV 업로드가 필요한 작업은 만들 수 없습니다. `download_bulk`는 결과 파일(CSV)을 `result["data"]`에 바이트로 반환합니다.

## 소스

[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)에 있습니다.
