Use the Kirora package to call the Kirora /v1 API from a .NET server with typed requests, pagination, retry handling and webhook verification. It works like the Node.js library, with .NET’s own conventions. This page covers the common tasks; the README is the full reference.
Install
Add the package from NuGet:
dotnet add package KiroraIt targets .NET 8 or later. Its namespace is Kirora:
using Kirora;Create a client
Keep your API key on your server and set it as KIRORA_API_KEY. new KiroraClient() reads it from there:
var client = new KiroraClient(); // reads KIRORA_API_KEYCreate one client and reuse it, for example as a singleton in your app’s services; it’s safe to use from many threads at once. The constructor takes the API key and a KiroraClientOptions:
| Option | Default | Description |
|---|---|---|
BaseUrl |
KIRORA_BASE_URL, or https://api.kirora.io |
For tests and mocks. The host only, without a version: the client adds /v1 to each path. |
Timeout |
30 seconds | How long each attempt may take, including reading the response. |
MaxRetries |
3 | Attempts after the first, from 0 to 10. 0 disables retrying. |
MaxRetryDelay |
30 seconds | Ceiling for a single wait between attempts. |
HttpClient |
Its own | A custom HttpClient, such as one from IHttpClientFactory or with a proxy. |
Workspace |
None | Partner keys only: the tenant workspace’s externalId. See Partner workspaces. |
DefaultHeaders |
None | Extra headers on every request. |
AppInfo |
None | Your app’s name and optional version, added to the User-Agent. |
var client = new KiroraClient(apiKey, new KiroraClientOptions { MaxRetries = 5 });Each resource is a service on the client, and each method is named after its operationId with the resource dropped and Async added, so identifyContact is client.Contacts.IdentifyAsync() and sendCampaign is client.Campaigns.SendAsync(). Methods return the response’s data, already unwrapped.
| Service | Methods |
|---|---|
Contacts |
ListAsync, AllAsync, GetAsync, UpdateAsync, DeleteAsync, IdentifyAsync, IdentifyBatchAsync, DeleteBatchAsync, MergeAsync, ExportAsync, ListListsAsync, AllListsAsync, ListTopicsAsync, SetTopicAsync, ListInstallationsAsync, AllInstallationsAsync, RegisterInstallationAsync, DeleteInstallationAsync |
Lists |
ListAsync, AllAsync, GetAsync, CreateAsync, UpdateAsync, DeleteAsync, AddContactsAsync, DeleteContactsAsync |
Campaigns |
ListAsync, AllAsync, GetAsync, CreateAsync, SendAsync, TriggerAsync, ScheduleAsync, EligibilityAsync |
Transactional |
SendAsync, SendBatchAsync, CancelAsync |
Events |
TrackAsync, TrackBatchAsync |
Messages |
ListAsync, AllAsync, GetAsync |
Suppressions |
ListAsync, AllAsync, AddAsync, DeleteAsync |
Workspaces |
ListAsync, AllAsync, CreateAsync, GetAsync, UpdateAsync, DeleteAsync, SuspendAsync, ResumeAsync, CancelDeletionAsync (partner keys only) |
EmbedSessions |
CreateAsync (partner keys only) |
On the client itself, client.MeAsync() returns the API key in use, its scopes and the workspace it acts in, and client.ForWorkspace(externalId) returns a copy that acts in one of your tenants.
Methods that take a contact name it by Kirora’s id, your externalId or its email: ContactRef.Id(id), ContactRef.ExternalId(userId) or ContactRef.Email("[email protected]").
Every method takes an optional RequestOptions and a CancellationToken last. For an operation without a method, call client.RequestAsync<T>(), or client.RequestAllAsync<T>() for a list; both use the same auth, retries and error mapping. See Other endpoints.
Optional fields
Request types are generated from the API’s spec, as records with init properties. Leave an optional property out, or set it to null, to send nothing for it.
A field that can also be set to null is an Optional<T>. Leave it out to keep the current value, set it with a plain value, or clear it with Optional<T>.Null:
await client.Contacts.UpdateAsync(ContactRef.Id(contactId), new UpdateContactInput
{
FirstName = "Olivia",
LastName = Optional<string>.Null, // clears it
// Phone is left as it is
});Enums are string-backed structs with a property for each value, such as CampaignScheduleType.Fixed. Each has an IsKnown property, which is false for a value added to the API after your version of the library.
Identify a contact
Contacts.IdentifyAsync() calls identifyContact: an upsert resolved by externalId, then email, then phone. It is safe to repeat; it converges rather than creating duplicates.
var contact = await client.Contacts.IdentifyAsync(new IdentifyContactInput
{
ExternalId = "cust_1042",
Email = "[email protected]",
FirstName = "Olivia",
});
Console.WriteLine(contact.Id);Track an event
Events.TrackAsync() calls trackEvent. The idempotency key is optional; pass one derived from your own event or order id to make your own retries safe too. Without one, the library makes one per call, which covers only its own retries.
var tracked = await client.Events.TrackAsync(
new TrackEventInput
{
ExternalId = "cust_1042",
Name = "Order Completed",
Properties = new Dictionary<string, object?> { ["order_id"] = "1042", ["total"] = 42.5, ["currency"] = "USD" },
},
new RequestOptions { IdempotencyKey = "order-1042-completed" });Events.TrackBatchAsync() sends up to 100 events at once. One event refused doesn’t stop the rest: the call succeeds, and each entry in Results, in the order you sent them, has either the Event or an Error:
var result = await client.Events.TrackBatchAsync(new TrackEventsBatchInput { Events = entries });
for (var i = 0; i < result.Results.Count; i++)
{
if (result.Results[i].Error is { } error)
logger.LogWarning("Event {Index} not tracked: {Code}", i, error.Code);
}A refusal of the whole batch throws, like any other call.
Send a transactional message
Transactional.SendAsync() calls sendTransactionalMessage. The key is optional, but pass your own, made once per logical send before the first attempt and outside any retry loop: a retry with the same key and body then replays the first send for as long as its message is kept (Retention). Without one, the library makes one per call, which covers only its own retries. See Idempotency.
var orderId = "1042";
var sent = await client.Transactional.SendAsync(
new SendTransactionalInput
{
To = new ContactIdentifier { Email = "[email protected]" },
Data = new Dictionary<string, object?> { ["order_id"] = orderId },
Email = new SendTransactionalEmail { Template = "order-receipt" }, // its alias or its id
},
new RequestOptions { IdempotencyKey = $"receipt-{orderId}" });Transactional.SendBatchAsync() calls sendTransactionalMessagesBatch: up to 100 messages, each with its own IdempotencyKey, and results per entry as with Events.TrackBatchAsync(). Transactional.CancelAsync(messageId) cancels a message scheduled with SendAt.
Paginate
AllAsync() (and AllListsAsync(), AllInstallationsAsync()) returns an IAsyncEnumerable<T> over every item, fetching pages as you go. break whenever you’ve had enough; no further pages are fetched:
await foreach (var contact in client.Contacts.AllAsync(new ListContactsParams { Limit = 100 }))
{
Console.WriteLine(contact.Email);
}ListAsync() fetches one page. To fetch the next page yourself, pass its NextCursor back as Cursor, with the same filters. It’s null on the last page. Treat the cursor as opaque.
var parameters = new ListContactsParams { Limit = 100 };
var page = await client.Contacts.ListAsync(parameters);
if (page.Meta.Pagination.NextCursor is { } cursor)
{
var next = await client.Contacts.ListAsync(parameters with { Cursor = cursor });
}Cancelling the token stops iteration before the next item, even one from a page already fetched. See Pagination.
Errors
Every error the API returns throws a KiroraApiException. Branch on Code, never on the message:
try
{
await client.Campaigns.SendAsync(campaignId);
}
catch (KiroraApiException e) when (e.Code == ErrorCode.SendingDomainUnverified)
{
// Recoverable: publish the DNS records and check the domain.
}
catch (KiroraApiException e)
{
logger.LogError("Kirora request failed: {Code} (request {RequestId})", e.Code, e.RequestId);
}| Property | Description |
|---|---|
Code |
The API’s error code, with a value for each published one, such as ErrorCode.NotFound. A code added after your version still comes through; Code.IsKnown tells you which. |
Message |
Human-readable; for logs, not for branching. |
StatusCode |
The HTTP status. |
Errors |
On VALIDATION_ERROR and DRAFT_INCOMPLETE, each field the request got wrong, with a message to show beside it. |
Details |
What else the code reports, as a JsonElement. Its shape depends on the code; see Errors. |
RequestId |
The X-Request-Id response header, for support. |
RetryAfter |
The Retry-After header, when the server sent one. |
RateLimit |
The rate limit headers, when the server sent them. |
Other failures throw other exceptions, all KiroraExceptions:
KiroraConnectionException: no complete response, such as a network error, or the connection dropping while the body was read.IsTimeoutis true when an attempt took longer than its timeout.KiroraResponseException: a success status with a body the library can’t use, such as HTML from a proxy.OperationCanceledExceptionwhen you cancel a call.
Retries and timeouts
Every request goes through one retry loop, which repeats a call only when repeating it is safe. Whether an operation is safe to repeat comes from the API’s spec, not from each method:
- 429 is always retried, as are connections never made, such as a failed DNS lookup: the server did nothing.
- 5xx and other network failures are retried only when a repeat can’t cause a duplicate: reads, operations that converge on the same result, and writes with an idempotency key, which the library makes per call wherever the endpoint takes one and reuses on each retry.
IDEMPOTENCY_KEY_IN_USE(409) is retried when the call has a key: an earlier attempt, such as one that timed out, is still running, and waiting gets its response.- Other 4xx errors are never retried, including the other idempotency
409s,IDEMPOTENCY_KEY_REUSEDandIDEMPOTENCY_KEY_OUTCOME_UNKNOWN. - Backoff: exponential with jitter, capped at
MaxRetryDelay. When the server sendsRetry-After, the retry never comes sooner. - Bounded: at most
MaxRetriesretries (default 3), then the last error is thrown. A retry sends the same body and idempotency key as the first attempt. - Timeout:
Timeout(default 30 seconds) applies to each attempt, so a call that retries can take longer in total. For an overall deadline, use the cancellation token. A cancelled call is never retried.
Per-call options
A RequestOptions overrides the client’s settings for one call, and has two settings of its own:
| Property | Description |
|---|---|
IdempotencyKey |
On methods that create, send or record something. |
Workspace |
Partner keys only: the tenant to act in for this call. |
Timeout, MaxRetries |
Override the client’s settings for this call. |
OnResponse |
Called with the response’s details, a KiroraResponse. |
KiroraResponse holds the response’s RequestId, its RateLimit, and IdempotencyReplay, which is true when an earlier request with the same key already did the work and this is its stored response:
KiroraResponse? response = null;
var contact = await client.Contacts.GetAsync(ContactRef.Id(contactId), new RequestOptions { OnResponse = r => response = r });
Console.WriteLine(response?.RequestId); // quote this to Kirora supportVerify webhooks
Verify each webhook against the raw request body, before parsing it: parsed and re-serialized JSON won’t match the signature. Webhook.VerifyAsync(secret, request) reads the body and the X-Webhook-* headers from an ASP.NET Core HttpRequest, checks the signature in constant time, rejects a timestamp more than 5 minutes from now, and accepts any of the signatures sent while a secret rotation overlaps:
app.MapPost("/webhooks/kirora", async (HttpRequest request, ILogger<Program> logger) =>
{
try
{
var webhook = await Webhook.VerifyAsync(builder.Configuration["KIRORA_WEBHOOK_SECRET"]!, request);
// Delivery is at-least-once: deduplicate on webhook.EventId, then parse webhook.Body.
logger.LogInformation("{Event} {EventId}", webhook.Event, webhook.EventId);
return Results.Ok();
}
catch (WebhookVerificationException e)
{
logger.LogWarning("Rejected a webhook: {Reason}", e.Reason);
return Results.Unauthorized();
}
});e.Reason says why one was rejected: InvalidTimestamp, InvalidHeaders, SignatureMismatch (usually the wrong secret, or a body that was read and changed first), TimestampOutsideTolerance (a replay, or your server’s clock is out of sync) or BodyTooLarge (over 10 MiB). Pass new WebhookOptions { Tolerance = TimeSpan.FromMinutes(10) } to change the replay window.
If your framework has already read the body, use Webhook.ReadHeaders() and Webhook.VerifySignature() with the raw bytes instead, then take the event type and id from the verified body’s eventType and eventId: the signature doesn’t cover the headers. webhook.Event is a WebhookEvent, with values such as WebhookEvent.MessageDelivered; treat the type as open, because a * subscription receives types added later. See Webhooks.
Partner workspaces
With a partner key, act in one of your tenants’ workspaces by its externalId, with client.ForWorkspace(), or with Workspace on the client’s options or on a single call. Each is sent as the Kirora-Workspace header; a call’s option overrides the client’s. An empty externalId is refused rather than acting in your own workspace.
var tenant = client.ForWorkspace("tenant-42");
var contact = await tenant.Contacts.GetAsync(ContactRef.Id(contactId));Manage the workspaces themselves with client.Workspaces. DeleteAsync() takes effect after a grace period, which CancelDeletionAsync() stops.
To embed Kirora’s segment or email builder in your app, create a session for the tenant on your server and give its token to the browser. A session lasts 15 minutes.
var session = await client.ForWorkspace("tenant-42").EmbedSessions.CreateAsync(new CreateEmbedSessionInput
{
Components = [EmbedComponent.EmailBuilder],
});Sign tokens for the web SDK
The web SDK signs users in with a token from your server. UserToken.Create(secret, userId, lifetime) signs one:
var token = UserToken.Create(builder.Configuration["KIRORA_SDK_TOKEN_SECRET"]!, user.Id, UserToken.DefaultLifetime);secret is the workspace’s SDK token secret, from Developer → SDK in the dashboard; it never leaves your server. userId is your own id for the user, their contact’s externalId. UserToken.DefaultLifetime is an hour; pass another TimeSpan in whole seconds, up to Kirora’s limit of 24 hours. It needs no client and no API key. The web SDK’s setup has the whole route.
Other endpoints
For an operation without a method, client.RequestAsync<T>() deserializes the whole JSON body, envelope included, and client.RequestAllAsync<T>() pages like the services’ AllAsync() methods:
public record Segment(string Id, string Name);
public record SegmentResponse(Segment Data);
var response = await client.RequestAsync<SegmentResponse>(HttpMethod.Get, $"/v1/segments/{Uri.EscapeDataString(segmentId)}");
await foreach (var segment in client.RequestAllAsync<Segment>("/v1/segments"))
{
// ...
}For a large body, such as an export to stream to a file, client.RequestRawAsync() returns the HttpResponseMessage with its body unread; dispose of it when done. An endpoint newer than your version of the library is retried as a write only if you pass an IdempotencyKey.
Test your code
To test code that calls Kirora, give the client an HttpClient whose handler answers with canned JSON, and turn retries off so a failure shows at once:
class StubHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct) =>
Task.FromResult(request.Method == HttpMethod.Get && request.RequestUri!.AbsolutePath == "/v1/lists/beta"
? new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("""{"data":{"id":"beta","name":"Beta testers"}}""") }
: new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("""{"error":{"code":"NOT_FOUND","message":"no such route"}}""") });
}
var client = new KiroraClient("test-key", new KiroraClientOptions
{
HttpClient = new HttpClient(new StubHandler()) { BaseAddress = new Uri("https://api.kirora.test") },
MaxRetries = 0,
});Each service is also an interface, such as IContactsService, so you can mock the calls your code makes instead.