Usage API
Usage Tracking
Monitor your API usage in real-time
Track your API usage, monitor quota consumption, and understand your request patterns with the Usage API.
Endpoint
GET /api/v1/dev/usageThe Usage API provides real-time statistics for the current billing period (monthly cycle starting on the 1st).
Basic Usage Tracking
Python
import requests
headers = {
"X-API-Key": "your_api_key_here"
}
response = requests.get(
"https://api.brainus.lk/api/v1/dev/usage",
headers=headers
)
usage = response.json()
# Display key metrics
print(f"Total requests: {usage['total_requests']}")
print(f"Total tokens: {usage['total_tokens']:,}")
print(f"Total cost: ${usage['total_cost_usd']:.4f}")
print(f"Quota used: {usage['quota_percentage']:.1f}%")
print(f"Requests remaining: {usage['quota_remaining']}")JavaScript
const response = await fetch("https://api.brainus.lk/api/v1/dev/usage", {
headers: {
"X-API-Key": "your_api_key_here",
},
});
const usage = await response.json();
// Display key metrics
console.log(`Total requests: ${usage.total_requests}`);
console.log(`Total tokens: ${usage.total_tokens.toLocaleString()}`);
console.log(`Total cost: $${usage.total_cost_usd.toFixed(4)}`);
console.log(`Quota used: ${usage.quota_percentage.toFixed(1)}%`);
console.log(`Requests remaining: ${usage.quota_remaining}`);Understanding the Response
The Usage API returns statistics for the current billing period:
{
"total_requests": 86,
"total_tokens": 149434,
"total_cost_usd": 0.014382,
"by_endpoint": {
"/api/v1/dev/query": 86
},
"period_start": "2025-12-01",
"period_end": "2025-12-13",
"plan": {
"name": "Free",
"rate_limit_per_minute": 10,
"rate_limit_per_day": 300,
"monthly_quota": 300
},
"quota_remaining": 214,
"quota_percentage": 28.67
}Monitoring Quota Usage
Check Quota Status
def check_quota_status(usage):
"""Check if quota is running low."""
quota_percentage = usage['quota_percentage']
remaining = usage['quota_remaining']
if quota_percentage >= 90:
print(f"⚠️ CRITICAL: {quota_percentage:.1f}% quota used, only {remaining} requests left!")
elif quota_percentage >= 80:
print(f"⚠️ WARNING: {quota_percentage:.1f}% quota used, {remaining} requests remaining")
elif quota_percentage >= 70:
print(f"ℹ️ INFO: {quota_percentage:.1f}% quota used, {remaining} requests remaining")
else:
print(f"✅ Quota healthy: {quota_percentage:.1f}% used, {remaining} requests remaining")
# Get usage and check status
response = requests.get(
"https://api.brainus.lk/api/v1/dev/usage",
headers={"X-API-Key": "your_api_key_here"}
)
check_quota_status(response.json())Automated Monitoring Script
Create a monitoring script that runs periodically:
import requests
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
def send_alert(subject, message):
"""Send email alert."""
# Configure your email settings
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = 'alerts@yourapp.com'
msg['To'] = 'admin@yourapp.com'
# Send email (configure SMTP settings)
# s = smtplib.SMTP('localhost')
# s.send_message(msg)
# s.quit()
print(f"Alert: {subject}\n{message}")
def monitor_usage():
"""Monitor usage and send alerts if needed."""
response = requests.get(
"https://api.brainus.lk/api/v1/dev/usage",
headers={"X-API-Key": "your_api_key_here"}
)
usage = response.json()
percentage = usage['quota_percentage']
if percentage >= 90:
send_alert(
"🚨 Critical: API Quota at 90%",
f"Your API usage is at {percentage:.1f}%\n"
f"Remaining: {usage['quota_remaining']} requests\n"
f"Consider upgrading your plan."
)
elif percentage >= 80:
send_alert(
"⚠️ Warning: API Quota at 80%",
f"Your API usage is at {percentage:.1f}%\n"
f"Remaining: {usage['quota_remaining']} requests"
)
# Run this with a cron job or scheduler
if __name__ == "__main__":
monitor_usage()Endpoint Breakdown
Track which endpoints are consuming your quota:
response = requests.get(
"https://api.brainus.lk/api/v1/dev/usage",
headers={"X-API-Key": "your_api_key_here"}
)
usage = response.json()
print("Request breakdown by endpoint:")
for endpoint, count in usage['by_endpoint'].items():
percentage = (count / usage['total_requests']) * 100
print(f" {endpoint}: {count} requests ({percentage:.1f}%)")Cost Tracking
Monitor your costs over time:
import json
from datetime import datetime
def log_daily_cost(usage_data):
"""Log daily cost to a file for tracking."""
log_entry = {
'date': usage_data['period_end'],
'total_requests': usage_data['total_requests'],
'total_cost_usd': usage_data['total_cost_usd'],
'total_tokens': usage_data['total_tokens'],
'quota_percentage': usage_data['quota_percentage']
}
# Append to log file
with open('usage_log.json', 'a') as f:
f.write(json.dumps(log_entry) + '\n')
# Calculate cost per request
if usage_data['total_requests'] > 0:
cost_per_request = usage_data['total_cost_usd'] / usage_data['total_requests']
print(f"Average cost per request: ${cost_per_request:.6f}")
# Get current usage
response = requests.get(
"https://api.brainus.lk/api/v1/dev/usage",
headers={"X-API-Key": "your_api_key_here"}
)
log_daily_cost(response.json())Best Practices
1. Regular Monitoring
Check your usage regularly to avoid surprises:
// Check usage before making a request
async function queryWithUsageCheck(query) {
// Get current usage
const usageResponse = await fetch("https://api.brainus.lk/api/v1/dev/usage", {
headers: { "X-API-Key": process.env.API_KEY },
});
const usage = await usageResponse.json();
// Check if we're running low
if (usage.quota_remaining < 10) {
console.warn(
"⚠️ Low quota: Only",
usage.quota_remaining,
"requests remaining"
);
}
// Make the query
const response = await fetch("https://api.brainus.lk/api/v1/dev/query", {
method: "POST",
headers: {
"X-API-Key": process.env.API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({ query, store_id: "default" }),
});
return response.json();
}2. Set Up Alerts
Configure automatic alerts when quota thresholds are reached:
- 70% - Start monitoring closely
- 80% - Consider caching or optimization
- 90% - Prepare to upgrade plan or reduce usage
3. Track Trends
Monitor your usage patterns:
def analyze_usage_trend():
"""Analyze usage trends over time."""
# Load historical logs
with open('usage_log.json', 'r') as f:
logs = [json.loads(line) for line in f]
if len(logs) >= 2:
# Compare with previous day
today = logs[-1]
yesterday = logs[-2]
request_change = today['total_requests'] - yesterday['total_requests']
cost_change = today['total_cost_usd'] - yesterday['total_cost_usd']
print(f"Request change: {request_change:+d}")
print(f"Cost change: ${cost_change:+.4f}")The billing period resets on the 1st of each month at 00:00:00 UTC. All usage statistics are calculated from that date to the current date.
Related Resources
- Usage API - Complete API reference
- Rate Limits - Understanding rate limits
- Plans & Pricing - Upgrade your plan