Skip to main content

BaZi API - Official Python SDK (bazi-api-sdk)

Version Python CI PyPI Release Python Versions PyPI Package License: MIT

Official Python SDK for the BaZi API Platform — the enterprise-grade Chinese Four Pillars of Destiny (八字) astrological calculation engine and real-time webhook infrastructure.

What's New in v1.1.0:

  • Programmatic Webhook Management: Register, list, update, and test webhook endpoints directly with your API Key (client.webhooks.create(...), client.webhooks.list(), client.webhooks.test(...)).
  • Secure Outbound Webhook Handling: Constant-time verification (hmac.compare_digest) with anti-replay attack timestamp tolerance (construct_webhook_event).
  • Typed Webhook Models: Dataclasses for WebhookSubscription, WebhookDeliveryLog, and WebhookEvent.

Installation

pip install --upgrade bazi-api-sdk

Quick Start (BaZi Calculation)

Grab your API key from the BaZi API Dashboard and start calculating:

from bazi import BaziClient, BaziError

# Initialize client with your API key
client = BaziClient(api_key="bazi_live_your_api_key_here")

try:
    chart = client.calculate(
        birth_date="1998-08-12",
        birth_time="10:30",
        gender="male",
        timezone="Asia/Shanghai",
        language="en"
    )

    print("Four Pillars:")
    print(f"  Year : {chart.pillars.year}")
    print(f"  Month: {chart.pillars.month}")
    print(f"  Day  : {chart.pillars.day} (Day Master: {chart.heavenly_stems.day_stem})")
    print(f"  Hour : {chart.pillars.hour}")

    print(f"\nDominant Element: {chart.analysis.strongest_element}")
    print(f"Chinese Zodiac  : {chart.zodiac.animal}")

except BaziError as e:
    print(f"Calculation failed: {e}")

Programmatic Webhook Management

Manage your outbound webhook subscriptions using your API Key:

from bazi import BaziClient

client = BaziClient(api_key="bazi_live_your_api_key_here")

# 1. Register an endpoint
sub = client.webhooks.create(
    url="https://yourapp.com/api/webhooks/bazi",
    events=["daily.bazi_shift", "solar_term.changed"],
    description="Production astrology push server"
)
print("Registered Webhook ID:", sub.id)
print("Signing Secret:", sub.secret) # Store safely in your .env

# 2. List all endpoints
all_subs = client.webhooks.list()
for item in all_subs:
    print(item.id, item.url, item.events, item.is_active)

# 3. Trigger a live test ping
client.webhooks.test(sub.id)
print("Test ping dispatched to", sub.url)

# 4. View delivery logs
logs = client.webhooks.get_logs(sub.id)
for log in logs:
    print(log.event, log.status, log.status_code, log.created_at)

Secure Webhook Receiver (FastAPI / Flask)

Protect against timing attacks and replay attacks with automatic event construction:

FastAPI Example:

from fastapi import FastAPI, Request, HTTPException, status
from bazi import construct_webhook_event, WebhookVerificationError
import os

app = FastAPI()
WEBHOOK_SECRET = os.environ.get("BAZI_WEBHOOK_SECRET")

@app.post("/api/webhooks/bazi")
async def handle_bazi_webhook(request: Request):
    payload = await request.body()
    signature = request.headers.get("x-bazi-signature")
    timestamp = request.headers.get("x-bazi-timestamp")

    try:
        event = construct_webhook_event(
            payload=payload,
            signature=signature,
            secret=WEBHOOK_SECRET,
            timestamp=timestamp,
            tolerance=300 # 5 minutes replay protection window
        )
    except WebhookVerificationError as err:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(err))

    # Process verified event
    if event.event == "daily.bazi_shift":
        pillar = event.data.get("dayPillar")
        zodiac = event.data.get("zodiac")
        print(f"Daily BaZi Shift: Stem={pillar['gan']} Branch={pillar['zhi']} Zodiac={zodiac}")

    elif event.event == "solar_term.changed":
        term = event.data.get("solarTerm")
        print(f"Solar Term Transition: {term}")

    return {"received": True}

AI Agent & LangChain Function Calling

from langchain.tools import tool
from bazi import BaziClient

client = BaziClient(api_key="bazi_live_your_api_key")

@tool
def calculate_bazi(birth_date: str, birth_time: str, gender: str, timezone: str = "Asia/Shanghai") -> dict:
    """Calculates Chinese Four Pillars of Destiny (BaZi) chart."""
    return client.calculate(
        birth_date=birth_date,
        birth_time=birth_time,
        gender=gender,
        timezone=timezone
    ).to_dict()

License

MIT License © Md. Nasir Uddin Shoyas

Release files for bazi-api-sdk 2.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bazi-api-sdk 2.0.1
File Size Uploaded
bazi_api_sdk-2.0.1.tar.gz 16.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for bazi-api-sdk 2.0.1
File Interpreter ABI Platform
bazi_api_sdk-2.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 31.0 kB

Release files / bazi_api_sdk-2.0.1.tar.gz

Download URL bazi_api_sdk-2.0.1.tar.gz
Size 16.2 kB
Tags Source
SHA-256 checksum
How to use checksums
f8d767ab0b82f25e45baecc14ce6cc66337f1f53d50c5fac04f43c45ad23d3eb
BLAKE2b-256 checksum
How to use checksums
e8c10f7589a7b9af4a5cff1fbc4e3fcf3686cd167f71c1a9f60b74fbdeec2fcd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / bazi_api_sdk-2.0.1-py3-none-any.whl

Download URL bazi_api_sdk-2.0.1-py3-none-any.whl
Size 14.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a698af4a03821268de1d2dc0934cf0ea4a3de4833f2dca2538e2cf9efa449817
BLAKE2b-256 checksum
How to use checksums
1ee75bb3c5882eec59b7bbff6d729d986342d19ef20769cb5f784ca9888bccb3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release history Release notifications | RSS feed

2.0.2

2 release files

This release

2.0.1 This release

2 release files

2.0.0

2 release files

1.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page