Mastering the Claude API: A Practical Guide to Company and Organization Management
Learn how to manage company and organization settings in the Claude API, including billing, user roles, and API key administration for enterprise teams.
This guide teaches you how to programmatically manage your Anthropic organization and company settings via the Claude API, covering user roles, billing administration, API key rotation, and best practices for enterprise deployments.
Mastering the Claude API: A Practical Guide to Company and Organization Management
As organizations scale their use of Claude AI, managing API access, billing, and user permissions becomes critical. Whether you're a team lead, DevOps engineer, or IT administrator, understanding how to programmatically control your Anthropic organization settings can save hours of manual work and prevent security headaches.
This guide walks you through the essential operations for managing your company's Claude API setup—from user role administration to billing oversight—using practical code examples you can implement today.
Understanding the Anthropic Organization Model
Before diving into code, it's important to understand how Anthropic structures organizations and companies:
- Organization: A logical grouping of users, API keys, and billing settings. Each organization has its own rate limits and usage quotas.
- Company: A higher-level entity that can contain multiple organizations. Typically used for enterprises with separate teams or departments.
- Users: Individuals with assigned roles (admin, member, billing) who can access the organization's resources.
- API Keys: Authentication tokens tied to a specific organization, used to make API calls.
Prerequisites
To follow this guide, you'll need:
- An Anthropic account with admin privileges
- Your organization's API key (starts with
sk-ant-) - Python 3.8+ or Node.js 16+
- The
requestslibrary (Python) oraxios(Node.js)
Setting Up Your Environment
Python Setup
import requests
import json
Your API key - store this securely, never in code!
API_KEY = "sk-ant-your-api-key-here"
BASE_URL = "https://api.anthropic.com/v1"
headers = {
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01",
"Content-Type": "application/json"
}
TypeScript/Node.js Setup
import axios from 'axios';
const API_KEY = process.env.ANTHROPIC_API_KEY;
const BASE_URL = 'https://api.anthropic.com/v1';
const client = axios.create({
baseURL: BASE_URL,
headers: {
'x-api-key': API_KEY,
'anthropic-version': '2023-06-01',
'Content-Type': 'application/json'
}
});
Managing Your Organization
Retrieving Organization Details
First, let's fetch your organization's information to understand your current setup:
def get_organization():
response = requests.get(f"{BASE_URL}/organizations", headers=headers)
if response.status_code == 200:
orgs = response.json()['data']
for org in orgs:
print(f"Organization: {org['name']} (ID: {org['id']})")
print(f" Role: {org['role']}")
print(f" Created: {org['created_at']}")
return orgs
else:
print(f"Error: {response.status_code} - {response.text}")
return None
orgs = get_organization()
Listing Users and Their Roles
Knowing who has access to your organization is crucial for security:
def list_users(org_id):
response = requests.get(
f"{BASE_URL}/organizations/{org_id}/users",
headers=headers
)
if response.status_code == 200:
users = response.json()['data']
for user in users:
print(f"User: {user['email']} - Role: {user['role']}")
print(f" Status: {user['status']}")
print(f" Last active: {user.get('last_active_at', 'N/A')}")
return users
else:
print(f"Error: {response.status_code}")
return None
Inviting New Users
To add team members to your organization:
def invite_user(org_id, email, role="member"):
payload = {
"email": email,
"role": role # Options: "admin", "member", "billing"
}
response = requests.post(
f"{BASE_URL}/organizations/{org_id}/users",
headers=headers,
json=payload
)
if response.status_code == 201:
print(f"Invitation sent to {email}")
return response.json()
else:
print(f"Failed to invite user: {response.text}")
return None
Example: Invite a new admin
invite_user("org_abc123", "[email protected]", role="admin")
Updating User Roles
As team members change responsibilities, you can update their roles:
def update_user_role(org_id, user_id, new_role):
payload = {"role": new_role}
response = requests.patch(
f"{BASE_URL}/organizations/{org_id}/users/{user_id}",
headers=headers,
json=payload
)
if response.status_code == 200:
print(f"User {user_id} role updated to {new_role}")
return response.json()
else:
print(f"Failed to update role: {response.text}")
return None
API Key Management
Creating API Keys
For security best practices, each developer or service should have its own API key:
def create_api_key(org_id, name, scopes=None):
payload = {
"name": name,
"scopes": scopes or ["api:read", "api:write"]
}
response = requests.post(
f"{BASE_URL}/organizations/{org_id}/api_keys",
headers=headers,
json=payload
)
if response.status_code == 201:
key_data = response.json()
print(f"API Key created: {key_data['key']}")
print(f"Key ID: {key_data['id']}")
# Store this key securely - you won't see it again!
return key_data
else:
print(f"Failed to create key: {response.text}")
return None
Create a key for a CI/CD pipeline
create_api_key("org_abc123", "ci-cd-pipeline-v1")
Listing and Revoking API Keys
Regular key audits help maintain security:
def list_api_keys(org_id):
response = requests.get(
f"{BASE_URL}/organizations/{org_id}/api_keys",
headers=headers
)
if response.status_code == 200:
keys = response.json()['data']
for key in keys:
print(f"Key: {key['name']} (ID: {key['id']})")
print(f" Created: {key['created_at']}")
print(f" Last used: {key.get('last_used_at', 'Never')}")
return keys
def revoke_api_key(org_id, key_id):
response = requests.delete(
f"{BASE_URL}/organizations/{org_id}/api_keys/{key_id}",
headers=headers
)
if response.status_code == 204:
print(f"API key {key_id} revoked successfully")
return True
else:
print(f"Failed to revoke key: {response.text}")
return False
Billing and Usage Management
Viewing Current Usage
Monitor your API consumption to avoid surprises:
def get_usage(org_id, start_date, end_date):
params = {
"start_date": start_date, # Format: YYYY-MM-DD
"end_date": end_date
}
response = requests.get(
f"{BASE_URL}/organizations/{org_id}/usage",
headers=headers,
params=params
)
if response.status_code == 200:
usage = response.json()
print(f"Total tokens used: {usage['total_tokens']}")
print(f"Input tokens: {usage['input_tokens']}")
print(f"Output tokens: {usage['output_tokens']}")
print(f"Estimated cost: ${usage['estimated_cost']:.2f}")
return usage
else:
print(f"Error fetching usage: {response.text}")
return None
Get usage for the last 30 days
from datetime import datetime, timedelta
end = datetime.now().strftime("%Y-%m-%d")
start = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")
get_usage("org_abc123", start, end)
Setting Spending Limits
Prevent runaway costs with budget controls:
def set_spending_limit(org_id, limit_amount, currency="USD"):
payload = {
"spending_limit": {
"amount": limit_amount,
"currency": currency
}
}
response = requests.put(
f"{BASE_URL}/organizations/{org_id}/billing",
headers=headers,
json=payload
)
if response.status_code == 200:
print(f"Spending limit set to ${limit_amount} {currency}")
return response.json()
else:
print(f"Failed to set limit: {response.text}")
return None
Set a monthly limit of $500
set_spending_limit("org_abc123", 500.00)
Best Practices for Enterprise Management
1. Role-Based Access Control
Assign the minimum necessary permissions:
| Role | Permissions |
|---|---|
| Admin | Full access: manage users, keys, billing |
| Member | Use API keys, view usage |
| Billing | View and manage billing only |
2. API Key Rotation Policy
Implement regular key rotation with this automation script:
def rotate_api_key(org_id, old_key_id, new_key_name):
# Step 1: Create new key
new_key = create_api_key(org_id, new_key_name)
if not new_key:
return None
# Step 2: Update your applications to use the new key
print(f"IMPORTANT: Update all services to use: {new_key['key']}")
# Step 3: After confirming new key works, revoke old key
confirmation = input("Have you updated all services? (yes/no): ")
if confirmation.lower() == "yes":
revoke_api_key(org_id, old_key_id)
print("Key rotation complete!")
else:
print("Key rotation paused. Old key remains active.")
return new_key
3. Audit Logging
Track all organization changes for compliance:
def get_audit_logs(org_id, limit=50):
params = {"limit": limit}
response = requests.get(
f"{BASE_URL}/organizations/{org_id}/audit_logs",
headers=headers,
params=params
)
if response.status_code == 200:
logs = response.json()['data']
for log in logs:
print(f"[{log['timestamp']}] {log['action']} by {log['actor']['email']}")
print(f" Details: {json.dumps(log['details'], indent=2)}")
return logs
else:
print(f"Error fetching audit logs: {response.text}")
return None
Troubleshooting Common Issues
403 Forbidden Errors
If you receive a 403 when trying to manage your organization:
# Check your current permissions
def check_permissions():
response = requests.get(f"{BASE_URL}/me", headers=headers)
if response.status_code == 200:
me = response.json()
print(f"Your role: {me['role']}")
print(f"Your organization: {me['organization']['name']}")
if me['role'] != 'admin':
print("WARNING: You need admin privileges for this operation")
return me
else:
print(f"Error: {response.text}")
return None
Rate Limiting
When making many API calls, implement exponential backoff:
import time
def api_call_with_retry(url, headers, max_retries=3):
for attempt in range(max_retries):
response = requests.get(url, headers=headers)
if response.status_code == 429:
wait_time = 2 ** attempt
print(f"Rate limited. Waiting {wait_time} seconds...")
time.sleep(wait_time)
elif response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
return None
print("Max retries exceeded")
return None
Conclusion
Managing your Anthropic organization programmatically gives you fine-grained control over your Claude AI deployment. By automating user management, key rotation, and billing oversight, you can maintain security and cost efficiency as your team scales.
Remember that the API management endpoints are separate from the Claude chat API—they use the same authentication but different base paths. Always store your API keys securely using environment variables or a secrets manager, never hardcode them.
Key Takeaways
- Organization management is fully programmable via the Anthropic API, allowing you to automate user invitations, role changes, and API key creation
- Implement role-based access control by assigning admin, member, or billing roles based on actual user needs
- Regular API key rotation is essential for security—automate the process with the provided scripts
- Set spending limits to prevent unexpected costs and monitor usage with the billing API
- Audit logs provide a complete history of changes for compliance and security monitoring