# Ruby SDK

Install the 96Astro API gem, make your first call, handle errors and retries, create PDF and audio reports, and verify webhooks in Ruby and Rails.

`astro96` is the official client for Ruby 3.0 and later. 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 error class that carries the API's error `code`. It has no dependencies: each method takes a Hash (or a JSON string) and returns the parsed response.

## Install

```bash
gem install astro96
```

Or in your Gemfile: `gem "astro96"`.

## 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 an environment variable or Rails credentials.

```ruby
require "astro96"

astro = Astro96::Client.new(api_key: ENV.fetch("ASTRO_API_KEY"))
# Optional: base_url:, max_retries: (default 3)
```

## Your first call

Every capability is a method named after its id in snake_case: `planet-positions` is `planet_positions`, `daily-panchang` is `daily_panchang`.

```ruby
answer = astro.planet_positions(
  datetime: "1990-10-18T14:30:00", timezone: "Asia/Kolkata", latitude: 28.6139, longitude: 77.209
)
answer["data"]                    # the result
answer["meta"]["credits_used"]    # what it cost
```

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

```ruby
astro.call("panchang", "daily-panchang", { datetime: "2026-11-19T06:00:00", timezone: "Asia/Kolkata", latitude: 28.6139, longitude: 77.209 })
```

## Errors

An error answer raises `Astro96::Error` with `status` (HTTP), `code` (the API's error code) and `body` (the raw answer):

```ruby
begin
  astro.planet_positions(body)
rescue Astro96::Error => e
  case
  when e.status == 422 then # invalid input: e.body names the field
  when e.code == "quota_exhausted" then # out of credits
  else raise
  end
end
```

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 raised at once.

A connection failure (no answer at all) raises the usual `Net::*` or `SocketError` exception and is not retried by the client, because it cannot know whether the call reached us. The client waits up to 180 s for an answer.

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

```ruby
require "net/http"

birth = { datetime: "1990-10-18T14:30:00", timezone: "Asia/Kolkata", latitude: 28.6139, longitude: 77.209 }
job = astro.create_pdf_job(capability: "report-career", input: birth, branding: { brand_name: "Shree Jyotish Kendra" })["data"]
while %w[queued running].include?(job["status"])
  sleep 3
  job = astro.get_job(job["id"])["data"]
end
if job["status"] == "succeeded"
  File.binwrite("career.pdf", Net::HTTP.get(URI(job["download_url"])))
else
  warn job["error"].inspect # failed: nothing was charged
end
```

`create_audio_job` 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. In Rails, run this in a background job (Active Job, Sidekiq), or receive the `job.succeeded` [webhook](#webhooks) instead of polling.

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

```ruby
require "openssl"

def valid_webhook?(request, secret)
  id = request.headers["Astro-Webhook-Id"].to_s
  ts = request.headers["Astro-Webhook-Timestamp"].to_s
  sig = request.headers["Astro-Signature"].to_s
  return false unless ts.match?(/\A\d+\z/) && (Time.now.to_i - ts.to_i).abs <= 300
  expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{id}.#{ts}.#{request.raw_post}")
  sig.split(",").map(&:strip).any? { |p| p.start_with?("v1=") && OpenSSL.secure_compare(expected, p.delete_prefix("v1=")) }
end
```

`request.raw_post` is the raw body in Rails (in Sinatra, `request.body.read`). 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 and licence (MIT): [RubyGems](https://rubygems.org/gems/astro96) or the [download](https://96astroapi.com/downloads/sdk/astro96-ruby.zip).
