# Dart and Flutter SDK

Install astro96_api from pub.dev, make your first call, handle errors and retries, create PDF and audio reports, and verify webhooks in Dart; and how to use it safely with Flutter.

`astro96_api` is the official client for Dart 3 and later: servers (Dart Frog, Shelf, Serverpod), the command line, and every Flutter platform. It has a 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`. Each method takes the request as a `Map` (or a JSON string) and returns the parsed response. Its only dependency is `package:http`.

## Install

```bash
dart pub add astro96_api      # or: flutter pub add astro96_api
```

## Flutter: keep the key off the device

A secret key inside a Flutter app can be extracted by anyone who has the app. Use this package in your **backend** (a Dart server, a Cloud Function, or any server you run) and have the Flutter app call that backend with `package:http`. See [Platforms](https://96astroapi.com/docs/platforms.md).

## 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.

```dart
import 'dart:io';
import 'package:astro96_api/astro96_api.dart';

final astro = Astro96Client(apiKey: Platform.environment['ASTRO_API_KEY']!);
// Optional: baseUrl:, maxRetries: (default 3), timeout: (default 180 s), httpClient: (your own http.Client)
```

Create one client and reuse it; call `astro.close()` when you are done (it closes the HTTP client it created).

## Your first call

Every capability is a method named after its id in camelCase: `planet-positions` is `planetPositions`, `daily-panchang` is `dailyPanchang`.

```dart
final answer = await astro.planetPositions({
  'datetime': '1990-10-18T14:30:00',
  'timezone': 'Asia/Kolkata',
  'latitude': 28.6139,
  'longitude': 77.209,
});
final data = answer['data'];
final credits = answer['meta']['credits_used'];
```

Each request body and response is described on the capability's page in the [API reference](https://96astroapi.com/docs/reference). You can also call any capability by its family and id:

```dart
final answer = await astro.call('panchang', 'daily-panchang', {...});
```

## Errors

An error answer throws `Astro96Exception` with `status` (HTTP), `code` (the API's error code) and `body` (the raw answer):

```dart
try {
  await astro.planetPositions(birth);
} on Astro96Exception catch (e) {
  if (e.status == 422) {
    // invalid input: e.body names the field
  } else if (e.code == 'quota_exhausted') {
    // out of credits
  } else {
    rethrow;
  }
}
```

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 `maxRetries` (3) times, with the **same** key, so a retried call is never charged twice. Other errors are thrown at once.

A connection failure or a timeout (no answer at all) throws the `http` package's exception or a `TimeoutException`, 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).

```dart
import 'dart:io';
import 'package:http/http.dart' as http;

var job = (await astro.createPdfJob({
  'capability': 'report-career',
  'input': birth,
  'branding': {'brand_name': 'Shree Jyotish Kendra'},
}))['data'];
while (job['status'] == 'queued' || job['status'] == 'running') {
  await Future<void>.delayed(const Duration(seconds: 3));
  job = (await astro.getJob(job['id'] as String))['data'];
}
if (job['status'] == 'succeeded') {
  final pdf = await http.get(Uri.parse(job['download_url'] as String));
  await File('career.pdf').writeAsBytes(pdf.bodyBytes);
}
```

`createAudioJob` 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. This uses [`package:crypto`](https://pub.dev/packages/crypto).

```dart
import 'dart:convert';
import 'package:crypto/crypto.dart';

bool validWebhook(String id, String timestamp, String signature, List<int> rawBody, String secret) {
  final ts = int.tryParse(timestamp);
  if (ts == null || (DateTime.now().millisecondsSinceEpoch ~/ 1000 - ts).abs() > 300) return false;
  final mac = Hmac(sha256, utf8.encode(secret)).convert([...utf8.encode('$id.$timestamp.'), ...rawBody]).toString();
  for (final part in signature.split(',').map((p) => p.trim())) {
    if (!part.startsWith('v1=')) continue;
    final given = part.substring(3);
    if (given.length != mac.length) continue;
    var diff = 0;
    for (var i = 0; i < mac.length; i++) {
      diff |= mac.codeUnitAt(i) ^ given.codeUnitAt(i); // constant time
    }
    if (diff == 0) return true;
  }
  return false;
}
```

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.
- Package, API docs and licence (MIT): [pub.dev/packages/astro96_api](https://pub.dev/packages/astro96_api).
