> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tirdad.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Using the SDKs

> Client setup, usage events, idempotency, errors, retries, pagination, and webhook parsing in the Tirdad Go, Python, and TypeScript SDKs

Every example on this page has a Go, Python, and TypeScript tab. Pick a language once and every code block on the page switches to it. For what the SDKs share and which one to pick, see the [SDK overview](https://docs.tirdad.ai/developers/sdks/overview).

> [!WARNING]
>
> The SDKs authenticate with an API key that can read and write your whole environment. Call them from server code only, even though the TypeScript SDK also runs in browsers. See Harden client-side access.

## Installing the Tirdad SDK

```bash Go theme={null}
go get github.com/tirdad-billing/go-sdk/v2
```

```bash Python theme={null}
pip install tirdad-sdk
```

```bash TypeScript theme={null}
npm i @tirdad/sdk
# or: pnpm add @tirdad/sdk
# or: yarn add @tirdad/sdk
```

| SDK | Requires | Notes |
| - | - | - |
| Go | Go 1.25 or newer, with modules | Imported as `github.com/tirdad-billing/go-sdk/v2` |
| Python | Python 3.10 or newer | Install into your project's virtual environment. Pulls in `httpx` and `pydantic` |
| TypeScript | Node.js 18+, Bun, Deno, Cloudflare Workers, Vercel Edge | Ships ESM and CommonJS builds with full type definitions |

## Creating an SDK client

```go Go theme={null}
import (
	"os"

	tirdad "github.com/tirdad-billing/go-sdk/v2"
)

client := tirdad.New(
	tirdad.WithServerURL(os.Getenv("TIRDAD_API_HOST")), // https://api.tirdad.ai/v1
	tirdad.WithSecurity(os.Getenv("TIRDAD_API_KEY")),
)
```

```python Python theme={null}
import os
from tirdad_sdk import Tirdad

client = Tirdad(
    server_url=os.getenv("TIRDAD_API_HOST", "https://api.tirdad.ai/v1"),
    api_key_auth=os.environ["TIRDAD_API_KEY"],
)
```

```typescript TypeScript theme={null}
import { Tirdad } from "@tirdad/sdk";

const tirdad = new Tirdad({
  serverURL: process.env.TIRDAD_API_HOST ?? "https://api.tirdad.ai/v1",
  apiKeyAuth: process.env.TIRDAD_API_KEY,
});
```

The server URL is the full base URL including `/v1`, with no trailing slash.

* **Go:** omit `WithServerURL`, or pass an empty string, to use the default server.
* **Python:** the client is also a context manager. `with Tirdad(server_url=..., api_key_auth=...) as client:` closes the underlying HTTP connection pool on exit.

## Creating a customer and sending usage events with the SDK

```go Go theme={null}
_, err := client.Customers.CreateCustomer(ctx, types.CreateCustomerRequest{
	ExternalID: "cust_123",
	Name:       "Acme",
	Email:      tirdad.String("billing@acme.example"),
})
if err != nil {
	return err
}

resp, err := client.Events.IngestEvent(ctx, types.IngestEventRequest{
	EventName:          "api_request",
	ExternalCustomerID: "cust_123",
	EventID:            tirdad.String("req_9f3c"),             // your own ID, reused on retries
	Timestamp:          tirdad.String("2026-10-10T14:03:00Z"), // when the usage happened, reused on retries
	Properties:         map[string]string{"region": "us-east-1", "bytes": "1024"},
	Source:             tirdad.String("api-gateway"),
})
if err != nil {
	return err
}
log.Println(resp.Object["event_id"])
```

```python Python theme={null}
client.customers.create_customer(
    external_id="cust_123",
    name="Acme",
    email="billing@acme.example",
)

result = client.events.ingest_event(
    event_name="api_request",
    external_customer_id="cust_123",
    event_id="req_9f3c",  # your own ID, reused on retries
    timestamp="2026-10-10T14:03:00Z",  # when the usage happened, reused on retries
    properties={"region": "us-east-1", "bytes": "1024"},
    source="api-gateway",
)
print(result["event_id"])
```

```typescript TypeScript theme={null}
const customer = await tirdad.customers.createCustomer({
  externalId: "cust_123",
  name: "Acme",
  email: "billing@acme.example",
});

const result = await tirdad.events.ingestEvent({
  eventName: "api_request",
  externalCustomerId: "cust_123",
  eventId: "req_9f3c",                 // your own ID, reused on retries
  timestamp: "2026-10-10T14:03:00Z",   // when the usage happened, reused on retries
  properties: { region: "us-east-1", bytes: "1024" },
  source: "api-gateway",
});
console.log(result.event_id);
```

Ingestion answers `202 Accepted` with `{"event_id": "...", "message": "..."}`. Go exposes it as `resp.Object`, and Python and TypeScript return it as a plain map. The event is metered asynchronously, so a successful call means "queued", not "counted". Use the [Event Debugger](https://docs.tirdad.ai/docs/event-ingestion/event-debugger.md) to confirm how it aggregated. A retried event collapses into the original only when it carries the same `event_id` and `timestamp`: see [Idempotency and Deduplication](https://docs.tirdad.ai/docs/core-concepts/usage-events/idempotency.md).

### SDK field names and optional values

* **Field names.** The API uses `snake_case`. Go uses `PascalCase` fields (`ExternalID`) and TypeScript uses `camelCase` fields (`externalId`), and both convert on the wire. Python keeps `snake_case` keyword arguments.
* **Optional fields in Go.** Required fields such as `ExternalID` and `Name` are plain Go values, and maps such as `Metadata` are plain Go maps. Optional scalar fields are pointers. The package ships `tirdad.String`, `tirdad.Int64`, `tirdad.Bool`, and `tirdad.Pointer` so you do not write `&s` everywhere.
* **Nil-safe getters in Go.** Response structs expose getters, so `resp.GetCustomerResponse().GetID()` is safe even when a parent is `nil`.

## Sending usage events in bulk with the SDK

For backfills or batching, send up to 1000 events per call. Each item takes the same fields as a single event:

```go Go theme={null}
_, err := client.Events.IngestEventsBulk(ctx, types.BulkIngestEventRequest{
	Events: []types.IngestEventRequest{
		{EventName: "api_request", ExternalCustomerID: "cust_123", EventID: tirdad.String("req_9f3c")},
		{EventName: "api_request", ExternalCustomerID: "cust_456", EventID: tirdad.String("req_9f3d")},
	},
})
```

```python Python theme={null}
client.events.ingest_events_bulk(events=[
    {"event_name": "api_request", "external_customer_id": "cust_123", "event_id": "req_9f3c"},
    {"event_name": "api_request", "external_customer_id": "cust_456", "event_id": "req_9f3d"},
])
```

```typescript TypeScript theme={null}
await tirdad.events.ingestEventsBulk({
  events: [
    { eventName: "api_request", externalCustomerId: "cust_123", eventId: "req_9f3c" },
    { eventName: "api_request", externalCustomerId: "cust_456", eventId: "req_9f3d" },
  ],
});
```

### Batching events with the Go async client

The Go SDK has an async client that queues events in memory and sends them from background goroutines, picking up `BatchSize` events at a time or every `FlushInterval`. Each event still goes out as its own `POST /events` request:

```go theme={null}
asyncConfig := tirdad.DefaultAsyncConfig()
asyncClient := client.NewAsyncClientWithConfig(asyncConfig)
defer asyncClient.Close()

err := asyncClient.Enqueue("api_request", "cust_123", map[string]interface{}{
	"region": "us-east-1",
})
```

`Enqueue` takes `map[string]interface{}` properties and converts the values to strings on the wire. `EnqueueWithOptions` takes a `tirdad.EventOptions` when you need `EventID`, `Timestamp`, or `Source`:

```go theme={null}
err := asyncClient.EnqueueWithOptions(tirdad.EventOptions{
	EventName:          "api_request",
	ExternalCustomerID: "cust_123",
	EventID:            "req_9f3c",
	Properties:         map[string]interface{}{"region": "us-east-1"},
	Source:             "api-gateway",
	Timestamp:          time.Now().UTC().Format(time.RFC3339),
})
```

`BatchSize`, `FlushInterval`, `MaxQueueSize`, and `Debug` are fields on the config. The async client does not set an `event_id`, so pass one with `EnqueueWithOptions` if you need retries to dedupe. A failed send is dropped once the parent client's retries run out, and `Close()` returns without waiting for queued events, so events still in memory at exit can be lost. For usage you bill on, see [High-Volume Ingestion](https://docs.tirdad.ai/docs/core-concepts/usage-events/high-volume-ingestion.md#how-the-go-sdk-async-client-sends-usage-events).

### Async calls in the Python SDK

The Python client also works as an async context manager, and every method has an `_async` twin:

```python theme={null}
import asyncio
import os
from tirdad_sdk import Tirdad

async def main():
    async with Tirdad(
        server_url="https://api.tirdad.ai/v1",
        api_key_auth=os.environ["TIRDAD_API_KEY"],
    ) as client:
        result = await client.events.ingest_event_async(
            event_name="api_request",
            external_customer_id="cust_123",
        )
        print(result)

asyncio.run(main())
```

Use the async client inside FastAPI, aiohttp, or any event loop so ingestion does not block request handling. TypeScript methods already return promises and need no separate client.

## Idempotent requests with the SDK

Idempotency lives in the request body, on the endpoints that support it. Invoices, credit notes, wallet top-ups, portal payments, and checkout sessions take an `idempotency_key` field. Send the same key on a retry and the API does not create a second object: invoices and credit notes return the original, and a wallet top-up answers `409 Conflict`:

```go Go theme={null}
_, err := client.Wallets.TopUpWallet(ctx, walletID, types.TopUpWalletRequest{
	CreditsToAdd:      tirdad.String("100"),
	TransactionReason: types.TransactionReasonPurchasedCreditDirect,
	IdempotencyKey:    tirdad.String("topup-order-8841"),
})
```

```python Python theme={null}
client.wallets.top_up_wallet(
    id=wallet_id,
    credits_to_add="100",
    transaction_reason="PURCHASED_CREDIT_DIRECT",
    idempotency_key="topup-order-8841",
)
```

```typescript TypeScript theme={null}
await tirdad.wallets.topUpWallet(walletId, {
  creditsToAdd: "100",
  transactionReason: "PURCHASED_CREDIT_DIRECT",
  idempotencyKey: "topup-order-8841",
});
```

For other creates, rely on the natural key. A second customer with the same external ID returns `409 Conflict`, so a retried create can be treated as success. Events dedupe on their event ID and timestamp together.

The Go package also exports `WithIdempotencyKey`, which sets an `Idempotency-Key` request header. The API does not read that header, so it does not make a call safe to retry on its own.

## Handling SDK errors

API errors carry the HTTP status code, so you can branch on it:

```go Go theme={null}
import "github.com/tirdad-billing/go-sdk/v2/errorutils"

_, err := client.Customers.CreateCustomer(ctx, req)
switch {
case errorutils.IsConflict(err):     // 409: already exists, safe to look up instead
case errorutils.IsValidation(err):   // 400: fix the request
case errorutils.IsNotFound(err):     // 404
case errorutils.IsRateLimit(err):    // 429: back off
case errorutils.IsPermissionDenied(err): // 403: key lacks the role
case errorutils.IsServerError(err):  // 5xx: surface it
case err != nil:
	return err
}
```

```python Python theme={null}
from tirdad_sdk.models import errors

try:
    client.customers.get_customer(id="cust_does_not_exist")
except errors.TirdadError as e:
    if e.status_code == 404:
        ...  # not found
    elif e.status_code == 409:
        ...  # conflict: safe to retry or look up
    elif e.status_code == 429:
        ...  # rate limited: back off
    else:
        raise
```

```typescript TypeScript theme={null}
import { TirdadError } from "@tirdad/sdk";

try {
  await tirdad.customers.getCustomer("cust_does_not_exist");
} catch (err) {
  if (err instanceof TirdadError) {
    switch (err.statusCode) {
      case 404: /* not found */ break;
      case 409: /* conflict: safe to retry or look up */ break;
      case 429: /* rate limited: back off */ break;
      default: throw err;
    }
  }
}
```

* **Go:** use the `errorutils` helpers for a quick status check, or `errors.As` for the typed error.
* **Python:** `TirdadError` is the base class. `errors.ErrorResponse` carries a parsed API error body, and `errors.NoResponseError` means the request never got an HTTP response.
* **TypeScript:** non-`2xx` responses throw. `TirdadError` is the base class and carries `statusCode`, `body`, `headers`, and `rawResponse`.

## Retrying failed SDK requests

Retries are off by default in every SDK. Pass a retry config to the client and it retries `429`, `500`, `502`, `503`, and `504` responses with exponential backoff, plus connection errors when that flag is set. Intervals are in milliseconds:

```go Go theme={null}
import "github.com/tirdad-billing/go-sdk/v2/retry"

client := tirdad.New(
	tirdad.WithSecurity(os.Getenv("TIRDAD_API_KEY")),
	tirdad.WithRetryConfig(retry.Config{
		Strategy: "backoff",
		Backoff: &retry.BackoffStrategy{
			InitialInterval: 500, // milliseconds
			MaxInterval:     10000,
			Exponent:        1.5,
			MaxElapsedTime:  60000,
		},
		RetryConnectionErrors: true,
	}),
)
```

```python Python theme={null}
import os
from tirdad_sdk import Tirdad
from tirdad_sdk.utils import BackoffStrategy, RetryConfig

client = Tirdad(
    server_url="https://api.tirdad.ai/v1",
    api_key_auth=os.environ["TIRDAD_API_KEY"],
    retry_config=RetryConfig("backoff", BackoffStrategy(500, 10_000, 1.5, 60_000), True),
)
```

```typescript TypeScript theme={null}
const tirdad = new Tirdad({
  serverURL: process.env.TIRDAD_API_HOST ?? "https://api.tirdad.ai/v1",
  apiKeyAuth: process.env.TIRDAD_API_KEY,
  retryConfig: {
    strategy: "backoff",
    backoff: { initialInterval: 500, maxInterval: 10000, exponent: 1.5, maxElapsedTime: 60000 },
    retryConnectionErrors: true,
  },
});
```

## Paginating list endpoints with the SDK

List methods take a limit and an offset. The offset in the response's `pagination` is already advanced to the next page. In Go, the list sits behind `GetListCustomersResponse()`:

```go Go theme={null}
offset := int64(0)
for {
	page, err := client.Customers.QueryCustomer(ctx, types.CustomerFilter{
		Limit:  tirdad.Int64(100),
		Offset: tirdad.Int64(offset),
	})
	if err != nil {
		return err
	}

	list := page.GetListCustomersResponse()
	for _, c := range list.GetItems() {
		// ...
	}

	next, total := list.GetPagination().GetOffset(), list.GetPagination().GetTotal()
	if len(list.GetItems()) == 0 || next == nil || total == nil || *next >= *total {
		break
	}
	offset = *next
}
```

```python Python theme={null}
offset = 0
while True:
    page = client.customers.query_customer(limit=100, offset=offset)
    for customer in page.items:
        ...
    if not page.items or offset + 100 >= page.pagination.total:
        break
    offset = page.pagination.offset
```

```typescript TypeScript theme={null}
let offset = 0;
while (true) {
  const page = await tirdad.customers.queryCustomer({ limit: 100, offset });
  for (const customer of page.items ?? []) {
    // ...
  }
  if (!page.items?.length || offset + 100 >= (page.pagination?.total ?? 0)) break;
  offset = page.pagination?.offset ?? offset + 100;
}
```

## Parsing webhook payloads with the SDK

Every SDK ships a typed model for each webhook payload. Read `event_type`, then parse the body into the matching model. Verify the signature before parsing: see [Signature verification](https://docs.tirdad.ai/developers/webhooks/signature-verification.md).

```go Go theme={null}
import (
	"encoding/json"
	"io"
	"net/http"

	"github.com/tirdad-billing/go-sdk/v2/models/types"
)

type envelope struct {
	EventType types.WebhookEventName `json:"event_type"`
}

func handleWebhook(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)

	var env envelope
	if err := json.Unmarshal(body, &env); err != nil {
		http.Error(w, "invalid JSON", http.StatusBadRequest)
		return
	}

	switch env.EventType {
	case types.WebhookEventNameInvoiceUpdateFinalized:
		var payload types.WebhookDtoInvoiceWebhookPayload
		json.Unmarshal(body, &payload)
		// payload.GetInvoice().GetID()
	case types.WebhookEventNamePaymentSuccess, types.WebhookEventNamePaymentFailed:
		var payload types.WebhookDtoPaymentWebhookPayload
		json.Unmarshal(body, &payload)
	}

	w.WriteHeader(http.StatusOK) // also for events you do not handle
}
```

```python Python theme={null}
import json
from tirdad_sdk.models import (
    WebhookDtoInvoiceWebhookPayload,
    WebhookDtoPaymentWebhookPayload,
    WebhookDtoSubscriptionWebhookPayload,
)

def handle_webhook(raw_body: str) -> None:
    event = json.loads(raw_body)

    match event.get("event_type"):
        case "invoice.update.finalized" | "invoice.payment.overdue":
            payload = WebhookDtoInvoiceWebhookPayload.model_validate(event)
            invoice = payload.invoice
        case "payment.success" | "payment.failed":
            payload = WebhookDtoPaymentWebhookPayload.model_validate(event)
        case "subscription.activated" | "subscription.cancelled":
            payload = WebhookDtoSubscriptionWebhookPayload.model_validate(event)
        case _:
            pass  # return 200 for events you do not handle
```

```typescript TypeScript theme={null}
import { webhookDtoInvoiceWebhookPayloadFromJSON } from "@tirdad/sdk";

export async function POST(req: Request) {
  const raw = await req.text();
  // verify the signature on `raw` first, see Signature verification

  const { event_type } = JSON.parse(raw);

  if (event_type === "invoice.update.finalized") {
    const parsed = webhookDtoInvoiceWebhookPayloadFromJSON(raw);
    if (!parsed.ok) return new Response("bad payload", { status: 400 });
    const invoice = parsed.value.invoice;
    // ...
  }

  return new Response("ok", { status: 200 }); // also for events you do not handle
}
```

In TypeScript, each payload's `fromJSON` helper returns a `SafeParseResult`, so check `.ok` before reading `.value`.

## Standalone functions in the TypeScript SDK

Every TypeScript method is also exported as a standalone function that takes a `TirdadCore` instance. Unused functions tree-shake out of the bundle, and the functions return a `Result` instead of throwing, which suits serverless and edge code:

```typescript theme={null}
import { TirdadCore } from "@tirdad/sdk/core.js";
import { eventsIngestEvent } from "@tirdad/sdk/funcs/events-ingest-event.js";

const core = new TirdadCore({
  serverURL: "https://api.tirdad.ai/v1",
  apiKeyAuth: process.env.TIRDAD_API_KEY,
});

const res = await eventsIngestEvent(core, {
  eventName: "api_request",
  externalCustomerId: "cust_123",
});

if (res.ok) {
  console.log(res.value.event_id);
} else {
  console.error(res.error);
}
```

## TypeScript compiler settings for the SDK

Target ES2020 or newer so the SDK's async iterables and streams compile without polyfills:

```jsonc theme={null}
{
  "compilerOptions": {
    "target": "es2020",
    "lib": ["es2020", "dom", "dom.iterable"]
  }
}
```

## SDK troubleshooting

| Symptom | Cause |
| - | - |
| `401` on every call | The API key is unset, expired |
| `404` on every call | The server URL is missing `/v1` or has a trailing slash |
| Events accepted but never metered | The event name does not match a feature's event name exactly (case-sensitive), or the customer's external ID differs |
| Go: `not enough arguments in call to c.apiClient.Events.IngestEvent` at build time | The module resolved to `v2.1.31`, which does not compile. Run `go get github.com/tirdad-billing/go-sdk/v2@latest` to move to `v2.1.32` or newer |
| Go: last events missing after exit | The async client was not closed with `Close()` |
| Python: `RuntimeError: Event loop is closed` | A sync client was used inside `async` code. Use `async with` and the `_async` methods |
| TypeScript: `fetch is not defined` | Node.js is older than 18. Upgrade, or pass a `fetch` polyfill through the `httpClient` option |

> [card] [Go SDK source](https://github.com/tirdad-billing/go-sdk)

> [card] [Python SDK source](https://github.com/tirdad-billing/python-sdk)

> [card] [TypeScript SDK source](https://github.com/tirdad-billing/ts-sdk)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.