# .NET SDK

Install the 96Astro API client for .NET from NuGet, make your first call, handle errors and retries, create PDF and audio reports, and verify webhooks.

`Astro96.Api` is the official client for .NET 8 and later (C#, F#, VB). It has an async method for every capability in the [API reference](https://96astroapi.com/docs/reference), PDF and audio job methods, automatic retries with idempotency keys, and an exception that carries the API's error `code`. It has no dependencies: requests and responses are JSON strings, so you parse them with `System.Text.Json` or the library you already use.

## Install

```bash
dotnet add package Astro96.Api
```

## Create a client

Get a key in the [dashboard](https://96astroapi.com/dashboard): a sandbox key (`sk_test_…`) is free and runs real calculations, a live key (`sk_live_…`) uses credits. Keep it on your server, in configuration or a secret store, never in a client app.

```csharp
using Astro96;

var astro = new Astro96Client(Environment.GetEnvironmentVariable("ASTRO_API_KEY")!);
// Optional: baseUrl, maxRetries (default 3), and your own HttpClient (for example from IHttpClientFactory)
```

Create one client and reuse it (register it as a singleton in ASP.NET Core). Passing your own `HttpClient` lets you set its timeout; the default `HttpClient` timeout is 100 seconds.

## Your first call

Every capability is a method named after its id in PascalCase with `Async`: `planet-positions` is `PlanetPositionsAsync`, `daily-panchang` is `DailyPanchangAsync`. Pass the request body as JSON; the answer is the JSON response.

```csharp
using System.Text.Json;

var body = JsonSerializer.Serialize(new { datetime = "1990-10-18T14:30:00", timezone = "Asia/Kolkata", latitude = 28.6139, longitude = 77.209 });
string json = await astro.PlanetPositionsAsync(body);
using var doc = JsonDocument.Parse(json);
var data = doc.RootElement.GetProperty("data");
var credits = doc.RootElement.GetProperty("meta").GetProperty("credits_used").GetInt32();
```

Each request body and response is described on the capability's page in the [API reference](https://96astroapi.com/docs/reference). Any capability can also be called by its family and id, and every method takes a `CancellationToken`:

```csharp
string json = await astro.CallAsync("panchang", "daily-panchang", body, cancellationToken);
```

## Errors

An error answer throws `Astro96Exception` with `Status` (HTTP), `Code` (the API's error code) and `Body` (the raw answer):

```csharp
try
{
    await astro.PlanetPositionsAsync(body);
}
catch (Astro96Exception e) when (e.Status == 422)
{
    // invalid input: e.Body names the field
}
catch (Astro96Exception e) when (e.Code == "quota_exhausted")
{
    // out of credits
}
```

Every code and what to do about it is in [Errors](https://96astroapi.com/docs/errors.md). Failed calls are never charged.

## Retries and idempotency

Each call sends an `Idempotency-Key`. When the API answers with an error it marks `retryable` (a rate limit or a brief outage), the client waits 0.5 s, 1 s and 2 s and tries again, up to 3 times, with the **same** key, so a retried call is never charged twice. Other errors are thrown at once.

A connection failure (no answer at all) is thrown as `HttpRequestException` or `TaskCanceledException` and is not retried by the client, because it cannot know whether the call reached us.

## PDF and audio reports

A [PDF report](https://96astroapi.com/docs/jobs-and-webhooks.md) or an [audio report](https://96astroapi.com/docs/audio-reports.md) is a job: create it, then poll it until `status` is `succeeded` and download the file from `download_url` (a signed link that needs no key).

```csharp
var request = JsonSerializer.Serialize(new
{
    capability = "report-career",
    input = new { datetime = "1990-10-18T14:30:00", timezone = "Asia/Kolkata", latitude = 28.6139, longitude = 77.209 },
    branding = new { brand_name = "Shree Jyotish Kendra" },
});
var job = JsonDocument.Parse(await astro.CreatePdfJobAsync(request)).RootElement.GetProperty("data");
while (job.GetProperty("status").GetString() is "queued" or "running")
{
    await Task.Delay(3000);
    job = JsonDocument.Parse(await astro.GetJobAsync(job.GetProperty("id").GetString()!)).RootElement.GetProperty("data");
}
if (job.GetProperty("status").GetString() == "succeeded")
{
    var pdf = await new HttpClient().GetByteArrayAsync(job.GetProperty("download_url").GetString());
    await File.WriteAllBytesAsync("career.pdf", pdf);
}
```

`CreateAudioJobAsync` takes the same request plus the audio options (`minutes`, `voice`, `tone`, `format` and more, in [Audio reports](https://96astroapi.com/docs/audio-reports.md)). Polling is free. Instead of polling you can receive the `job.succeeded` [webhook](#webhooks).

## Webhooks

A webhook carries `Astro-Webhook-Id`, `Astro-Webhook-Timestamp` and `Astro-Signature: v1=<hex>`. Verify it with the **raw** request body: compute HMAC-SHA256 of `{id}.{timestamp}.{body}` with your endpoint's secret (the whole `whsec_…` string), compare it in constant time with each `v1=` value, and refuse a timestamp more than 5 minutes off.

```csharp
using System.Security.Cryptography;
using System.Text;

static bool Verify(string id, string timestamp, string signature, byte[] rawBody, string secret)
{
    if (!long.TryParse(timestamp, out var ts) || Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ts) > 300) return false;
    var signed = Encoding.UTF8.GetBytes($"{id}.{timestamp}.").Concat(rawBody).ToArray();
    var expected = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), signed);
    foreach (var part in signature.Split(','))
    {
        var p = part.Trim();
        if (!p.StartsWith("v1=")) continue;
        try
        {
            if (CryptographicOperations.FixedTimeEquals(expected, Convert.FromHexString(p[3..]))) return true;
        }
        catch (FormatException) { }
    }
    return false;
}
```

In ASP.NET Core, read the raw body with `Request.EnableBuffering()` and a `MemoryStream` before any model binding. Answer `2xx` quickly and deduplicate on `Astro-Webhook-Id`. See [Jobs and webhooks](https://96astroapi.com/docs/jobs-and-webhooks.md#webhooks) for the events.

## Also on this platform

- Not wrapped by the client: [streaming](https://96astroapi.com/docs/ai-streaming-and-chat.md), [conversations](https://96astroapi.com/docs/ai-streaming-and-chat.md#conversations) and `.ics` export. Call them over plain HTTP with the same key.
- The [OpenAPI document](https://96astroapi.com/openapi/v1.json) works with NSwag or Kiota if you prefer typed models.
- Never ship a secret key in a desktop, MAUI or Blazor WebAssembly app: call your own backend. See [Platforms](https://96astroapi.com/docs/platforms.md).
- Package and licence (MIT): [NuGet](https://www.nuget.org/packages/Astro96.Api) or the [download](https://96astroapi.com/downloads/sdk/astro96-dotnet.zip).
