Track, measure, and optimize your API usage like a pro Ever wondered which of your apps is burning through your API budget? Or need to bill customers accurately for their AI usage? App Attribution is your answer – a powerful feature that lets you tag, track, and analyze every API call with surgical precision.

What’s in it for you?

πŸ“Š Crystal-clear usage insights – See exactly how each app, project, or customer uses your API
πŸ’° Bulletproof cost allocation – No more guesswork when dividing bills
πŸš€ Performance monitoring – Track response times and success rates per app
πŸ“ˆ Data-driven decisions – Export detailed reports and spot trends instantly
πŸ›‘οΈ Smart spending controls – Set limits and get alerts before things get expensive

Getting Started: Two Ways to Tag Your Requests

Clean, simple, and works everywhere
import requests

url = "https://api.anyapi.ai/api/v1/chat/completions"
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
    
    # 🏷️ Your attribution tags
    "X-AnyAPI-App-ID": "my-chatbot-v2",           # Required: Your app's unique ID
    "X-AnyAPI-App-Name": "Customer Support Bot",   # Optional: Human-readable name
    "X-AnyAPI-App-Version": "2.1.0",              # Optional: Track versions
    "X-AnyAPI-User-ID": "user_12345",             # Optional: End user tracking
    "X-AnyAPI-Session-ID": "session_abc123"       # Optional: Session tracking
}

payload = {
    "model": "openai/gpt-4o",
    "messages": [{"role": "user", "content": "Hello, how can you help me?"}]
}

response = requests.post(url, headers=headers, json=payload)

Method 2: Request Body Metadata

Perfect for complex attribution scenarios
payload = {
    "model": "anthropic/claude-3-5-sonnet-20241022",
    "messages": [{"role": "user", "content": "Analyze this quarterly data..."}],
    
    # 🎯 Rich metadata for detailed tracking
    "metadata": {
        "app_id": "data-analyzer",
        "app_name": "Business Intelligence Tool", 
        "app_version": "1.5.2",
        "user_id": "analyst_jane_doe",
        "project": "q4-sales-analysis",
        "department": "marketing",
        "region": "us-west"
    }
}

Attribution Fields Reference

Must-Have

  • app_id – Your app’s unique identifier (this is the only required field)

Nice-to-Have (But Really Useful)

  • app_name – Human-friendly app name for dashboards
  • app_version – Track performance across versions
  • user_id – See per-user usage patterns
  • session_id – Follow conversation threads
  • project – Organize by campaigns or initiatives
  • environment – Separate prod from staging costs
  • region – Geographic usage distribution

Real-World Implementation

Single App Setup

Perfect for most developers
class AnyAPIClient:
    def __init__(self, api_key, app_id, app_name=None, app_version=None):
        self.api_key = api_key
        self.app_id = app_id
        self.app_name = app_name
        self.app_version = app_version
        self.base_url = "https://api.anyapi.ai/api/v1"
    
    def _get_headers(self, user_id=None, session_id=None):
        """Smart header generation with attribution"""
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
            "X-AnyAPI-App-ID": self.app_id
        }
        
        # Add optional fields only when they exist
        if self.app_name:
            headers["X-AnyAPI-App-Name"] = self.app_name
        if self.app_version:
            headers["X-AnyAPI-App-Version"] = self.app_version
        if user_id:
            headers["X-AnyAPI-User-ID"] = user_id
        if session_id:
            headers["X-AnyAPI-Session-ID"] = session_id
        
        return headers
    
    def chat_completion(self, messages, model="openai/gpt-4o", 
                       user_id=None, session_id=None, **kwargs):
        """Make attributed requests effortlessly"""
        
        headers = self._get_headers(user_id, session_id)
        payload = {"model": model, "messages": messages, **kwargs}
        
        response = requests.post(
            f"{self.base_url}/chat/completions",
            headers=headers,
            json=payload
        )
        return response.json()

# πŸš€ Usage is dead simple
client = AnyAPIClient(
    api_key=API_KEY,
    app_id="customer-support-bot",
    app_name="Customer Support Assistant", 
    app_version="3.2.1"
)

# Every request gets properly attributed automatically
result = client.chat_completion(
    messages=[{"role": "user", "content": "How do I reset my password?"}],
    user_id="customer_54321",
    session_id="support_session_789"
)

Multi-Tenant SaaS Setup

When you’re serving multiple customers
class MultiTenantAPIClient:
    def __init__(self, api_key, base_app_id):
        self.api_key = api_key
        self.base_app_id = base_app_id
        self.base_url = "https://api.anyapi.ai/api/v1"
    
    def make_request_for_tenant(self, tenant_id, messages, 
                               model="openai/gpt-4o", **kwargs):
        """Tenant-specific attribution made easy"""
        
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
            "X-AnyAPI-App-ID": f"{self.base_app_id}-{tenant_id}",
            "X-AnyAPI-App-Name": f"SaaS App - {tenant_id}",
            "X-AnyAPI-User-ID": kwargs.get("user_id"),
            "X-AnyAPI-Tenant-ID": tenant_id
        }
        
        # Rich metadata for business intelligence
        payload = {
            "model": model,
            "messages": messages,
            "metadata": {
                "tenant_id": tenant_id,
                "subscription_tier": kwargs.get("tier", "standard"),
                "feature_flags": kwargs.get("features", []),
                "billing_cycle": kwargs.get("billing_cycle", "monthly")
            }
        }
        
        response = requests.post(f"{self.base_url}/chat/completions",
                               headers=headers, json=payload)
        return response.json()

# πŸ’Ό Perfect for SaaS platforms
client = MultiTenantAPIClient(API_KEY, "my-saas-platform")

# Company A gets premium features
result_a = client.make_request_for_tenant(
    tenant_id="company-abc",
    messages=[{"role": "user", "content": "Generate quarterly projections..."}],
    user_id="ceo_alice",
    tier="enterprise",
    features=["advanced_analytics", "custom_models"]
)

# Startup B gets the essentials  
result_b = client.make_request_for_tenant(
    tenant_id="startup-xyz", 
    messages=[{"role": "user", "content": "Help brainstorm marketing ideas..."}],
    user_id="founder_bob",
    tier="startup"
)

Analytics That Actually Matter

Get Usage Insights

See where your money’s going
def get_usage_by_app(app_id, start_date, end_date):
    """Pull detailed usage stats for any app"""
    
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    params = {
        "app_id": app_id,
        "start_date": start_date,
        "end_date": end_date,
        "group_by": ["date", "model", "user_id"]  # Slice and dice your data
    }
    
    response = requests.get(
        "https://api.anyapi.ai/api/v1/analytics/usage",
        headers=headers,
        params=params
    )
    
    return response.json()

# πŸ“Š Get the last 30 days of data
import datetime

end_date = datetime.datetime.now()
start_date = end_date - datetime.timedelta(days=30)

usage_data = get_usage_by_app(
    "customer-support-bot",
    start_date.isoformat(),
    end_date.isoformat()
)

print(f"πŸ”₯ Total requests: {usage_data['total_requests']:,}")
print(f"πŸ’° Total cost: ${usage_data['total_cost']:.2f}")
print(f"⚑ Average response time: {usage_data['avg_response_time']}ms")

Cost Allocation Reports

Perfect for finance teams and client billing
def generate_cost_allocation_report(start_date, end_date):
    """Create executive-ready cost breakdowns"""
    
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "start_date": start_date,
        "end_date": end_date,
        "group_by": ["app_id", "model"],
        "metrics": ["requests", "cost", "tokens", "avg_response_time"]
    }
    
    response = requests.post(
        "https://api.anyapi.ai/api/v1/analytics/cost-allocation",
        headers=headers,
        json=payload
    )
    
    data = response.json()
    
    # πŸ“‹ Beautiful console report
    print("πŸ’Ž Cost Allocation Report")
    print("=" * 50)
    
    for app in data["apps"]:
        print(f"\nπŸš€ App: {app['app_name']} ({app['app_id']})")
        print(f"   πŸ“Š Requests: {app['total_requests']:,}")
        print(f"   πŸ’΅ Cost: ${app['total_cost']:.2f}")
        print(f"   ⚑ Avg Response: {app['avg_response_time']}ms")
        
        for model in app["models"]:
            print(f"      πŸ€– {model['model']}: {model['requests']:,} requests, ${model['cost']:.2f}")
    
    return data

Smart Usage Controls

Set Spending Limits

Sleep better knowing your costs are under control
def set_app_usage_limit(app_id, monthly_limit_dollars):
    """Set bulletproof spending limits"""
    
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "app_id": app_id,
        "limit_type": "monthly",
        "limit_amount": monthly_limit_dollars * 100,  # Convert to credits
        "alert_thresholds": [50, 80, 95]  # Get warned before it's too late
    }
    
    response = requests.post(
        "https://api.anyapi.ai/api/v1/limits/app",
        headers=headers,
        json=payload
    )
    
    return response.json()

# πŸ›‘οΈ Set a $100 monthly limit 
limit_result = set_app_usage_limit("customer-support-bot", 100)
print(f"βœ… Limit set successfully: {limit_result['success']}")

Real-Time Usage Monitoring

Stay on top of your spending
def check_app_usage_status(app_id):
    """Get instant usage updates"""
    
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    response = requests.get(
        f"https://api.anyapi.ai/api/v1/usage/app/{app_id}/current",
        headers=headers
    )
    
    data = response.json()
    usage_percent = (data["current_usage"] / data["limit"]) * 100
    
    print(f"πŸ“± App: {data['app_name']}")
    print(f"πŸ’° Current: ${data['current_usage']/100:.2f}")
    print(f"🎯 Limit: ${data['limit']/100:.2f}")
    print(f"πŸ“Š Usage: {usage_percent:.1f}%")
    
    # Smart alerts
    if usage_percent > 90:
        print("🚨 ALERT: You're almost at your limit!")
    elif usage_percent > 75:
        print("⚠️  HEADS UP: Usage is getting high")
    else:
        print("βœ… All good! Spending is under control")
    
    return data

Pro Tips for Success

🎯 Smart App IDs

  • Be descriptive: Use customer-chat-prod not app1
  • Stay consistent: Pick a naming pattern and stick to it
  • Include environment: Separate prod, staging, dev

πŸ“Š Meaningful Data

  • Track what matters: User IDs for SaaS, session IDs for chat apps
  • Version everything: Catch performance regressions early
  • Add context: Project names, feature flags, A/B test groups

πŸ’° Cost Management

  • Set realistic limits: Start conservative, adjust as needed
  • Monitor trends: Weekly reviews prevent monthly surprises
  • Use alerts wisely: 50% warning, 80% action needed, 95% panic mode

πŸ”’ Security First

  • Hash user IDs: Protect customer privacy
  • No secrets in tags: Attribution data is logged
  • Follow regulations: GDPR, CCPA compliance matters

πŸ“ˆ Analytics Optimization

  • Consistent naming: Same field names across all apps
  • Rich metadata: More context = better insights
  • Regular reviews: Monthly deep dives reveal optimization opportunities

Common Success Stories

🏒 Multi-Tenant SaaS
”We use App Attribution to bill customers accurately and identify our power users. Revenue attribution increased 40%.”
πŸš€ Product Teams
”Tracking by feature helped us kill underperforming products and double down on winners. ROI improved dramatically.”
πŸ§‘β€πŸ’» Development Teams
”Separating staging from production costs was a game-changer. No more surprise bills from testing.”
πŸ“Š Analytics Teams
”Per-user tracking revealed usage patterns we never knew existed. Our retention strategies are now data-driven.”
πŸ’Ό Finance Teams
”Cost allocation reports make budgeting and forecasting actually possible. CFO loves the transparency.”

What’s Next?

Ready to get surgical precision on your API costs? App Attribution gives you the visibility and control you need to optimize usage, allocate costs fairly, and make data-driven decisions about your AI investments. Start with a simple app_id on your next request, then gradually add more attribution fields as your needs grow. Your future self (and your finance team) will thank you. Happy tracking! πŸš€