# SDK de C#

El paquete NuGet `Tomba` es el cliente oficial de .NET para la [API de Tomba](/introduction). Cada área de la API es una clase de servicio, y cada método envía una solicitud y devuelve el `HttpResponseMessage` sin procesar.

## Requisitos

- .NET 10. La versión 1.0.1 del paquete solo tiene como destino `net10.0`.
- [`Newtonsoft.Json`](https://www.nuget.org/packages/Newtonsoft.Json), instalado como dependencia.

## Instalación

```bash
dotnet add package Tomba
```

Las clases están en el espacio de nombres `Tomba`.

## Autenticación

Crea una clave API y copia tu secreto en la página [API keys](https://app.tomba.io/api), y luego exporta ambos:

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

El SDK no lee variables de entorno. Pasa los valores a `SetKey()` y `SetSecret()`, y el cliente los envía como los encabezados `X-Tomba-Key` y `X-Tomba-Secret`. Llama a cada setter una sola vez por cliente: una segunda llamada lanza `ArgumentException`. La caducidad y la rotación de las claves se explican en [Autenticación](/authentication).

## Primera solicitud

Verifica una dirección 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"]);
```

El ejemplo es un programa `dotnet new console` con instrucciones de nivel superior. Los métodos devuelven el `HttpResponseMessage` sin analizar, así que lee y analiza tú mismo el cuerpo JSON. La API envuelve su payload en un objeto `data` ([Formato de respuesta](/introduction#response-format)); el estado de la verificación está en `data.email.status`.

## Errores

El SDK lanza `TombaException` cuando la API responde con un estado 400 o superior y cuando la solicitud falla. En los errores de la API, la excepción va envuelta: la `TombaException` externa tiene el `errors.message` de la API como `Message`, y su `InnerException` es una `TombaException` cuyo `Code` es el estado HTTP y cuyo `Response` es el cuerpo de la respuesta sin procesar.

```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` es `null` cuando la solicitud falló antes de que llegara una respuesta. El `Response` sin procesar es el cuerpo JSON del error; cada `errors.type` que contiene se describe en [Errores](/error-handling#error-types).

## Límites de solicitudes y reintentos

El SDK no reintenta. `Client.ParseRateLimit(response)` lee los [encabezados de límites de solicitudes](/rate-limits#rate-limit-headers) de una respuesta correcta en un `RateLimit` con las propiedades `int?` `SecondRateLimit`, `MinuteRateLimit`, `DailyRateLimit`, `MinuteRequestLeft`, `DailyRequestLeft`, `MinuteResetSeconds`, `DailyResetSeconds` y `RetryAfter`, y las propiedades `string` `RateLimitPolicy` y `RateLimitValue`.

Un `429` lanza `TombaException` sin los encabezados de la respuesta. Espera antes de reintentar como se describe en [Gestionar respuestas 429](/rate-limits#handle-429-responses).

Las solicitudes agotan el tiempo de espera a los 120 segundos.

## Referencia de métodos

Crea cada servicio con el cliente, por ejemplo `new Verifier(client)`. Todos los métodos devuelven `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` es el segmento `{type}` que se enumera en [Tipos de trabajos masivos](/bulks#bulk-types). `CreateAsync` envía un cuerpo JSON, así que no puede crear trabajos que requieren subir un CSV, como los trabajos de [Email Finder](/bulks#email-finder).

## Código fuente

[github.com/tomba-io/csharp](https://github.com/tomba-io/csharp) (Apache-2.0). Las notas de la versión están en [CHANGELOG.md](https://github.com/tomba-io/csharp/blob/master/CHANGELOG.md).
