BaZi API - Official Python SDK (bazi-api-sdk)
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, andWebhookEvent.
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.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| bazi_api_sdk-2.0.2.tar.gz | 16.2 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| bazi_api_sdk-2.0.2-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 31.0 kB
Release files / bazi_api_sdk-2.0.2.tar.gz
| Download URL | bazi_api_sdk-2.0.2.tar.gz |
|---|---|
| Size | 16.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
965eb1c34769fe14251aa5313395b337b61f20fe927ef14196c6fd3c5835fae7
|
|
BLAKE2b-256 checksum How to use checksums |
3d1c5b896acdbceb588a46f902d9994be088e16aab5bd12aaf50ffe3fa7f4e4b
|
| 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.2-py3-none-any.whl
| Download URL | bazi_api_sdk-2.0.2-py3-none-any.whl |
|---|---|
| Size | 14.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9393622fd1c93f81f37a6238279f19fad6afdde20ef1df3cd782e373d7d85735
|
|
BLAKE2b-256 checksum How to use checksums |
7824811a5d223b13336ff044cb429dfac7481f2dad14db22be91d0aafad704c0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|