astrologybazi-api / USAGE_EXAMPLES.md
th
🎯 Rebrand to AstrologyBazi API v2.0
16eedb2
|
Raw History Blame Contribute Delete
10.8 kB
# 🔮 AstrologyBazi API - Usage Examples
## Quick Reference
**Base URL:** `https://sisithefox-astrologybazi-api.hf.space`
**Authentication:** Add header `x-api-key: your_api_key_here`
---
## Example 1: Basic BaZi Calculation (cURL)
```bash
curl -X POST "https://sisithefox-astrologybazi-api.hf.space/calculate-bazi" \
-H "Content-Type: application/json" \
-H "x-api-key: your_api_key_here" \
-d '{
"birth_date": "1990-01-15",
"birth_time": "08:30",
"gender": "male",
"is_lunar": false
}'
```
---
## Example 2: Python Integration
```python
import requests
API_URL = "https://sisithefox-astrologybazi-api.hf.space/calculate-bazi"
API_KEY = "your_api_key_here"
def get_bazi_chart(birth_date, birth_time, gender="male", is_lunar=False):
"""Get BaZi chart from API"""
headers = {
"Content-Type": "application/json",
"x-api-key": API_KEY
}
data = {
"birth_date": birth_date,
"birth_time": birth_time,
"gender": gender,
"is_lunar": is_lunar
}
response = requests.post(API_URL, headers=headers, json=data)
if response.status_code == 200:
result = response.json()
return result['data']
else:
raise Exception(f"API Error: {response.status_code} - {response.text}")
# Example usage
bazi_data = get_bazi_chart("1990-01-15", "08:30")
print("Day Master:", bazi_data['day_master']['gan'])
print("Element:", bazi_data['day_master']['element'])
print("\nFive Elements:")
for element, count in bazi_data['five_elements'].items():
print(f" {element}: {count}")
```
---
## Example 3: JavaScript/TypeScript Integration
```typescript
const API_URL = 'https://sisithefox-astrologybazi-api.hf.space/calculate-bazi';
const API_KEY = 'your_api_key_here';
interface BaZiRequest {
birth_date: string;
birth_time: string;
gender: 'male' | 'female';
is_lunar: boolean;
}
async function getBaZiChart(request: BaZiRequest) {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': API_KEY,
},
body: JSON.stringify(request),
});
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
const result = await response.json();
return result.data;
}
// Example usage
const baziData = await getBaZiChart({
birth_date: '1990-01-15',
birth_time: '08:30',
gender: 'male',
is_lunar: false,
});
console.log('Day Master:', baziData.day_master.gan);
console.log('Five Elements:', baziData.five_elements);
```
---
## Example 4: React Component
```tsx
import { useState } from 'react';
const API_URL = 'https://sisithefox-astrologybazi-api.hf.space/calculate-bazi';
const API_KEY = process.env.NEXT_PUBLIC_BAZI_API_KEY;
interface BaZiFormData {
birthDate: string;
birthTime: string;
gender: 'male' | 'female';
isLunar: boolean;
}
export default function BaZiCalculator() {
const [formData, setFormData] = useState<BaZiFormData>({
birthDate: '',
birthTime: '',
gender: 'male',
isLunar: false,
});
const [result, setResult] = useState<any>(null);
const [loading, setLoading] = useState(false);
const calculateBaZi = async () => {
setLoading(true);
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': API_KEY!,
},
body: JSON.stringify({
birth_date: formData.birthDate,
birth_time: formData.birthTime,
gender: formData.gender,
is_lunar: formData.isLunar,
}),
});
const data = await response.json();
setResult(data.data);
} catch (error) {
console.error('BaZi calculation failed:', error);
} finally {
setLoading(false);
}
};
return (
<div className="bazi-calculator">
<h2>BaZi Calculator</h2>
<input
type="date"
value={formData.birthDate}
onChange={(e) => setFormData({ ...formData, birthDate: e.target.value })}
/>
<input
type="time"
value={formData.birthTime}
onChange={(e) => setFormData({ ...formData, birthTime: e.target.value })}
/>
<button onClick={calculateBaZi} disabled={loading}>
{loading ? 'Calculating...' : 'Calculate BaZi'}
</button>
{result && (
<div className="result">
<h3>Day Master: {result.day_master.gan}</h3>
<p>Element: {result.day_master.element}</p>
<h4>Four Pillars:</h4>
<ul>
<li>Year: {result.bazi_chart.year.pillar}</li>
<li>Month: {result.bazi_chart.month.pillar}</li>
<li>Day: {result.bazi_chart.day.pillar}</li>
<li>Hour: {result.bazi_chart.hour.pillar}</li>
</ul>
</div>
)}
</div>
);
}
```
---
## Example 5: Lunar Calendar Support
```python
# Chinese Lunar Calendar example
# For someone born on lunar calendar: 1977年农历8月11日
response = requests.post(
"https://sisithefox-astrologybazi-api.hf.space/calculate-bazi",
headers={"x-api-key": API_KEY},
json={
"birth_date": "1977-08-11", # Lunar date
"birth_time": "19:00",
"gender": "female",
"is_lunar": True # Important: Set to True for lunar calendar
}
)
result = response.json()
print("Solar date:", result['data']['solar_date']) # Auto-converted to solar
print("Lunar date:", result['data']['lunar_date'])
```
---
## Example 6: Integration with astrologybazi.com
```typescript
// Face-reading app integration
import { BaZiAPI } from './lib/bazi-api';
async function generateFortuneReading(userPhoto: File, birthInfo: BirthInfo) {
// Step 1: Analyze face with AI
const faceAnalysis = await analyzeFaceWithAI(userPhoto);
// Step 2: Get BaZi chart
const baziChart = await BaZiAPI.calculate({
birth_date: birthInfo.date,
birth_time: birthInfo.time,
gender: birthInfo.gender,
is_lunar: false,
});
// Step 3: Combine face reading + BaZi for comprehensive analysis
const fortuneReading = {
faceReading: faceAnalysis,
baziChart: baziChart,
dayMaster: baziChart.day_master,
fiveElements: baziChart.five_elements,
// AI interpretation combining both
interpretation: await generateAIInterpretation({
face: faceAnalysis,
bazi: baziChart,
}),
};
return fortuneReading;
}
```
---
## Example 7: Error Handling
```python
def safe_bazi_calculation(birth_date, birth_time):
"""BaZi calculation with proper error handling"""
try:
response = requests.post(
"https://sisithefox-astrologybazi-api.hf.space/calculate-bazi",
headers={
"Content-Type": "application/json",
"x-api-key": API_KEY
},
json={
"birth_date": birth_date,
"birth_time": birth_time,
"gender": "male",
"is_lunar": False
},
timeout=10
)
response.raise_for_status()
return response.json()['data']
except requests.exceptions.HTTPError as e:
if e.response.status_code == 403:
print("Invalid API key")
elif e.response.status_code == 400:
print("Invalid input data:", e.response.json()['detail'])
else:
print(f"HTTP error: {e}")
except requests.exceptions.Timeout:
print("Request timeout - API is slow or unavailable")
except Exception as e:
print(f"Unexpected error: {e}")
return None
```
---
## Example 8: Batch Processing
```python
import asyncio
import aiohttp
async def batch_calculate_bazi(birth_records):
"""Calculate BaZi for multiple people efficiently"""
async def calculate_one(session, record):
async with session.post(
"https://sisithefox-astrologybazi-api.hf.space/calculate-bazi",
headers={"x-api-key": API_KEY},
json=record
) as response:
result = await response.json()
return result['data']
async with aiohttp.ClientSession() as session:
tasks = [calculate_one(session, record) for record in birth_records]
results = await asyncio.gather(*tasks)
return results
# Example usage
birth_records = [
{"birth_date": "1990-01-15", "birth_time": "08:30", "gender": "male", "is_lunar": False},
{"birth_date": "1985-06-20", "birth_time": "14:45", "gender": "female", "is_lunar": False},
{"birth_date": "1992-03-10", "birth_time": "22:00", "gender": "male", "is_lunar": False},
]
results = asyncio.run(batch_calculate_bazi(birth_records))
```
---
## Example 9: Simplified API for Mobile Apps
```swift
// iOS Swift example
struct BaZiService {
static let apiURL = "https://sisithefox-astrologybazi-api.hf.space/calculate-bazi-simple"
static let apiKey = "your_api_key_here"
struct BaZiRequest: Codable {
let birth_date: String
let birth_time: String
let gender: String
let is_lunar: Bool
}
static func calculateBaZi(birthDate: String, birthTime: String) async throws -> [String: Any] {
guard let url = URL(string: apiURL) else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(apiKey, forHTTPHeaderField: "x-api-key")
let body = BaZiRequest(
birth_date: birthDate,
birth_time: birthTime,
gender: "male",
is_lunar: false
)
request.httpBody = try JSONEncoder().encode(body)
let (data, _) = try await URLSession.shared.data(for: request)
let result = try JSONDecoder().decode([String: Any].self, from: data)
return result
}
}
```
---
## Testing the API
Visit the interactive documentation:
**Swagger UI:** https://sisithefox-astrologybazi-api.hf.space/docs
You can test all endpoints directly in your browser!
---
## Common Issues
### 1. 403 Forbidden Error
- **Cause:** Invalid or missing API key
- **Solution:** Contact SisiTheFox for API access
### 2. 400 Bad Request
- **Cause:** Invalid date/time format
- **Solution:** Use `YYYY-MM-DD` for date, `HH:MM` for time
### 3. 500 Internal Server Error
- **Cause:** BaZi calculation failed (rare)
- **Solution:** Check your input data, contact support if persists
---
## Need Help?
- 📚 Full Documentation: https://sisithefox-astrologybazi-api.hf.space/docs
- 📧 Email: contact@sisithefox.com
- 🌐 Website: https://sisithefox.com
---
**Made with ❤️ by SisiTheFox**