API Key Management
Provision and manage API keys with granular controls and security features
Comprehensive Key Management
ParrotRouter provides enterprise-grade API key management with fine-grained permissions, usage controls, and comprehensive security features. Create keys for different environments, team members, or applications with specific access rights.
Granular Permissions
Control access to specific models and features
Security Controls
IP restrictions, domain limits, and more
Usage Analytics
Track usage per key with detailed metrics
Creating API Keys
Create API keys programmatically or through the dashboard:
import requests
# Create a new API key
response = requests.post(
"https://api.parrotrouter.com/v1/keys",
headers={
"Authorization": "Bearer your-master-key",
"Content-Type": "application/json"
},
json={
"name": "Production App Key",
"description": "Key for production application",
"permissions": {
"models": [
"gpt-4-turbo-preview",
"gpt-3.5-turbo",
"claude-3-opus"
],
"features": [
"chat_completion",
"embeddings",
"structured_outputs"
],
"operations": ["read", "write"],
"max_requests_per_minute": 100,
"max_requests_per_day": 10000,
"max_cost_per_day": 50.00
},
"restrictions": {
"ip_whitelist": ["203.0.113.0/24"],
"domains": ["app.yourcompany.com", "*.yourcompany.com"],
"referrers": ["https://app.yourcompany.com/*"],
"user_agents": ["YourApp/1.0"]
},
"metadata": {
"environment": "production",
"team": "backend",
"cost_center": "engineering"
},
"expires_at": "2024-12-31T23:59:59Z"
}
)
key_data = response.json()
print(f"API Key: {key_data['key']}")
print(f"Key ID: {key_data['id']}")
print(f"Created: {key_data['created_at']}")
# IMPORTANT: Store the key securely - it won't be shown again!
Key Permission Levels
Model Permissions
Control which AI models can be accessed with each key.
# Fine-grained model permissions
permissions = {
"models": {
"allowed": [
"gpt-4-turbo-preview",
"gpt-3.5-turbo",
"claude-3-opus",
"claude-3-sonnet"
],
"denied": [
"gpt-4-vision-preview", # No vision models
"dall-e-*" # No image generation
],
"cost_limits": {
"gpt-4-turbo-preview": {
"max_requests_per_day": 100,
"max_tokens_per_request": 4000,
"max_cost_per_day": 10.00
},
"gpt-3.5-turbo": {
"max_requests_per_day": 1000,
"max_tokens_per_request": 2000
}
}
},
"routing": {
"allow_auto_routing": True,
"allowed_providers": ["openai", "anthropic"],
"force_provider": None, # Or specific provider
"fallback_allowed": True
}
}
Feature Permissions
Enable or disable specific features per key.
# Feature-level permissions
permissions = {
"features": {
"chat_completion": True,
"embeddings": True,
"function_calling": False, # Disabled
"vision": False,
"structured_outputs": True,
"streaming": True,
"web_search": False,
"prompt_caching": True,
"message_transforms": False
},
"advanced_features": {
"zero_completion_insurance": False,
"custom_presets": True,
"batch_processing": True,
"priority_queue": False
},
"data_access": {
"log_requests": True,
"log_responses": False, # Privacy
"export_data": False,
"delete_data": False
}
}
Rate Limiting
Set usage limits to control costs and prevent abuse.
# Comprehensive rate limiting
rate_limits = {
"requests": {
"per_second": 10,
"per_minute": 100,
"per_hour": 1000,
"per_day": 10000,
"burst_size": 20 # Allow short bursts
},
"tokens": {
"input_per_minute": 100000,
"output_per_minute": 50000,
"total_per_day": 10000000
},
"costs": {
"per_request_max": 1.00,
"per_hour_max": 10.00,
"per_day_max": 100.00,
"per_month_max": 1000.00,
"alert_threshold": 0.8 # Alert at 80%
},
"concurrency": {
"max_parallel_requests": 5,
"max_queued_requests": 20
}
}
Security Features
Implement comprehensive security controls for your API keys:
# Advanced security configuration
security_config = {
"network_restrictions": {
"ip_whitelist": [
"203.0.113.0/24", # Office network
"198.51.100.42/32", # CI/CD server
"2001:db8::/32" # IPv6 range
],
"ip_blacklist": [
"192.0.2.0/24" # Known bad actors
],
"require_https": True,
"allowed_origins": [
"https://app.company.com",
"https://*.company.com"
],
"blocked_countries": ["XX", "YY"] # ISO codes
},
"authentication": {
"require_signature": True,
"signature_algorithm": "HMAC-SHA256",
"require_timestamp": True,
"max_timestamp_age": 300, # 5 minutes
"require_nonce": True
},
"domain_restrictions": {
"allowed_domains": [
"app.company.com",
"*.company.com"
],
"allowed_referrers": [
"https://app.company.com/*"
],
"user_agent_pattern": "^YourApp/\d+\.\d+"
},
"audit": {
"log_all_requests": True,
"log_failures": True,
"alert_on_suspicious": True,
"retention_days": 90
}
}
# Create key with security config
response = requests.post(
"https://api.parrotrouter.com/v1/keys",
headers={"Authorization": "Bearer your-master-key"},
json={
"name": "Secure Production Key",
"security": security_config
}
)
Key Rotation
Automatic Rotation
# Configure automatic key rotation
rotation_config = {
"enabled": True,
"schedule": "0 0 1 * *", # Monthly
"strategy": "gradual", # or "immediate"
"notification_channels": [
"email:security@company.com",
"webhook:https://api.company.com/key-rotation"
],
"grace_period_hours": 24,
"auto_update_apps": True
}
response = requests.post(
f"https://api.parrotrouter.com/v1/keys/{key_id}/rotation",
headers={"Authorization": "Bearer your-master-key"},
json=rotation_config
)
# Manual rotation
response = requests.post(
f"https://api.parrotrouter.com/v1/keys/{key_id}/rotate",
headers={"Authorization": "Bearer your-master-key"},
json={
"invalidate_old": False, # Keep old key active
"grace_period_hours": 48 # Overlap period
}
)
new_key = response.json()
print(f"New key: {new_key['key']}")
print(f"Old key expires: {new_key['old_key_expires_at']}")
Key Lifecycle Management
# Update key permissions
response = requests.patch(
f"https://api.parrotrouter.com/v1/keys/{key_id}",
headers={"Authorization": "Bearer your-master-key"},
json={
"permissions": {
"max_requests_per_day": 5000 # Reduce limit
},
"expires_at": "2024-06-30T23:59:59Z"
}
)
# Temporarily disable key
response = requests.post(
f"https://api.parrotrouter.com/v1/keys/{key_id}/disable",
headers={"Authorization": "Bearer your-master-key"},
json={
"reason": "Suspicious activity detected",
"auto_enable_after": "1h" # Auto re-enable
}
)
# Revoke key permanently
response = requests.delete(
f"https://api.parrotrouter.com/v1/keys/{key_id}",
headers={"Authorization": "Bearer your-master-key"},
json={
"reason": "Key compromised",
"revoke_immediately": True
}
)
Team & Organization Keys
Manage keys for teams and organizations with role-based access:
# Create team-scoped key
team_key = requests.post(
"https://api.parrotrouter.com/v1/keys",
headers={"Authorization": "Bearer your-admin-key"},
json={
"name": "Frontend Team Key",
"type": "team",
"scope": {
"organization_id": "org_123",
"team_id": "team_frontend",
"projects": ["project_a", "project_b"]
},
"permissions": {
"inherit_from": "team_default",
"overrides": {
"models": ["gpt-3.5-turbo"], # Only GPT-3.5
"max_cost_per_day": 20.00
}
},
"members": [
{
"user_id": "user_123",
"role": "admin",
"can_manage_key": True
},
{
"user_id": "user_456",
"role": "developer",
"can_manage_key": False
}
]
}
)
# Create environment-specific keys
environments = ["development", "staging", "production"]
for env in environments:
response = requests.post(
"https://api.parrotrouter.com/v1/keys",
headers={"Authorization": "Bearer your-admin-key"},
json={
"name": f"{env.title()} Environment Key",
"environment": env,
"permissions": {
"development": {
"all_models": True,
"all_features": True,
"max_cost_per_day": 10.00
},
"staging": {
"models": ["gpt-4-turbo-preview", "gpt-3.5-turbo"],
"max_cost_per_day": 50.00
},
"production": {
"models": ["gpt-4-turbo-preview"],
"require_approval": True,
"max_cost_per_day": 500.00
}
}[env]
}
)
Usage Monitoring
Real-time Analytics
# Get key usage analytics
analytics = requests.get(
f"https://api.parrotrouter.com/v1/keys/{key_id}/analytics",
headers={"Authorization": "Bearer your-master-key"},
params={
"period": "7d",
"granularity": "hour"
}
).json()
print(f"Total requests: {analytics['total_requests']}")
print(f"Total cost: $" + str(analytics['total_cost']))
print(f"Average latency: {analytics['avg_latency_ms']}ms")
print(f"Error rate: {analytics['error_rate']}%")
# Model usage breakdown
print("
Model Usage:")
for model in analytics['models']:
print(f" {model['name']}: {model['requests']} requests, $" + str(model['cost']))
# Feature usage
print("
Feature Usage:")
for feature in analytics['features']:
print(f" {feature['name']}: {feature['usage_count']}")
# Real-time monitoring
import websocket
def on_usage_update(ws, message):
data = json.loads(message)
if data['cost'] > 1.00: # Alert on expensive requests
print(f"High cost request: $" + str(data['cost']) + f" for {data['model']}")
ws = websocket.WebSocketApp(
f"wss://api.parrotrouter.com/v1/keys/{key_id}/usage/stream",
header=["Authorization: Bearer your-master-key"],
on_message=on_usage_update
)
ws.run_forever()
Audit Logs
# Get audit logs for key
audit_logs = requests.get(
f"https://api.parrotrouter.com/v1/keys/{key_id}/audit",
headers={"Authorization": "Bearer your-master-key"},
params={
"start_date": "2024-01-01",
"end_date": "2024-01-31",
"event_types": ["usage", "permission_change", "security_alert"]
}
).json()
for log in audit_logs['events']:
print(f"
{log['timestamp']}: {log['event_type']}")
print(f" User: {log['user_id']}")
print(f" IP: {log['ip_address']}")
print(f" Details: {log['details']}")
# Export audit logs
export = requests.post(
f"https://api.parrotrouter.com/v1/keys/{key_id}/audit/export",
headers={"Authorization": "Bearer your-master-key"},
json={
"format": "csv", # or "json", "parquet"
"period": "last_quarter",
"include_pii": False
}
)
Best Practices
- 1.Use Separate Keys per Environment
Never use production keys in development or testing
- 2.Implement Key Rotation
Rotate keys regularly, especially for production systems
- 3.Monitor Usage Patterns
Set up alerts for unusual usage or spending
- 4.Use IP Whitelisting
Restrict keys to known IP addresses when possible