Authentication
Sub2API uses API keys to authenticate requests. This page covers everything you need to know about creating, using, and managing your API keys.
API Key Overview
- Format: Keys are prefixed with
sk-followed by a random string - Security: Keys are encrypted at rest and never logged
- Visibility: Full key shown only once at creation
- Revocation: Can be disabled or deleted anytime
- Scope: Each key belongs to a workspace (personal or organization)
Creating API Keys
Via Console
- Log in to app.tokenlio.ai
- Navigate to API Keys
- Click Create New Key
- Enter a descriptive name
- (Optional) Set quota limits
- Click Create
- Copy the key immediately - you won't see it again
Key Naming Best Practices
Use descriptive names to identify keys later:
- ✅
production-web-app - ✅
development-local - ✅
data-pipeline-service - ✅
mobile-app-ios - ❌
key1,test,temp
Using API Keys
HTTP Header
Include your API key in the Authorization header as a Bearer token:
curl https://api.tokenlio.ai/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "gpt-4-turbo", "messages": [{"role": "user", "content": "Hello"}]}'OpenAI SDK
The OpenAI SDK handles authentication automatically:
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.tokenlio.ai/v1"
)
# SDK adds Authorization header automatically
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[{"role": "user", "content": "Hello"}]
)Environment Variables
Never hardcode API keys in your source code. Use environment variables instead:
# .env file
SUB2API_KEY=sk-your-key-here# Python
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv('SUB2API_KEY')// Node.js
import 'dotenv/config';
const apiKey = process.env.SUB2API_KEY;Key Quotas and Limits
You can set optional limits when creating a key:
Request Quota
Limit the total number of requests this key can make:
- Useful for testing or demo keys
- Resets when you update the quota
- Key is disabled when quota is reached
Rate Limits
Control requests per minute:
- Prevents runaway costs
- Useful for batch processing
- Returns 429 error when exceeded
Monthly Spend Limit
Cap spending per key per month:
- Calculated in UTC calendar months
- Prevents budget overruns
- Key is disabled when limit is reached
TIP
Quota and rate limits apply per key. Workspace-level limits are separate and checked first.
Key Management
Viewing Keys
In the console, you can see:
- Key name
- Key prefix (e.g.,
sk-abc...xyz) - Status (active/disabled)
- Created date
- Last used date
- Usage statistics
WARNING
The full key is never shown again after creation. You'll only see a masked version.
Disabling Keys
Temporarily disable a key without deleting it:
- Go to API Keys
- Click the key you want to disable
- Click Disable
- Confirm the action
Disabled keys:
- Return 401 errors immediately
- Can be re-enabled anytime
- Preserve usage history
Deleting Keys
Permanently remove a key:
- Go to API Keys
- Click the key you want to delete
- Click Delete
- Confirm - this cannot be undone
DANGER
Deleted keys cannot be recovered. Any application using this key will immediately fail.
Rotating Keys
To rotate a key:
- Create a new key
- Update your application to use the new key
- Verify the new key works
- Delete the old key
TIP
Use separate keys for dev/staging/production so you can rotate them independently.
Security Best Practices
Do's ✅
- Store keys securely in environment variables or secrets managers
- Use separate keys for development, staging, and production
- Rotate keys regularly (every 90 days recommended)
- Delete unused keys immediately
- Monitor key usage for anomalies
- Set quota limits on test and demo keys
- Use descriptive names to identify keys later
Don'ts ❌
- Never commit keys to version control (Git, SVN, etc.)
- Never share keys via email, Slack, or other messaging
- Never hardcode keys in client-side JavaScript
- Never log keys in your application logs
- Never reuse keys across multiple applications
- Never use production keys in development
If a Key is Compromised
If you suspect a key has been exposed:
- Immediately disable the key in the console
- Check usage logs for unauthorized activity
- Create a new key as a replacement
- Update your application with the new key
- Delete the compromised key
- Review your security practices
Contact support@tokenlio.ai if you notice suspicious activity.
Workspace Context
API keys belong to workspaces:
Personal Workspace
- Keys you create in your personal workspace
- Charged to your personal balance
- Only you can manage these keys
Organization Workspace
- Keys created within an organization
- Charged to the organization's balance
- Owner can manage all keys
- Members can only manage their own keys
When making a request, the key determines which balance is charged. You cannot change a key's workspace after creation.
Authentication Errors
401 Unauthorized
Cause: Invalid, missing, or disabled API key
Solutions:
- Verify the key is correct (check for extra spaces)
- Ensure the key is active in the console
- Check the Authorization header format:
Bearer YOUR_KEY
403 Forbidden
Cause: Valid key but insufficient permissions
Solutions:
- Verify the model is available in your workspace
- Check if the workspace has access to the requested model
- Contact support if you need access
429 Rate Limited
Cause: Too many requests
Solutions:
- Implement exponential backoff
- Check your key's rate limits
- Spread requests over time
- Contact support for higher limits
Advanced Topics
Server-to-Server Authentication
For backend services:
# Read key from secure environment
import os
api_key = os.environ['SUB2API_KEY']
# Use in long-running service
client = OpenAI(api_key=api_key, base_url="https://api.tokenlio.ai/v1")Proxy Authentication
If using a proxy or middleware:
// Express middleware example
app.use((req, res, next) => {
const apiKey = process.env.SUB2API_KEY;
req.openaiClient = new OpenAI({
apiKey: apiKey,
baseURL: 'https://api.tokenlio.ai/v1'
});
next();
});Multi-Key Applications
For applications using multiple keys:
# Different keys for different models or rate limits
class APIClients:
def __init__(self):
self.gpt4_client = OpenAI(
api_key=os.getenv('SUB2API_GPT4_KEY'),
base_url="https://api.tokenlio.ai/v1"
)
self.claude_client = OpenAI(
api_key=os.getenv('SUB2API_CLAUDE_KEY'),
base_url="https://api.tokenlio.ai/v1"
)Testing Authentication
Verify your authentication setup:
# Test with curl
curl https://api.tokenlio.ai/v1/models \
-H "Authorization: Bearer YOUR_API_KEY"
# Should return list of available models
# 401 error means authentication failed