# SDK para C#

O pacote NuGet `Tomba` é o cliente oficial .NET para a [API da Tomba](/introduction). Cada área da API é uma classe de serviço, e cada método envia uma requisição e retorna o `HttpResponseMessage` bruto.

## Requisitos

- .NET 10. A versão 1.0.1 do pacote tem como destino apenas `net10.0`.
- [`Newtonsoft.Json`](https://www.nuget.org/packages/Newtonsoft.Json), instalado como dependência.

## Instalação

```bash
dotnet add package Tomba
```

As classes estão no namespace `Tomba`.

## Autenticação

Crie uma chave de API e copie seu secret na página [API keys](https://app.tomba.io/api) e depois exporte os dois:

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

O SDK não lê variáveis de ambiente. Passe os valores para `SetKey()` e `SetSecret()`, e o cliente os envia nos cabeçalhos `X-Tomba-Key` e `X-Tomba-Secret`. Chame cada setter uma única vez por cliente: uma segunda chamada lança `ArgumentException`. A expiração e a rotação das chaves são explicadas em [Autenticação](/authentication).

## Primeira requisição

Verifique um endereço de email.

```csharp
using Newtonsoft.Json.Linq;
using Tomba;

var client = new Client()
    .SetKey(Environment.GetEnvironmentVariable("TOMBA_API_KEY"))
    .SetSecret(Environment.GetEnvironmentVariable("TOMBA_SECRET_KEY"));

var response = await new Verifier(client).EmailVerifier("jane.doe@stripe.com");
var body = JObject.Parse(await response.Content.ReadAsStringAsync());
Console.WriteLine(body["data"]?["email"]?["status"]);
```

O exemplo é um programa `dotnet new console` com instruções de nível superior. Os métodos retornam o `HttpResponseMessage` sem análise, então leia e analise o corpo JSON você mesmo. A API encapsula o payload em um objeto `data` ([Formato da resposta](/introduction#response-format)); o status da verificação fica em `data.email.status`.

## Erros

O SDK lança `TombaException` quando a API responde com status 400 ou superior e quando a requisição falha. Nos erros da API, a exceção vem encapsulada: a `TombaException` externa tem o `errors.message` da API como `Message`, e a `InnerException` dela é uma `TombaException` cujo `Code` é o status HTTP e cujo `Response` é o corpo bruto da resposta.

```csharp
using Newtonsoft.Json.Linq;
using Tomba;

var client = new Client()
    .SetKey(Environment.GetEnvironmentVariable("TOMBA_API_KEY"))
    .SetSecret(Environment.GetEnvironmentVariable("TOMBA_SECRET_KEY"));

try
{
    var response = await new Verifier(client).EmailVerifier("jane.doe@stripe.com");
    var body = JObject.Parse(await response.Content.ReadAsStringAsync());
    Console.WriteLine(body["data"]?["email"]?["status"]);
}
catch (TombaException e)
{
    var inner = e.InnerException as TombaException;
    Console.WriteLine($"{inner?.Code} {e.Message}");
    Console.WriteLine(inner?.Response);
}
```

`inner` é `null` quando a requisição falhou antes de chegar uma resposta. O `Response` bruto é o corpo JSON do erro; cada `errors.type` nele é descrito em [Erros](/error-handling#error-types).

## Limites de requisições e novas tentativas

O SDK não faz novas tentativas. `Client.ParseRateLimit(response)` lê os [cabeçalhos de limite de requisições](/rate-limits#rate-limit-headers) de uma resposta bem-sucedida em um `RateLimit` com as propriedades `int?` `SecondRateLimit`, `MinuteRateLimit`, `DailyRateLimit`, `MinuteRequestLeft`, `DailyRequestLeft`, `MinuteResetSeconds`, `DailyResetSeconds` e `RetryAfter`, e as propriedades `string` `RateLimitPolicy` e `RateLimitValue`.

Um `429` lança `TombaException` sem os cabeçalhos da resposta. Aguarde antes de tentar novamente, conforme descrito em [Tratar respostas 429](/rate-limits#handle-429-responses).

As requisições expiram após 120 segundos.

## Referência de métodos

Crie cada serviço com o cliente, por exemplo `new Verifier(client)`. Todos os métodos retornam `Task<HttpResponseMessage>`.

| Método                                                                               | Endpoint                                                                    |
| ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| `Account.GetAccount()`                                                               | [`GET /me`](/api/account#get-account)                                       |
| `Usage.GetUsage()`                                                                   | [`GET /usage`](/api/account#retrieve-api-usage)                             |
| `Logs.GetLogs(int? page = null, int? limit = null)`                                  | [`GET /logs`](/api/account#retrieve-api-logs)                               |
| `Format.EmailFormatAsync(string domain)`                                             | [`GET /email-format`](/api/finder#email-format)                             |
| `Count.EmailCount(string domain)`                                                    | [`GET /email-count`](/api/finder#email-count)                               |
| `Verifier.EmailVerifier(string email, string webhookUrl = null)`                     | [`GET /email-verifier`](/api/verifier#email-verifier)                       |
| `Sources.EmailSources(string email)`                                                 | [`GET /email-sources`](/api/email#email-sources)                            |
| `Phone.FinderAsync(Dictionary<string, object> parameters, string webhookUrl = null)` | [`GET /phone-finder`](/api/phone#phone-finder)                              |
| `Phone.ValidatorAsync(string phone, string countryCode = null)`                      | [`GET /phone-validator`](/api/phone#phone-validator)                        |
| `Status.DomainStatus(string domain)`                                                 | [`GET /domain-status`](/api/domain#domain-status)                           |
| `Status.AutoComplete(string query)`                                                  | [`GET /domain-suggestions`](/api/domain-suggestions#get-domain-suggestions) |
| `Keys.GetKeys()`                                                                     | [`GET /keys`](/api/keys#retrieve-api-keys)                                  |
| `Keys.GetKey(string id)`                                                             | [`GET /keys/{id}`](/api/keys#retrieve-a-single-api-key)                     |
| `Keys.CreateKey()`                                                                   | [`POST /keys`](/api/keys#create-an-api-key)                                 |
| `Keys.ResetKey(string id)`                                                           | [`PUT /keys/{id}`](/api/keys#reset-an-api-key)                              |
| `Keys.DeleteKey(string id)`                                                          | [`DELETE /keys/{id}`](/api/keys#delete-an-api-key)                          |
| `Leads.ListLeadsAsync(int? page = 1, int? limit = 10, string domain = null)`         | [`GET /leads`](/api/leads#retrieve-leads)                                   |
| `Leads.GetLeadAsync(string id)`                                                      | [`GET /leads/{id}`](/api/leads#retrieve-a-single-lead)                      |
| `Leads.CreateLeadAsync(Dictionary<string, object> data)`                             | [`POST /leads`](/api/leads#create-a-lead)                                   |
| `Leads.UpdateLeadAsync(string id, Dictionary<string, object> data)`                  | [`PUT /leads/{id}`](/api/leads#update-a-lead)                               |
| `Leads.DeleteLeadAsync(string id)`                                                   | [`DELETE /leads/{id}`](/api/leads#delete-a-lead)                            |
| `LeadsLists.GetLists()`                                                              | [`GET /leads_lists`](/api/lead-lists#retrieve-leads-lists)                  |
| `LeadsLists.DeleteListId(string id)`                                                 | [`DELETE /leads_lists/{id}`](/api/lead-lists#delete-leads-list)             |
| `Bulk.ListAsync(string type, Dictionary<string, object> parameters = null)`          | [`GET /bulk/{type}`](/api/bulks)                                            |
| `Bulk.CreateAsync(string type, Dictionary<string, object> data)`                     | [`POST /bulk/{type}`](/api/bulks)                                           |
| `Bulk.GetAsync(string type, string id)`                                              | [`GET /bulk/{type}/{id}`](/api/bulks)                                       |
| `Bulk.ProgressAsync(string type, string id)`                                         | [`GET /bulk/{type}/{id}/progress`](/api/bulks)                              |
| `Bulk.DownloadAsync(string type, string id)`                                         | [`GET /bulk/{type}/{id}/download`](/api/bulks)                              |
| `Bulk.RenameAsync(string type, string id, string name)`                              | [`PUT /bulk/{type}/{id}/rename`](/api/bulks)                                |

`type` é o segmento `{type}` listado em [Tipos de jobs em massa](/bulks#bulk-types). `CreateAsync` envia um corpo JSON, então não pode criar jobs que exigem o envio de um CSV, como os jobs de [Email Finder](/bulks#email-finder).

## Código-fonte

[github.com/tomba-io/csharp](https://github.com/tomba-io/csharp) (Apache-2.0). As notas de versão estão em [CHANGELOG.md](https://github.com/tomba-io/csharp/blob/master/CHANGELOG.md).
