# Ashtakavarga in Rust: axum, reqwest and typed serde structs

> Rust gives you a compile-time check on the shape of the response, which suits a numeric endpoint like ashtakavarga: seven planets, twelve signs, a fixed table. This page wires an axum route to `POST /v1/ashtakavarga` through one shared `reqwest::Client` and turns the per-planet tables into per-sign strength.

Source: https://astronode.dev/integrations/rust · Updated: 2026-12-05

**How this page was verified:** **The Rust was not compiled or run** - there is no Rust toolchain on the build machine. The identical request (same URL, headers and JSON body) and the same per-sign summation were executed in Node 24 against the in-memory API; the totals below are from that run and were cross-checked against `POST /v1/sarvashtakavarga`, which returned the same twelve numbers.

## Dependencies and state

`Cargo.toml`:

```toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1", features = ["derive"] }
```

The key comes from `ASTRONODE_API_KEY` at startup and lives in the router state next to one `reqwest::Client`. The client holds a connection pool; building one per request throws the pool away and pays a new TLS handshake on every call.

## Typed structs and the handler

`src/main.rs`:

```rust
use std::{env, time::Duration};

use axum::{extract::State, http::StatusCode, routing::post, Json, Router};
use serde::{Deserialize, Serialize};

const SIGNS: [&str; 12] = [
    "Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
    "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces",
];

#[derive(Clone)]
struct AppState {
    http: reqwest::Client,
    base: String,
    key: String,
}

#[derive(Serialize, Deserialize)]
struct Birth {
    date: String,
    time: String,
    tz_offset_minutes: i32,
    lat: f64,
    lng: f64,
}

#[derive(Deserialize)]
struct Envelope<T> {
    data: Option<T>,
    error: Option<ApiError>,
}

#[derive(Deserialize)]
struct ApiError {
    code: String,
    message: String,
}

#[derive(Deserialize)]
struct Ashtakavarga {
    charts: Vec<PlanetChart>,
}

#[derive(Deserialize)]
struct PlanetChart {
    planet: String,
    bindus_per_sign: [u8; 12], // index 0 = Aries
    total: u16,
}

#[derive(Serialize)]
struct SignStrength {
    sign: &'static str,
    bindus: u16,
}

#[derive(Serialize)]
struct Summary {
    planet_totals: Vec<(String, u16)>,
    signs: Vec<SignStrength>,
    total: u16,
}

type ApiResult<T> = Result<Json<T>, (StatusCode, String)>;

async fn ashtakavarga(State(st): State<AppState>, Json(birth): Json<Birth>) -> ApiResult<Summary> {
    let res = st
        .http
        .post(format!("{}/v1/ashtakavarga", st.base))
        .bearer_auth(&st.key)
        .json(&birth)
        .send()
        .await
        .map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?;
    let status = res.status();
    let envelope: Envelope<Ashtakavarga> = res
        .json()
        .await
        .map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?;

    let data = match (envelope.data, envelope.error) {
        (Some(data), _) => data,
        (None, Some(e)) => {
            let code = if status.is_client_error() { StatusCode::BAD_REQUEST } else { StatusCode::BAD_GATEWAY };
            return Err((code, format!("{}: {}", e.code, e.message)));
        }
        (None, None) => return Err((StatusCode::BAD_GATEWAY, format!("empty envelope ({status})"))),
    };

    let mut per_sign = [0u16; 12];
    for chart in &data.charts {
        for (i, n) in chart.bindus_per_sign.iter().enumerate() {
            per_sign[i] += u16::from(*n);
        }
    }

    Ok(Json(Summary {
        planet_totals: data.charts.iter().map(|c| (c.planet.clone(), c.total)).collect(),
        signs: SIGNS.into_iter().zip(per_sign).map(|(sign, bindus)| SignStrength { sign, bindus }).collect(),
        total: per_sign.iter().sum(),
    }))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let state = AppState {
        http: reqwest::Client::builder().timeout(Duration::from_secs(15)).build()?,
        base: env::var("ASTRONODE_BASE_URL").unwrap_or_else(|_| "https://api.astronode.dev".into()),
        key: env::var("ASTRONODE_API_KEY")?, // fail at startup, not on the first request
    };
    let app = Router::new().route("/ashtakavarga", post(ashtakavarga)).with_state(state);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, app).await?;
    Ok(())
}
```

`[u8; 12]` is deliberate: if the array ever arrived with a different length, decoding fails with an error instead of producing a shifted sign table. Unknown fields such as `request_id` and `meta` are ignored by serde's default, so new fields in the response do not break the build - do not add `#[serde(deny_unknown_fields)]` to response types.

## The numbers

For a birth on 2 November 1985 at 21:10 in Berlin (`tz_offset_minutes: 60`), the per-planet totals were Sun 48, Moon 49, Mars 39, Mercury 54, Jupiter 56, Venus 52 and Saturn 39 - the fixed totals of the classical tables, which is a useful assertion in a test. Summed per sign:

*Bindus per sign (sum of the seven planet tables), total 337*

| Strongest | Bindus | Weakest | Bindus |
| --- | --- | --- | --- |
| Cancer | 37 | Aquarius | 20 |
| Aries | 35 | Capricorn | 24 |
| Leo | 33 | Gemini / Sagittarius / Pisces | 25 |

If all you need is that per-sign row, `POST /v1/sarvashtakavarga` returns it directly (it returned the same twelve values and `total: 337`). Call `/v1/ashtakavarga` when you also need which planet contributed where - for transit scoring, for example ([ashtakavarga calculation](https://astronode.dev/guides/ashtakavarga-calculation)).

## The mistake that bites first: reqwest::blocking inside axum

- Copying a `reqwest::blocking::get` example into an async handler compiles, then panics at runtime: the blocking client starts its own Tokio runtime, and Tokio refuses to create or drop a runtime inside one that is already driving your handler. Use the async `reqwest::Client` and `.await` it.
- If you do have blocking work - a CPU-heavy render of the chart - move it to `tokio::task::spawn_blocking`, not the HTTP call.
- `tz_offset_minutes` is an `i32` because it is negative west of Greenwich; a `u16` decodes Berlin and then fails for New York. `lat` sent as a JSON string returned `400 VALIDATION_ERROR` - `f64` in the struct rules that out.

> **Note:** Both `POST /v1/ashtakavarga` and `POST /v1/sarvashtakavarga` need the Hobby plan or above.

## Questions

**Which AstroNode endpoints does the Rust (axum + reqwest) example call?**

2 endpoints: Ashtakavarga (`POST /v1/ashtakavarga`); Sarvashtakavarga (`POST /v1/sarvashtakavarga`).

**Was the Rust (axum + reqwest) code on this page actually run?**

**The Rust was not compiled or run** - there is no Rust toolchain on the build machine. The identical request (same URL, headers and JSON body) and the same per-sign summation were executed in Node 24 against the in-memory API; the totals below are from that run and were cross-checked against `POST /v1/sarvashtakavarga`, which returned the same twelve numbers.

## Endpoints

- [`POST /v1/ashtakavarga`](https://astronode.dev/capabilities/vedic/ashtakavarga) - Ashtakavarga API
- [`POST /v1/sarvashtakavarga`](https://astronode.dev/capabilities/vedic/sarvashtakavarga) - Sarvashtakavarga API
