โ† Recipes

Build a Gun Milan score widget behind your own endpoint

A matching widget needs a score out of 36, eight bars and a manglik line. Put a thin route of your own between the browser and the API: it keeps the key server-side and the payload small.

You build
POST /api/gun-milan on your server, returning widget-ready JSON
Code
Node.js, Python - no SDK, runnable as shown

Updated

Shape of the widget

POST /v1/compatibility takes two birth inputs and returns total (score, max 36, a bucket label), eight koots with their own maxima (1, 2, 3, 4, 5, 6, 7, 8 - they sum to 36), match_percentage, a manglik_match block and slotting. A widget uses about a third of that. Doing the trimming on your server means the browser never sees the API key and never depends on fields you did not choose to expose.

The route

One function does the call and the trimming; the same file serves it as POST /api/gun-milan when started with serve, and otherwise prints a text preview of the bars:

gun-milan-widget.mjs

Node.js
// gun-milan-widget.mjs - node gun-milan-widget.mjs [serve]
import { createServer } from "node:http";

const API = process.env.ASTRONODE_API_URL ?? "https://api.astronode.dev";
const KEY = process.env.ASTRONODE_API_KEY; // the browser never sees this

const LABELS = { varna: "Varna", vashya: "Vashya", tara: "Tara", yoni: "Yoni",
  graha_maitri: "Graha Maitri", gana: "Gana", bhakoot: "Bhakoot", nadi: "Nadi" };

// Everything the widget draws, and nothing else.
export const gunMilanWidget = async (person_a, person_b, genders) => {
  const res = await fetch(`${API}/v1/compatibility`, {
    method: "POST",
    headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json" },
    body: JSON.stringify(genders ? { person_a, person_b, genders } : { person_a, person_b }),
  });
  const body = await res.json();
  if (!res.ok) return { status: res.status, error: body.error.code };
  const d = body.data;
  return {
    score: d.total.score, max: d.total.max, bucket: d.total.bucket,
    bars: d.koots.map((k) => ({ label: LABELS[k.name] ?? k.name, score: k.score, max: k.max,
      pct: Math.round((100 * k.score) / k.max), note: k.cancellation_note || undefined })),
    manglik: d.manglik_match.status,
    groom: d.slotting.groom,
  };
};

if (process.argv[2] === "serve") {
  // POST /api/gun-milan { person_a, person_b, genders? } -> widget JSON
  createServer(async (req, res) => {
    if (req.method !== "POST" || req.url !== "/api/gun-milan") return res.writeHead(404).end();
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const { person_a, person_b, genders } = JSON.parse(raw);
    const out = await gunMilanWidget(person_a, person_b, genders);
    res.writeHead(out.error ? out.status : 200, { "content-type": "application/json" });
    res.end(JSON.stringify(out));
  }).listen(Number(process.env.PORT ?? 3000));
} else {
  const a = { date: "1973-04-24", time: "17:25:00", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 };
  const b = { date: "1976-12-22", time: "06:42:00", tz_offset_minutes: 330, lat: 28.6139, lng: 77.209 };
  const w = await gunMilanWidget(a, b);
  // A terminal preview of what the component draws from that JSON.
  console.log(`${w.score}/${w.max} ${w.bucket} | manglik: ${w.manglik} | groom slot: ${w.groom}`);
  for (const bar of w.bars) {
    console.log(`${bar.label.padEnd(13)} ${bar.score}/${bar.max}`.padEnd(19), "#".repeat(bar.pct / 10).padEnd(10, "."));
  }
}

node gun-milan-widget.mjs

text
34/36 Excellent | manglik: compatible | groom slot: person_a
Varna         1/1   ##########
Vashya        2/2   ##########
Tara          3/3   ##########
Yoni          2/4   #####.....
Graha Maitri  5/5   ##########
Gana          6/6   ##########
Bhakoot       7/7   ##########
Nadi          8/8   ##########

Started with serve and called with the same two people plus "genders": { "person_a": "female", "person_b": "male" }, the route returns:

curl -X POST localhost:3000/api/gun-milan -d '{...}'

json
{"score":34,"max":36,"bucket":"Excellent","bars":[{"label":"Varna","score":1,"max":1,"pct":100},{"label":"Vashya","score":2,"max":2,"pct":100},{"label":"Tara","score":3,"max":3,"pct":100},{"label":"Yoni","score":2,"max":4,"pct":50},{"label":"Graha Maitri","score":5,"max":5,"pct":100},{"label":"Gana","score":6,"max":6,"pct":100},{"label":"Bhakoot","score":7,"max":7,"pct":100},{"label":"Nadi","score":8,"max":8,"pct":100}],"manglik":"compatible","groom":"person_b"}

Who is the groom: the genders field

Part of the matching is directional - the Varna and Gana koots, and which partner the manglik rules call the boy - so the two people are not interchangeable. Without genders the API reads person_a as the groom and says so: "slotting": {"groom": "person_a", "basis": "order"}. With genders it slots by them - above, groom flipped to person_b and basis to gender. For this pair the score is 34 either way, but the manglik note changes from describing the girl's cancelled Mars to the boy's. If your form asks for gender, pass it; if it does not, label the two inputs so users know which slot they are filling.

Turning a 400 into form errors

Two kinds of 400 VALIDATION_ERROR reach a form. A value that breaks the schema ("6:42") comes back with details[], each naming the field in instancePath. A value that passes the schema but not the engine ("25:10" matches HH:mm) comes back with a message only. Handle both:

gun_milan_form.py

Python 3.9+
# gun_milan_form.py - turn a 400 into per-field form errors (3.9+, standard library)
import json, os, urllib.error, urllib.request

API = os.environ.get("ASTRONODE_API_URL", "https://api.astronode.dev")
KEY = os.environ["ASTRONODE_API_KEY"]

def score(person_a, person_b):
    req = urllib.request.Request(API + "/v1/compatibility", method="POST",
                                 data=json.dumps({"person_a": person_a, "person_b": person_b}).encode(),
                                 headers={"Authorization": "Bearer " + KEY,
                                          "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req) as r:
            d = json.load(r)["data"]
            return {"score": d["total"]["score"], "max": d["total"]["max"]}
    except urllib.error.HTTPError as e:
        err = json.load(e)["error"]
        if err["code"] != "VALIDATION_ERROR":
            raise
        # Schema failures list each field in details[].instancePath; a value that
        # passes the schema but not the engine (hour 25) has a message only.
        fields = {i["instancePath"]: i["message"] for i in err.get("details", [])}
        return {"form_errors": fields or {"": err["message"]}}

a = {"date": "1973-04-24", "time": "17:25:00", "tz_offset_minutes": 330, "lat": 19.076, "lng": 72.8777}
b = {"date": "1976-12-22", "time": "06:42:00", "tz_offset_minutes": 330, "lat": 28.6139, "lng": 77.209}
print(score(a, dict(b, time="6:42")))
print(score(a, dict(b, time="25:10")))
print(score(a, b))

Output:

text
{'form_errors': {'/person_b/time': 'time must be HH:mm or HH:mm:ss (24h)'}}
{'form_errors': {'': 'hour must be 0..23, got 25'}}
{'score': 34, 'max': 36}

Neither 400 counts toward your monthly quota - only responses below 400 do - so validating in the browser first is about user experience, not cost. Full error shapes are on the VALIDATION_ERROR page.

Before you launch

  • Cache by the pair. The result is deterministic, and a matrimony profile page gets viewed far more often than the two births change.
  • Scoring hundreds of candidate pairs for one profile is a job for POST /v1/compatibility/batch (up to 500 pairs per call, asynchronous), not a loop over this route.
  • Show bucket and max from the response instead of hard-coding thresholds, so your copy follows the engine.
  • /v1/compatibility needs the Hobby plan.

Questions

What do I end up with?
POST /api/gun-milan on your server, returning widget-ready JSON. The code is in Node.js and Python.
Which endpoints does this recipe call, and in what order?
2 endpoints, in this order: Kundli Matching (Ashtakoot Gun Milan) (POST /v1/compatibility), then Bulk Kundli Matching (POST /v1/compatibility/batch).