Troubleshooting
Version: 1.0 Last Updated: 2026-02-03
Table of Contents
- Authentication Issues
- API Request Errors
- Database Connection Issues
- Rate Limiting
- Performance Issues
- Integration Issues
- Common Error Codes
- Getting Help
Authentication Issues
Issue: 401 Unauthorized
Symptoms:
{
"detail": "Could not validate credentials"
}
Common Causes:
- Token expired (8-hour lifetime)
- Invalid token format
- Token revoked/blacklisted
- Missing Authorization header
Solutions:
# Solution 1: Check token format
# ✅ Correct
headers = {"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}
# ❌ Wrong - missing "Bearer"
headers = {"Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}
# Solution 2: Refresh expired token
import requests
def refresh_token(current_token):
response = requests.post(
"https://api.ainative.studio/v1/auth/refresh",
headers={"Authorization": f"Bearer {current_token}"}
)
if response.status_code == 200:
return response.json()["access_token"]
else:
# Token too old - need to re-login
return login()
# Solution 3: Re-login if token is blacklisted
def login():
response = requests.post(
"https://api.ainative.studio/v1/auth/login-json",
json={
"username": "user@example.com",
"password": "password"
}
)
return response.json()["access_token"]
Issue: 403 Forbidden
Symptoms:
{
"detail": "Insufficient permissions"
}
Common Causes:
- User role doesn't have required permissions
- Accessing admin-only endpoints with user token
- Resource belongs to another user
Solutions:
# Check your current user role
response = requests.get(
"https://api.ainative.studio/v1/auth/me",
headers={"Authorization": f"Bearer {token}"}
)
user_data = response.json()
print(f"Your role: {user_data['role']}")
# Required roles:
# - USER: Standard API access
# - ADMIN: Admin endpoints
# - DEVELOPER: Advanced features
Issue: Invalid API Key
Symptoms:
{
"detail": "Invalid API key"
}
Common Causes:
- API key revoked or expired
- Wrong header name
- Typo in API key
Solutions:
# Solution 1: Verify API key format
# ✅ Correct formats
headers = {"X-API-Key": "sk_live_abc123..."}
# OR
headers = {"Authorization": "Bearer sk_live_abc123..."}
# ❌ Wrong header name
headers = {"Api-Key": "sk_live_abc123..."}
# Solution 2: List your active API keys
response = requests.get(
"https://api.ainative.studio/v1/api-keys",
headers={"Authorization": f"Bearer {jwt_token}"}
)
print(response.json())
# Solution 3: Create new API key
response = requests.post(
"https://api.ainative.studio/v1/api-keys",
headers={"Authorization": f"Bearer {jwt_token}"},
json={"name": "New Key", "expires_in_days": 90}
)
new_key = response.json()["api_key"]
print(f"New API Key: {new_key}")
API Request Errors
Issue: 422 Validation Error
Symptoms:
{
"detail": [
{
"loc": ["body", "email"],
"msg": "value is not a valid email address",
"type": "value_error.email"
}
]
}
Common Causes:
- Missing required fields
- Invalid data types
- Data doesn't match expected format
Solutions:
# Validate request data before sending
from pydantic import BaseModel, EmailStr, validator
class UserCreate(BaseModel):
email: EmailStr
password: str
full_name: str
@validator('password')
def password_strength(cls, v):
if len(v) < 8:
raise ValueError('Password must be at least 8 characters')
if not any(c.isupper() for c in v):
raise ValueError('Password must contain uppercase letter')
if not any(c.islower() for c in v):
raise ValueError('Password must contain lowercase letter')
if not any(c.isdigit() for c in v):
raise ValueError('Password must contain number')
return v
# Use the model to validate
try:
user_data = UserCreate(
email="user@example.com",
password="SecurePass123!",
full_name="John Doe"
)
response = requests.post(
"https://api.ainative.studio/v1/auth/register",
json=user_data.dict()
)
except ValueError as e:
print(f"Validation error: {e}")
Issue: 404 Not Found
Symptoms:
{
"detail": "Not found"
}
Common Causes:
- Wrong endpoint URL
- Resource doesn't exist
- Resource ID is incorrect
- Missing trailing slash (depending on endpoint)
Solutions:
# Solution 1: Verify endpoint exists
# Check API documentation for correct path
# Solution 2: List resources first
response = requests.get(
"https://api.ainative.studio/v1/database/projects",
headers={"Authorization": f"Bearer {token}"}
)
projects = response.json()
if projects:
project_id = projects[0]["id"]
else:
# No projects - create one first
response = requests.post(
"https://api.ainative.studio/v1/database/projects",
headers={"Authorization": f"Bearer {token}"},
json={"name": "My Project", "description": "Test"}
)
project_id = response.json()["id"]
# Solution 3: Check for trailing slash
# Both should work, but be consistent
url1 = "https://api.ainative.studio/v1/auth/me" # ✅
url2 = "https://api.ainative.studio/v1/auth/me/" # ✅
Issue: 409 Conflict
Symptoms:
{
"detail": "Email already registered"
}
Common Causes:
- Duplicate email/username
- Resource already exists
- Concurrent modification
Solutions:
# Solution: Check if resource exists first
def create_or_get_user(email, password, full_name):
try:
# Try to create
response = requests.post(
"https://api.ainative.studio/v1/auth/register",
json={
"email": email,
"password": password,
"full_name": full_name
}
)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 409:
# User exists - login instead
response = requests.post(
"https://api.ainative.studio/v1/auth/login-json",
json={"username": email, "password": password}
)
return response.json()
raise
Database Connection Issues
Issue: Connection Pool Exhausted
Symptoms:
{
"detail": "QueuePool limit of size 20 overflow 10 reached"
}
Common Causes:
- Too many concurrent requests
- Long-running queries
- Connections not being closed
Solutions:
# Solution 1: Use connection pooling wisely
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
session = requests.Session()
retry = Retry(
total=3,
backoff_factor=0.3,
status_forcelist=[500, 502, 503, 504]
)
adapter = HTTPAdapter(max_retries=retry, pool_connections=10, pool_maxsize=10)
session.mount('https://', adapter)
# Use session instead of requests directly
response = session.get(
"https://api.ainative.studio/v1/database/projects",
headers={"Authorization": f"Bearer {token}"}
)
# Solution 2: Add delays between requests
import time
for i in range(100):
response = make_request()
time.sleep(0.1) # 100ms delay
# Solution 3: Use async for concurrent requests
import asyncio
import aiohttp
async def fetch_project(session, project_id):
async with session.get(
f"https://api.ainative.studio/v1/database/projects/{project_id}",
headers={"Authorization": f"Bearer {token}"}
) as response:
return await response.json()
async def fetch_all_projects(project_ids):
async with aiohttp.ClientSession() as session:
tasks = [fetch_project(session, pid) for pid in project_ids]
return await asyncio.gather(*tasks)
# Run async
results = asyncio.run(fetch_all_projects([1, 2, 3, 4, 5]))
Issue: Database Query Timeout
Symptoms:
{
"detail": "Query execution timeout"
}
Common Causes:
- Complex queries without indexes
- Large result sets without pagination
- Slow database performance
Solutions:
# Solution 1: Add pagination
def fetch_all_records_paginated(table_name):
all_records = []
skip = 0
limit = 100 # Fetch 100 at a time
while True:
response = requests.post(
"https://api.ainative.studio/v1/database/query",
headers={"Authorization": f"Bearer {token}"},
json={
"project_id": "proj_123",
"query": f"SELECT * FROM {table_name} OFFSET {skip} LIMIT {limit}"
}
)
data = response.json()
records = data["rows"]
if not records:
break
all_records.extend(records)
skip += limit
return all_records
# Solution 2: Optimize queries
# ❌ Slow
query = "SELECT * FROM large_table"
# ✅ Fast - specific columns
query = "SELECT id, name FROM large_table WHERE created_at > '2026-01-01' LIMIT 1000"
# Solution 3: Use indexes
# Create index via SQL
query = "CREATE INDEX idx_email ON users(email)"
Rate Limiting
Issue: 429 Too Many Requests
Symptoms:
{
"detail": "Rate limit exceeded. Try again in 30 seconds.",
"retry_after": 30
}
Common Causes:
- Exceeded requests per minute (60 for free tier)
- Burst of requests
- No rate limiting in client code
Solutions:
# Solution 1: Implement exponential backoff
import time
import requests
def make_request_with_retry(url, headers, max_retries=3):
for attempt in range(max_retries):
response = requests.get(url, headers=headers)
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', 60))
print(f"Rate limited. Waiting {retry_after} seconds...")
time.sleep(retry_after)
continue
return response
raise Exception("Max retries exceeded")
# Solution 2: Track request rate
from collections import deque
from time import time, sleep
class RateLimiter:
def __init__(self, max_requests=60, time_window=60):
self.max_requests = max_requests
self.time_window = time_window
self.requests = deque()
def wait_if_needed(self):
now = time()
# Remove old requests outside time window
while self.requests and now - self.requests[0] > self.time_window:
self.requests.popleft()
# If at limit, wait
if len(self.requests) >= self.max_requests:
sleep_time = self.time_window - (now - self.requests[0])
if sleep_time > 0:
print(f"Rate limit reached. Sleeping {sleep_time:.2f}s")
sleep(sleep_time)
self.requests.append(now)
# Usage
limiter = RateLimiter(max_requests=60, time_window=60)
for i in range(200):
limiter.wait_if_needed()
response = make_request()
# Solution 3: Upgrade tier
# Free: 60/min, Pro: 300/min, Enterprise: 1000/min
# Visit: https://ainative.studio/pricing
Performance Issues
Issue: Slow Response Times
Symptoms:
- Requests taking > 5 seconds
- Timeouts
- Degraded performance
Solutions:
# Solution 1: Measure performance
import time
start = time.time()
response = requests.get(url, headers=headers)
elapsed = time.time() - start
print(f"Request took {elapsed:.2f}s")
# Solution 2: Use compression
headers = {
"Authorization": f"Bearer {token}",
"Accept-Encoding": "gzip, deflate"
}
# Solution 3: Optimize queries
# ❌ Slow - fetching unnecessary data
query = "SELECT * FROM users JOIN orders ON users.id = orders.user_id"
# ✅ Fast - only needed columns
query = "SELECT users.id, users.name, COUNT(orders.id) as order_count FROM users JOIN orders ON users.id = orders.user_id GROUP BY users.id LIMIT 100"
# Solution 4: Cache results
from functools import lru_cache
import time
@lru_cache(maxsize=100)
def fetch_user(user_id):
response = requests.get(
f"https://api.ainative.studio/v1/users/{user_id}",
headers={"Authorization": f"Bearer {token}"}
)
return response.json()
# Subsequent calls will be cached
user1 = fetch_user("user_123") # API call
user2 = fetch_user("user_123") # Cached
Integration Issues
Issue: Webhook Not Receiving Events
Symptoms:
- Webhook endpoint configured but no events received
- Events missing or delayed
Solutions:
# Solution 1: Verify webhook is active
response = requests.get(
"https://api.ainative.studio/v1/webhooks",
headers={"Authorization": f"Bearer {token}"}
)
print(response.json())
# Solution 2: Test webhook endpoint
import hmac
import hashlib
def verify_webhook_signature(payload, signature, secret):
expected = hmac.new(
secret.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected)
# Your webhook handler
from flask import Flask, request
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def handle_webhook():
# Verify signature
signature = request.headers.get('X-Signature')
payload = request.get_data(as_text=True)
if not verify_webhook_signature(payload, signature, WEBHOOK_SECRET):
return {'error': 'Invalid signature'}, 401
event = request.json
print(f"Received event: {event['type']}")
# Process event
if event['type'] == 'agent.task.completed':
handle_task_completion(event['data'])
return {'status': 'ok'}, 200
# Solution 3: Make endpoint publicly accessible
# Ensure your webhook URL is:
# - Publicly accessible (not localhost)
# - Uses HTTPS
# - Returns 200 status code
# - Responds within 30 seconds
Common Error Codes
| Code | Meaning | Common Cause | Solution |
|---|---|---|---|
| 400 | Bad Request | Invalid request format | Check request body matches schema |
| 401 | Unauthorized | Invalid/expired token | Refresh token or re-login |
| 403 | Forbidden | Insufficient permissions | Check user role |
| 404 | Not Found | Wrong URL or resource doesn't exist | Verify endpoint and resource ID |
| 409 | Conflict | Duplicate resource | Check if resource already exists |
| 422 | Validation Error | Invalid field values | Validate data before sending |
| 429 | Too Many Requests | Rate limit exceeded | Implement rate limiting |
| 500 | Internal Server Error | Server issue | Retry with exponential backoff |
| 502 | Bad Gateway | Gateway/proxy error | Check service status |
| 503 | Service Unavailable | Maintenance or overload | Retry later |
Getting Help
Step 1: Check Documentation
Step 2: Search Existing Issues
Search GitHub Issues: https://github.com/ainative/core/issues
Step 3: Enable Debug Logging
import logging
import requests
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
# Make request with debug output
response = requests.get(
url,
headers=headers
)
print(f"Status Code: {response.status_code}")
print(f"Headers: {response.headers}")
print(f"Body: {response.text}")
Step 4: Contact Support
If you still need help:
Email: support@ainative.studio
Include in your message:
- Error message (full JSON response)
- Request details (endpoint, method, headers)
- Code sample (without credentials!)
- Expected vs. actual behavior
- Environment (Python version, OS, etc.)
Example Support Email:
Subject: 401 Error on /v1/database/projects Endpoint
Hello,
I'm getting a 401 Unauthorized error when calling the projects endpoint.
Error Response:
{
"detail": "Could not validate credentials"
}
Request Details:
- Endpoint: GET /v1/database/projects
- Headers: Authorization: Bearer eyJhbG...
- Python Version: 3.9.7
- OS: macOS 13.1
Code Sample:
response = requests.get(
"https://api.ainative.studio/v1/database/projects",
headers={"Authorization": f"Bearer {token}"}
)
Expected: List of projects
Actual: 401 error
The token was just generated 5 minutes ago via /v1/auth/login-json.
Thanks for your help!
Service Status
Check real-time service status:
Subscribe to status updates for:
- Planned maintenance notifications
- Incident reports
- Performance metrics
Last Updated: 2026-02-03 Version: 1.0
Refs #1015