# Swift SDK

Add the 96Astro API Swift package, make your first call with async/await, handle errors and retries, create PDF and audio reports, and verify webhooks on a Swift server.

`Astro96` is the official Swift package, for Swift 5.9 and later on macOS 12+, iOS 15+ and Linux. 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 error that carries the API's error `code`. It has no dependencies: requests and responses are JSON strings, so you decode them with `JSONDecoder` or `JSONSerialization`.

## Install

In `Package.swift`:

```swift
dependencies: [
    .package(url: "https://github.com/96astro/astro96-swift.git", from: "0.2.0"),
],
targets: [
    .target(name: "YourApp", dependencies: [.product(name: "Astro96", package: "astro96-swift")]),
]
```

In Xcode: **File → Add Package Dependencies…** and paste `https://github.com/96astro/astro96-swift.git`.

## Keep the key off the device

A secret key inside an iOS or macOS app can be extracted by anyone who has the app. Use this package in **server-side Swift** (Vapor, Hummingbird) or a command-line tool, and have your app call your own backend. 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.

```swift
import Astro96
import Foundation

let astro = Astro96Client(apiKey: ProcessInfo.processInfo.environment["ASTRO_API_KEY"]!)
// Optional: baseURL:, maxRetries: (default 3)
```

## Your first call

Every capability is a method named after its id in camelCase: `planet-positions` is `planetPositions`, `daily-panchang` is `dailyPanchang`. Pass the request body as JSON; the answer is the JSON response.

```swift
let body = #"{"datetime":"1990-10-18T14:30:00","timezone":"Asia/Kolkata","latitude":28.6139,"longitude":77.209}"#
let json = try await astro.planetPositions(body)

let answer = try JSONSerialization.jsonObject(with: Data(json.utf8)) as! [String: Any]
let data = answer["data"]
let credits = (answer["meta"] as? [String: Any])?["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:

```swift
let json = try await astro.call("panchang", "daily-panchang", body)
```

## Errors

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

```swift
do {
    _ = try await astro.planetPositions(body)
} catch let e as Astro96Error where e.status == 422 {
    // invalid input: e.body names the field
} catch let e as Astro96Error where 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) throws the `URLError` and is not retried by the client, because it cannot know whether the call reached us. Each attempt waits up to 180 s.

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

```swift
struct Job: Decodable { let id: String; let status: String; let download_url: String? }
struct Envelope: Decodable { let data: Job }

let request = #"{"capability":"report-career","input":\#(body),"branding":{"brand_name":"Shree Jyotish Kendra"}}"#
var job = try JSONDecoder().decode(Envelope.self, from: Data(try await astro.createPdfJob(request).utf8)).data
while job.status == "queued" || job.status == "running" {
    try await Task.sleep(nanoseconds: 3_000_000_000)
    job = try JSONDecoder().decode(Envelope.self, from: Data(try await astro.getJob(job.id).utf8)).data
}
if job.status == "succeeded", let link = job.download_url, let url = URL(string: link) {
    let (pdf, _) = try await URLSession.shared.data(from: url)
    try pdf.write(to: URL(fileURLWithPath: "career.pdf"))
}
```

`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 with each `v1=` value, and refuse a timestamp more than 5 minutes off. `Crypto` comes from [swift-crypto](https://github.com/apple/swift-crypto) on Linux (the same API as CryptoKit on Apple platforms).

```swift
import Crypto
import Foundation

func validWebhook(id: String, timestamp: String, signature: String, rawBody: Data, secret: String) -> Bool {
    guard let ts = Int(timestamp), abs(Int(Date().timeIntervalSince1970) - ts) <= 300 else { return false }
    var signed = Data("\(id).\(timestamp).".utf8)
    signed.append(rawBody)
    let key = SymmetricKey(data: Data(secret.utf8))
    for part in signature.split(separator: ",").map({ $0.trimmingCharacters(in: .whitespaces) }) where part.hasPrefix("v1=") {
        let hex = part.dropFirst(3)
        guard hex.count % 2 == 0 else { continue }
        var bytes = [UInt8]()
        var i = hex.startIndex
        while i < hex.endIndex, let b = UInt8(hex[i..<hex.index(i, offsetBy: 2)], radix: 16) {
            bytes.append(b)
            i = hex.index(i, offsetBy: 2)
        }
        if HMAC<SHA256>.isValidAuthenticationCode(bytes, authenticating: signed, using: key) { return true }  // constant time
    }
    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.
- Source and licence (MIT): [github.com/96astro/astro96-swift](https://github.com/96astro/astro96-swift) or the [download](https://96astroapi.com/downloads/sdk/astro96-swift.zip). The package is built and tested on Linux; building for iOS and macOS is not part of our checks.
