# Java and Android SDK

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

`com.96astroapi:astro96-api` is the official client for Java 8 and later, and for Android. It has one 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 the library your app already uses (Jackson, Gson, org.json).

## Install

```xml title="Maven (pom.xml)"
<dependency>
  <groupId>com.96astroapi</groupId>
  <artifactId>astro96-api</artifactId>
  <version>VERSION</version>
</dependency>
```

```kotlin title="Gradle (build.gradle.kts)"
implementation("com.96astroapi:astro96-api:VERSION")
```

Replace `VERSION` with the latest release shown on [Maven Central](https://central.sonatype.com/artifact/com.96astroapi/astro96-api).

The Java package is `com.astro96` (a Java package name cannot start with a digit, so it differs from the Maven group).

## 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 your secret store.

```java
import com.astro96.Astro96Client;

Astro96Client astro = new Astro96Client(System.getenv("ASTRO_API_KEY"));
// Or: new Astro96Client(key, "https://api.96astroapi.com/v1", 3)  // base URL and retries
```

One client can be shared by all threads.

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

```java
String body = "{\"datetime\":\"1990-10-18T14:30:00\",\"timezone\":\"Asia/Kolkata\","
            + "\"latitude\":28.6139,\"longitude\":77.209}";
String json = astro.planetPositions(body);
// {"data": {...}, "meta": {"credits_used": 1, "request_id": "req_...", ...}}
```

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:

```java
String json = astro.call("panchang", "daily-panchang", body);
```

## Errors

An error answer throws `Astro96Client.ApiException` (an `IOException`) with the HTTP `status`, the API's `code` and the raw `body`:

```java
try {
    astro.planetPositions(body);
} catch (Astro96Client.ApiException e) {
    if (e.status == 422) { /* invalid input: e.body names the field */ }
    else if (e.code.equals("quota_exhausted")) { /* out of credits */ }
    else throw e;
}
```

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 an ordinary `IOException` and is not retried by the client, because it cannot know whether the call reached us. The client waits up to 10 s to connect and 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).

```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
JsonNode job = mapper.readTree(astro.createPdfJob("{\"capability\":\"report-career\",\"input\":" + body
        + ",\"branding\":{\"brand_name\":\"Shree Jyotish Kendra\"}}")).get("data");
while (job.get("status").asText().matches("queued|running")) {
    Thread.sleep(3000);
    job = mapper.readTree(astro.getJob(job.get("id").asText())).get("data");
}
if (job.get("status").asText().equals("succeeded")) {
    String url = job.get("download_url").asText();  // fetch it with any HTTP client, no key needed
} else {
    String why = job.get("error").toString();         // failed: nothing was charged
}
```

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

```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

static boolean verify(String id, String timestamp, String signature, byte[] rawBody, String secret) throws Exception {
    if (Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(timestamp)) > 300) return false;
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    mac.update((id + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8));
    byte[] expected = mac.doFinal(rawBody);
    for (String part : signature.split(",")) {
        part = part.trim();
        if (!part.startsWith("v1=")) continue;
        byte[] given = hex(part.substring(3));
        if (given != null && MessageDigest.isEqual(expected, given)) return true;
    }
    return false;
}

static byte[] hex(String s) {
    if (s.length() % 2 != 0) return null;
    byte[] out = new byte[s.length() / 2];
    for (int i = 0; i < out.length; i++) out[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);
    return out;
}
```

Answer `2xx` quickly and do the work afterwards; deduplicate on `Astro-Webhook-Id`. See [Jobs and webhooks](https://96astroapi.com/docs/jobs-and-webhooks.md#webhooks) for the events.

## Android

Do not put a secret key in an Android app: anyone can extract it. Have the app call your own backend (which can use this client) and let the backend call the API. See [Platforms](https://96astroapi.com/docs/platforms.md).

## 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 OpenAPI Generator if you prefer typed models.
- Source and licence (MIT): [Maven Central](https://central.sonatype.com/artifact/com.96astroapi/astro96-api) or the [download](https://96astroapi.com/downloads/sdk/astro96-java.zip).
