Your SaaS Superpower

Automate customer onboarding and key management like the pros Building a SaaS platform with AI features? Stop manually creating API keys for every customer. AnyAPI’s Provisioning API turns key management into a competitive advantage with automated customer onboarding, usage tracking, and bulletproof security controls.

🚀 What Provisioning Unlocks

From manual grunt work to automated excellence Before: Manually create keys, copy-paste limits, pray you don’t mess up customer billing. After: Fully automated customer lifecycle management:
  • 🎯 Instant customer onboarding → Keys created in seconds, not hours
  • 💰 Automated billing integration → Track usage, enforce limits, prevent overages
  • 🔐 Enterprise security → Automated key rotation and lifecycle management
  • 📊 Real-time monitoring → Usage analytics that actually matter
  • Scale without headaches → Handle thousands of customers effortlessly

⚡ Quick Start: From Zero to Hero

Get your first automated key in 60 seconds

Step 1: Get Your Provisioning Key

  1. Hit up the AnyAPI dashboard
  2. Create a new provisioning key (these are special—they manage other keys)
  3. Lock it down tight—this baby controls your entire key empire

Step 2: Your First Automated Key

import requests

# The master key (guard this with your life)
PROVISIONING_KEY = "ak-prov-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
BASE_URL = "https://api.anyapi.ai/api/v1/keys"

headers = {
    "Authorization": f"Bearer {PROVISIONING_KEY}",
    "Content-Type": "application/json"
}

# Create a customer key in 3 lines
def create_customer_key(customer_id, monthly_budget):
    payload = {
        "name": f"Customer {customer_id}",
        "label": f"customer-{customer_id}", 
        "limit": monthly_budget * 100,  # Convert $ to credits
        "description": f"Auto-provisioned for customer {customer_id}"
    }
    
    response = requests.post(f"{BASE_URL}/", headers=headers, json=payload)
    return response.json()

# Magic happens here
new_customer = create_customer_key("cust_12345", 50)  # $50/month limit
print(f"Customer key: {new_customer['key']}")
Boom. Your customer now has a working API key with spending limits. No manual work, no copy-paste errors, no late-night emergency key creation.

🛠️ The Complete Toolkit

Everything you need for enterprise key management

The SaaS Key Manager Class

Copy this, customize it, profit
class AnyAPIKeyManager:
    def __init__(self, provisioning_key):
        self.provisioning_key = provisioning_key
        self.base_url = "https://api.anyapi.ai/api/v1/keys"
        self.headers = {
            "Authorization": f"Bearer {provisioning_key}",
            "Content-Type": "application/json"
        }
    
    def onboard_customer(self, customer_id, plan_type):
        """Complete customer onboarding with one call"""
        plan_limits = {
            "starter": 25,    # $25/month
            "pro": 100,       # $100/month  
            "enterprise": 500  # $500/month
        }
        
        limit = plan_limits.get(plan_type, 25)
        
        payload = {
            "name": f"{plan_type.title()} Plan - Customer {customer_id}",
            "label": f"customer-{customer_id}-{plan_type}",
            "limit": limit * 100,
            "description": f"Auto-provisioned {plan_type} plan key"
        }
        
        response = requests.post(f"{self.base_url}/", headers=self.headers, json=payload)
        
        if response.status_code == 201:
            key_data = response.json()
            return {
                "api_key": key_data["key"],           # Give this to customer
                "hash": key_data["hash"],             # Store this in your DB
                "monthly_limit": limit,
                "plan": plan_type
            }
        else:
            raise Exception(f"Onboarding failed: {response.text}")
    
    def check_customer_usage(self, key_hash):
        """Get real-time usage stats"""
        response = requests.get(f"{self.base_url}/{key_hash}", headers=self.headers)
        
        if response.status_code == 200:
            data = response.json()
            usage_pct = (data["usage"] / data["limit"]) * 100 if data["limit"] > 0 else 0
            
            return {
                "spent": data["usage"] / 100,         # Convert to dollars
                "limit": data["limit"] / 100,         # Convert to dollars
                "usage_percentage": usage_pct,
                "last_used": data["last_used"],
                "status": "warning" if usage_pct > 80 else "healthy"
            }
        return None
    
    def upgrade_customer_plan(self, key_hash, new_plan):
        """Seamless plan upgrades"""
        plan_limits = {"starter": 25, "pro": 100, "enterprise": 500}
        new_limit = plan_limits.get(new_plan, 25) * 100
        
        payload = {
            "limit": new_limit,
            "name": f"{new_plan.title()} Plan Key"
        }
        
        response = requests.patch(f"{self.base_url}/{key_hash}", headers=self.headers, json=payload)
        return response.status_code == 200
    
    def suspend_customer(self, key_hash, reason="billing_issue"):
        """Temporarily disable a customer (non-payment, etc.)"""
        payload = {"disabled": True}
        response = requests.patch(f"{self.base_url}/{key_hash}", headers=self.headers, json=payload)
        return response.status_code == 200
    
    def reactivate_customer(self, key_hash):
        """Bring a customer back online"""
        payload = {"disabled": False}
        response = requests.patch(f"{self.base_url}/{key_hash}", headers=self.headers, json=payload)
        return response.status_code == 200

🔄 Automated Customer Lifecycle

Set it and forget it workflows

The Onboarding Pipeline

key_manager = AnyAPIKeyManager(PROVISIONING_KEY)

def complete_customer_onboarding(customer_data):
    """Handle new customer signup"""
    try:
        # Create their API key
        key_info = key_manager.onboard_customer(
            customer_data["id"], 
            customer_data["plan"]
        )
        
        # Store in your database
        save_customer_key_to_db(customer_data["id"], key_info)
        
        # Send welcome email with their key
        send_welcome_email(customer_data["email"], key_info["api_key"])
        
        # Set up usage monitoring
        schedule_usage_monitoring(customer_data["id"], key_info["hash"])
        
        return {"success": True, "key_hash": key_info["hash"]}
        
    except Exception as e:
        # Rollback any partial creation
        print(f"Onboarding failed for {customer_data['id']}: {e}")
        return {"success": False, "error": str(e)}

# Usage
new_signup = {
    "id": "cust_67890",
    "email": "founder@startup.com", 
    "plan": "pro"
}

result = complete_customer_onboarding(new_signup)
# Customer is now live with working AI features

Usage Monitoring Automation

def monitor_customer_usage():
    """Run this as a scheduled job (hourly/daily)"""
    customers = get_all_customer_keys_from_db()
    
    for customer in customers:
        usage = key_manager.check_customer_usage(customer["key_hash"])
        
        if usage:
            # Update your billing system
            update_customer_usage_in_db(customer["id"], usage)
            
            # Handle usage warnings
            if usage["status"] == "warning":
                send_usage_warning_email(customer["email"], usage)
            
            # Handle overages (if you allow them)
            if usage["usage_percentage"] > 100:
                handle_customer_overage(customer["id"], usage)
            
            # Upgrade suggestions for high usage
            if usage["usage_percentage"] > 85 and customer["plan"] != "enterprise":
                suggest_plan_upgrade(customer["email"], customer["plan"])

# Run as cron job
# 0 * * * * /usr/bin/python /path/to/monitor_usage.py

🔐 Security & Key Rotation

Enterprise-grade security automation

Automated Key Rotation

import datetime
from dateutil.relativedelta import relativedelta

def rotate_customer_keys():
    """Rotate keys older than 90 days"""
    cutoff_date = datetime.datetime.now() - relativedelta(days=90)
    old_keys = get_keys_older_than(cutoff_date)
    
    for key_info in old_keys:
        try:
            # Create replacement key
            new_key = key_manager.onboard_customer(
                key_info["customer_id"], 
                key_info["plan"]
            )
            
            # Gradual transition (run both keys for 24 hours)
            schedule_key_transition(key_info, new_key, hours=24)
            
            # Notify customer
            send_key_rotation_notification(
                key_info["customer_email"],
                new_key["api_key"],
                transition_deadline=datetime.datetime.now() + relativedelta(hours=24)
            )
            
        except Exception as e:
            alert_security_team(f"Key rotation failed: {key_info['customer_id']}: {e}")

def schedule_key_transition(old_key, new_key, hours=24):
    """Gradual key transition to prevent service disruption"""
    # Keep old key active for transition period
    transition_time = datetime.datetime.now() + relativedelta(hours=hours)
    
    # Schedule old key deactivation
    schedule_task("deactivate_old_key", {
        "key_hash": old_key["key_hash"],
        "execute_at": transition_time.isoformat()
    })

Security Monitoring

def security_audit():
    """Run security checks on all keys"""
    all_keys = key_manager.list_all_keys()
    
    security_issues = []
    
    for key in all_keys:
        # Check for dormant keys
        if not key.get("last_used"):
            security_issues.append({
                "type": "dormant_key",
                "key_hash": key["hash"],
                "created": key["created_at"]
            })
        
        # Check for keys without limits
        if not key.get("limit") or key["limit"] == 0:
            security_issues.append({
                "type": "unlimited_key", 
                "key_hash": key["hash"]
            })
        
        # Check for old keys
        created = datetime.datetime.fromisoformat(key["created_at"].replace('Z', '+00:00'))
        if created < datetime.datetime.now() - relativedelta(days=180):
            security_issues.append({
                "type": "stale_key",
                "key_hash": key["hash"],
                "age_days": (datetime.datetime.now() - created).days
            })
    
    if security_issues:
        send_security_report(security_issues)
    
    return security_issues

📊 Advanced Usage Patterns

Multi-Tenant Management

class MultiTenantKeyManager(AnyAPIKeyManager):
    def create_organization_keys(self, org_id, team_members):
        """Create keys for an entire organization"""
        org_keys = {}
        
        # Admin key with full access
        admin_key = self.onboard_customer(f"{org_id}-admin", "enterprise") 
        org_keys["admin"] = admin_key
        
        # Team member keys with limited access
        for member in team_members:
            member_key = self.onboard_customer(f"{org_id}-{member['id']}", "pro")
            org_keys[f"member_{member['id']}"] = member_key
        
        return org_keys
    
    def get_org_usage_summary(self, org_id):
        """Aggregate usage across all org keys"""
        org_keys = get_org_keys_from_db(org_id)
        
        total_usage = 0
        total_limit = 0
        
        for key_info in org_keys:
            usage = self.check_customer_usage(key_info["key_hash"])
            if usage:
                total_usage += usage["spent"]
                total_limit += usage["limit"]
        
        return {
            "total_spent": total_usage,
            "total_limit": total_limit,
            "utilization": (total_usage / total_limit) * 100 if total_limit > 0 else 0,
            "member_count": len(org_keys)
        }

Usage Analytics & Insights

def generate_usage_insights():
    """Create actionable insights from usage data"""
    all_customers = get_customer_usage_data()
    
    insights = {
        "high_usage_customers": [],
        "upgrade_candidates": [],
        "at_risk_customers": [],
        "usage_trends": {}
    }
    
    for customer in all_customers:
        usage = key_manager.check_customer_usage(customer["key_hash"])
        
        if usage:
            # High usage = happy customers
            if usage["usage_percentage"] > 90:
                insights["high_usage_customers"].append({
                    "customer_id": customer["id"],
                    "usage": usage["usage_percentage"]
                })
            
            # Upgrade opportunities
            if usage["usage_percentage"] > 75 and customer["plan"] != "enterprise":
                insights["upgrade_candidates"].append({
                    "customer_id": customer["id"],
                    "current_plan": customer["plan"],
                    "usage": usage["usage_percentage"]
                })
            
            # At-risk customers (low usage = might churn)
            if usage["usage_percentage"] < 10:
                insights["at_risk_customers"].append({
                    "customer_id": customer["id"],
                    "usage": usage["usage_percentage"]
                })
    
    return insights

🚨 Error Handling & Reliability

Bulletproof Error Handling

from tenacity import retry, stop_after_attempt, wait_exponential

class RobustKeyManager(AnyAPIKeyManager):
    @retry(
        stop=stop_after_attempt(3),
        wait=wait_exponential(multiplier=1, min=4, max=10)
    )
    def create_key_with_retry(self, customer_id, plan):
        """Create key with automatic retries"""
        try:
            return self.onboard_customer(customer_id, plan)
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 429:  # Rate limited
                raise Exception("Rate limited - will retry")
            elif e.response.status_code >= 500:  # Server error
                raise Exception("Server error - will retry")
            else:
                raise  # Don't retry client errors
    
    def safe_key_operation(self, operation, *args, **kwargs):
        """Wrapper for safe key operations"""
        try:
            return operation(*args, **kwargs)
        except requests.exceptions.ConnectionError:
            return {"error": "Connection failed", "retry": True}
        except requests.exceptions.Timeout:
            return {"error": "Request timed out", "retry": True}
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 401:
                return {"error": "Invalid provisioning key", "retry": False}
            elif e.response.status_code == 403:
                return {"error": "Insufficient permissions", "retry": False}
            else:
                return {"error": f"HTTP {e.response.status_code}", "retry": True}
        except Exception as e:
            return {"error": f"Unexpected error: {e}", "retry": False}

💡 Pro Tips for Production

🎯 Monitoring & Alerting

def setup_key_monitoring():
    """Essential monitoring for production"""
    # Alert on provisioning API failures
    # Alert on unusual key creation patterns
    # Alert on keys approaching limits
    # Alert on security issues (dormant keys, etc.)

🔐 Security Best Practices

  • Separate provisioning keys from regular API keys
  • Rotate provisioning keys quarterly
  • Log all key operations for audit trails
  • Use least-privilege permissions
  • Monitor for anomalous key usage patterns

💰 Cost Optimization

  • Set conservative limits initially—easier to increase than decrease
  • Monitor usage patterns to optimize plan structures
  • Implement usage-based pricing tiers
  • Alert on unexpected usage spikes

Performance at Scale

  • Batch key operations when possible
  • Cache usage data to reduce API calls
  • Use async processing for key rotation
  • Implement circuit breakers for resilience

Ready to automate your customer onboarding? Start provisioning keys like a SaaS pro with AnyAPI.