Skip to main content

Create a Customer

Create a customer to track usage and enforce limits:
from limitry import Limitry

client = Limitry()

customer = client.customers.create(
    external_id="user_123",  # Your internal user/customer ID
    name="Acme Corp",
    email="[email protected]",
    metadata={
        "plan": "pro",
        "tier": "enterprise"
    }
)

print(f"Created customer: {customer.id}")

List Customers

# List all customers
customers = client.customers.list()

for customer in customers.data:
    print(f"{customer.id}: {customer.name or customer.external_id}")

# With pagination
page = client.customers.list(limit=50)
if page.has_more:
    next_page = client.customers.list(cursor=page.next_cursor)

Retrieve a Customer

customer = client.customers.retrieve("cust_123")

print(f"Customer: {customer.name}")
print(f"External ID: {customer.external_id}")
print(f"Metadata: {customer.metadata}")

Update a Customer

customer = client.customers.update("cust_123",
    name="Acme Corporation",
    metadata={
        "plan": "enterprise",
        "tier": "premium"
    }
)

Get Customer Events

Retrieve events for a customer within a date range:
from datetime import datetime, timedelta

# Get events for the last 30 days
events = client.events.list(
    customer_id="cust_123",
    start_date=(datetime.now() - timedelta(days=30)).isoformat(),
    end_date=datetime.now().isoformat()
)

print(f"Total events: {len(events.data)}")
for event in events.data:
    print(f"{event.event_type}: {event.values}")

Use Cases

Customer Billing

Generate billing data for a customer using meters:
from datetime import datetime

def get_monthly_bill(customer_id: str, meter_id: str, year: int, month: int) -> dict:
    # Calculate month boundaries
    start = datetime(year, month, 1)
    if month == 12:
        end = datetime(year + 1, 1, 1)
    else:
        end = datetime(year, month + 1, 1)
    
    # Get meter value for the period
    meter_value = client.meters.get_value(
        meter_id,
        customer_id=customer_id,
        start_date=start.isoformat(),
        end_date=end.isoformat()
    )
    
    return {
        "customer_id": customer_id,
        "period": f"{year}-{month:02d}",
        "usage": meter_value.value,
        # Apply your pricing logic
        "cost_dollars": meter_value.value * 0.001  # Example: $0.001 per unit
    }

# Generate January 2024 bill
bill = get_monthly_bill("cust_123", "mtr_tokens", 2024, 1)
print(f"Invoice for {bill['period']}: ${bill['cost_dollars']:.2f}")

Customer Dashboard

Show usage stats in a customer-facing dashboard:
from datetime import datetime, timedelta

def get_customer_stats(customer_id: str, meter_id: str) -> dict:
    now = datetime.now()
    
    # Current month usage
    month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    current_month = client.meters.get_value(
        meter_id,
        customer_id=customer_id,
        start_date=month_start.isoformat(),
        end_date=now.isoformat()
    )
    
    # Previous month usage (for comparison)
    prev_month_end = month_start - timedelta(seconds=1)
    prev_month_start = prev_month_end.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    prev_month = client.meters.get_value(
        meter_id,
        customer_id=customer_id,
        start_date=prev_month_start.isoformat(),
        end_date=prev_month_end.isoformat()
    )
    
    return {
        "current_month": {"usage": current_month.value},
        "previous_month": {"usage": prev_month.value}
    }

stats = get_customer_stats("cust_123", "mtr_tokens")
print(f"This month: {stats['current_month']['usage']:,} units")
print(f"Last month: {stats['previous_month']['usage']:,} units")

Usage Reports

Generate usage reports across multiple customers:
def generate_usage_report(customer_ids: list[str], meter_id: str, start_date: str, end_date: str):
    report = []
    
    for customer_id in customer_ids:
        meter_value = client.meters.get_value(
            meter_id,
            customer_id=customer_id,
            start_date=start_date,
            end_date=end_date
        )
        
        report.append({
            "customer_id": customer_id,
            "usage": meter_value.value
        })
    
    # Sort by usage (highest first)
    report.sort(key=lambda x: x["usage"], reverse=True)
    
    return report

# Top customers by usage
customers = ["cust_001", "cust_002", "cust_003"]
report = generate_usage_report(
    customers,
    "mtr_tokens",
    start_date="2024-01-01T00:00:00Z",
    end_date="2024-01-31T23:59:59Z"
)

for row in report:
    print(f"{row['customer_id']}: {row['usage']:,} units")

Combining with Limits

Check limit status alongside usage:
def get_customer_limit_status(customer_id: str):
    # Check all limits for the customer
    check = client.limits.check(customer_id=customer_id)
    
    return {
        "allowed": check.allowed,
        "limits": [
            {
                "name": l.name,
                "current_value": l.current_value,
                "value": l.value,
                "remaining": l.remaining,
                "percentage": (l.current_value / l.value) * 100 if l.value > 0 else 0,
                "exceeded": l.exceeded
            }
            for l in check.limits
        ]
    }

status = get_customer_limit_status("cust_123")
print(f"Allowed: {status['allowed']}")
for limit in status["limits"]:
    print(f"{limit['name']}: {limit['current_value']}/{limit['value']} ({limit['percentage']:.1f}%)")