- Overview
- Authentication
- Base URL & Versioning
- Response Format
- Error Handling
- Rate Limiting
- API Endpoints
- Webhooks
- SDK & Integration Examples
The AI SaaS Platform provides a comprehensive RESTful API for managing AI-powered automation, analytics, and multi-tenant operations. The API is designed with modern standards including JWT authentication, tenant isolation, rate limiting, and comprehensive error handling.
- Multi-Tenant Architecture: Isolated data per tenant with shared infrastructure
- AI Agent Management: Create, deploy, and manage AI-powered automation agents
- Advanced Analytics: Real-time performance metrics and business intelligence
- Subscription Management: Integrated billing and plan management
- Enterprise Security: Bank-grade security with encryption and compliance
- Comprehensive Integration: Webhooks, API keys, and third-party integrations
https://your-domain.com/api/v1/
http://localhost:8000/api/v1/
https://your-domain.com/api/master/
- JWT Bearer Token (Recommended)
- API Key (For server-to-server)
- Session (Web interface only)
Authorization: Bearer {your_jwt_token}X-API-Key: {your_api_key}All API responses follow a consistent JSON structure:
{
"status": "success",
"message": "Operation completed successfully",
"data": {
// Response data here
},
"meta": {
"timestamp": "2024-01-20T10:30:00Z",
"request_id": "req_123456",
"version": "v1"
}
}{
"status": "error",
"message": "Error description",
"errors": {
"field": ["Validation error message"]
},
"meta": {
"timestamp": "2024-01-20T10:30:00Z",
"request_id": "req_123456",
"error_code": "VALIDATION_FAILED"
}
}{
"status": "success",
"data": [...],
"meta": {
"pagination": {
"current_page": 1,
"per_page": 15,
"total": 150,
"total_pages": 10,
"has_next": true,
"has_prev": false
}
}
}200- Success201- Created204- No Content400- Bad Request401- Unauthorized403- Forbidden404- Not Found409- Conflict422- Validation Error429- Rate Limit Exceeded500- Internal Server Error
{
"VALIDATION_FAILED": "Request validation failed",
"UNAUTHORIZED": "Authentication required",
"FORBIDDEN": "Insufficient permissions",
"NOT_FOUND": "Resource not found",
"RATE_LIMIT_EXCEEDED": "Too many requests",
"TENANT_NOT_FOUND": "Tenant does not exist",
"AGENT_LIMIT_REACHED": "Maximum agents limit reached",
"SUBSCRIPTION_REQUIRED": "Active subscription required",
"INSUFFICIENT_CREDITS": "Not enough API credits"
}- Starter: 100 requests/hour
- Pro: 1,000 requests/hour
- Enterprise: 10,000 requests/hour
- Custom: Negotiable
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200POST /api/v1/auth/register
Register a new user account.
Request:
{
"name": "John Doe",
"email": "john@example.com",
"password": "SecurePass123!",
"password_confirmation": "SecurePass123!",
"role": "user"
}Response:
{
"status": "success",
"message": "User registered successfully",
"data": {
"user": {
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"role": "user",
"created_at": "2024-01-20T10:30:00Z"
},
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
"token_type": "Bearer",
"expires_in": 3600
}
}POST /api/v1/auth/login
Authenticate user and obtain access token.
Request:
{
"email": "john@example.com",
"password": "SecurePass123!"
}Response:
{
"status": "success",
"message": "Login successful",
"data": {
"user": {
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"role": "user",
"last_login": "2024-01-20T10:30:00Z"
},
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
"token_type": "Bearer"
}
}GET /api/v1/auth/me
Get authenticated user information.
Headers:
Authorization: Bearer {token}Response:
{
"status": "success",
"data": {
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"role": "user",
"permissions": ["create_agents", "view_analytics"],
"tenant": {
"id": 1,
"name": "TechCorp Solutions",
"plan": "pro"
},
"preferences": {
"theme": "dark",
"timezone": "UTC"
}
}
}PUT /api/v1/auth/profile
Update user profile information.
Request:
{
"name": "John Smith",
"phone": "+1234567890",
"timezone": "America/New_York",
"preferences": {
"theme": "dark",
"notifications": true
}
}PUT /api/v1/auth/password
Change user password.
Request:
{
"current_password": "OldPass123!",
"new_password": "NewPass123!",
"new_password_confirmation": "NewPass123!"
}POST /api/v1/auth/api-key
Generate a new API key for server-to-server authentication.
Request:
{
"name": "Production API Key",
"permissions": ["agents.read", "analytics.read"]
}Response:
{
"status": "success",
"data": {
"api_key": "sk_live_1234567890abcdef",
"name": "Production API Key",
"permissions": ["agents.read", "analytics.read"],
"expires_at": "2025-01-20T10:30:00Z"
}
}POST /api/v1/auth/logout
Revoke access token and logout user.
Response:
{
"status": "success",
"message": "Logout successful"
}GET /api/v1/agents
Retrieve list of AI agents with filtering and search capabilities.
Query Parameters:
search(string): Search by agent nametype(string): Filter by agent type (chatbot, workflow, analytics, integration)status(string): Filter by status (active, inactive, training, error)page(integer): Page number for paginationper_page(integer): Items per page (max 100)
Response:
{
"status": "success",
"data": [
{
"id": 1,
"name": "Customer Support Bot",
"description": "AI-powered customer support automation",
"type": "chatbot",
"status": "active",
"model": "gpt-4",
"configuration": {
"temperature": 0.7,
"max_tokens": 1000,
"system_prompt": "You are a helpful customer support assistant..."
},
"statistics": {
"total_executions": 1247,
"success_rate": 96.5,
"avg_response_time": 1.2,
"last_executed": "2024-01-20T09:45:00Z"
},
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-20T08:15:00Z"
}
],
"meta": {
"pagination": {
"current_page": 1,
"per_page": 15,
"total": 25,
"total_pages": 2
}
}
}POST /api/v1/agents
Create a new AI agent.
Request:
{
"name": "Sales Lead Qualifier",
"description": "Automatically qualify and score sales leads",
"type": "workflow",
"model": "gpt-4",
"configuration": {
"temperature": 0.3,
"max_tokens": 500,
"system_prompt": "You are a sales lead qualification expert...",
"tools": ["web_search", "email", "crm_integration"],
"triggers": ["new_lead", "form_submission"]
},
"settings": {
"auto_execute": true,
"max_concurrent": 5,
"timeout": 30
}
}Response:
{
"status": "success",
"message": "AI Agent created successfully",
"data": {
"id": 26,
"name": "Sales Lead Qualifier",
"description": "Automatically qualify and score sales leads",
"type": "workflow",
"status": "inactive",
"model": "gpt-4",
"configuration": {
"temperature": 0.3,
"max_tokens": 500,
"system_prompt": "You are a sales lead qualification expert...",
"tools": ["web_search", "email", "crm_integration"],
"triggers": ["new_lead", "form_submission"]
},
"settings": {
"auto_execute": true,
"max_concurrent": 5,
"timeout": 30
},
"created_at": "2024-01-20T10:30:00Z"
}
}GET /api/v1/agents/{id}
Get detailed information about a specific AI agent.
Response:
{
"status": "success",
"data": {
"id": 1,
"name": "Customer Support Bot",
"description": "AI-powered customer support automation",
"type": "chatbot",
"status": "active",
"model": "gpt-4",
"configuration": {
"temperature": 0.7,
"max_tokens": 1000,
"system_prompt": "You are a helpful customer support assistant...",
"knowledge_base": ["faq.pdf", "product_manual.pdf"],
"integrations": ["zendesk", "slack"]
},
"statistics": {
"total_executions": 1247,
"success_rate": 96.5,
"avg_response_time": 1.2,
"error_rate": 3.5,
"cost_per_execution": 0.025,
"total_cost": 31.18
},
"recent_executions": [
{
"id": "exec_123",
"input": "How do I reset my password?",
"output": "To reset your password, please follow these steps...",
"duration": 1.1,
"cost": 0.023,
"status": "success",
"timestamp": "2024-01-20T09:45:00Z"
}
],
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-20T08:15:00Z"
}
}PUT /api/v1/agents/{id}
Update an existing AI agent.
Request:
{
"name": "Enhanced Customer Support Bot",
"description": "AI-powered customer support with advanced features",
"configuration": {
"temperature": 0.6,
"max_tokens": 1200,
"system_prompt": "You are an expert customer support assistant...",
"knowledge_base": ["faq.pdf", "product_manual.pdf", "troubleshooting.pdf"]
},
"settings": {
"auto_execute": true,
"max_concurrent": 10
}
}DELETE /api/v1/agents/{id}
Delete an AI agent permanently.
Response:
{
"status": "success",
"message": "AI Agent deleted successfully"
}POST /api/v1/agents/{id}/execute
Execute a task using the specified AI agent.
Request:
{
"input": {
"message": "I need help with my billing",
"context": {
"user_id": "user_456",
"conversation_id": "conv_789",
"metadata": {
"source": "website_chat",
"priority": "high"
}
}
},
"options": {
"stream": false,
"include_reasoning": true,
"max_tokens": 500
}
}Response:
{
"status": "success",
"data": {
"execution_id": "exec_987654",
"agent_id": 1,
"input": {
"message": "I need help with my billing",
"context": {
"user_id": "user_456",
"conversation_id": "conv_789"
}
},
"output": {
"message": "I'd be happy to help you with your billing. Let me look up your account information...",
"actions": [
{
"type": "lookup_account",
"user_id": "user_456",
"status": "completed"
}
],
"confidence": 0.92,
"reasoning": "User is asking about billing, detected from keywords 'help' and 'billing'..."
},
"metadata": {
"duration": 1.3,
"tokens_used": 245,
"cost": 0.025,
"model": "gpt-4",
"timestamp": "2024-01-20T10:35:00Z"
}
}
}GET /api/v1/agents/{id}/statistics
Get detailed statistics and performance metrics for an AI agent.
Query Parameters:
period(string): Time period (24h, 7d, 30d, 90d)granularity(string): Data granularity (hour, day, week)
Response:
{
"status": "success",
"data": {
"overview": {
"total_executions": 1247,
"success_rate": 96.5,
"avg_response_time": 1.2,
"total_cost": 31.18,
"cost_per_execution": 0.025
},
"trends": {
"executions_by_day": [
{"date": "2024-01-20", "count": 45},
{"date": "2024-01-19", "count": 52},
{"date": "2024-01-18", "count": 38}
],
"success_rate_trend": [
{"date": "2024-01-20", "rate": 97.8},
{"date": "2024-01-19", "rate": 96.2},
{"date": "2024-01-18", "rate": 95.1}
]
},
"performance": {
"avg_response_time": 1.2,
"p95_response_time": 2.1,
"p99_response_time": 3.8,
"error_distribution": {
"timeout": 12,
"invalid_input": 8,
"rate_limit": 3,
"other": 2
}
}
}
}GET /api/v1/agents/{id}/tasks
Get execution history and tasks for a specific agent.
Query Parameters:
status(string): Filter by status (success, error, pending)limit(integer): Number of tasks to return (max 100)start_date(string): Start date (ISO 8601)end_date(string): End date (ISO 8601)
Response:
{
"status": "success",
"data": [
{
"id": "exec_123456",
"agent_id": 1,
"status": "success",
"input": {
"message": "What are your business hours?",
"context": {"source": "website"}
},
"output": {
"message": "Our business hours are Monday through Friday, 9 AM to 6 PM EST.",
"confidence": 0.98
},
"metadata": {
"duration": 0.8,
"tokens_used": 156,
"cost": 0.019,
"model": "gpt-4"
},
"created_at": "2024-01-20T09:45:00Z"
}
]
}GET /api/v1/dashboard
Get comprehensive dashboard data including overview metrics and recent activity.
Query Parameters:
timeframe(string): Time period for metrics (7, 30, 90 days)
Response:
{
"status": "success",
"data": {
"overview": {
"total_agents": 12,
"active_agents": 8,
"total_api_calls": 15847,
"success_rate": 96.8,
"total_cost": 245.67,
"remaining_credits": 7543
},
"ai_agents": {
"by_type": {
"chatbot": 5,
"workflow": 4,
"analytics": 2,
"integration": 1
},
"by_status": {
"active": 8,
"inactive": 3,
"training": 1
}
},
"tasks": {
"total_executions": 3247,
"successful": 3142,
"failed": 105,
"pending": 0,
"avg_response_time": 1.4
},
"performance": {
"cpu_usage": 68.5,
"memory_usage": 72.1,
"api_response_time": 245,
"uptime": 99.9
},
"recent_activity": [
{
"id": "activity_001",
"type": "agent_execution",
"agent_name": "Customer Support Bot",
"description": "Handled customer inquiry about billing",
"status": "success",
"timestamp": "2024-01-20T10:30:00Z"
}
]
}
}GET /api/v1/analytics
Get comprehensive analytics including usage trends, performance metrics, and business intelligence.
Query Parameters:
period(string): Time period (24h, 7d, 30d, 90d)granularity(string): Data granularity (hour, day, week)metrics(array): Specific metrics to include
Response:
{
"status": "success",
"data": {
"overview_metrics": {
"total_api_calls": 28547,
"total_workflows": 15,
"success_rate": 96.8,
"avg_response_time": 1.4,
"total_cost": 423.67,
"active_users": 45
},
"usage_trends": {
"daily": {
"labels": ["2024-01-14", "2024-01-15", "2024-01-16", "2024-01-17", "2024-01-18", "2024-01-19", "2024-01-20"],
"datasets": [
{
"label": "API Calls",
"data": [1240, 1356, 1189, 1445, 1523, 1398, 1647]
}
]
}
},
"workflow_performance": [
{
"id": 1,
"name": "Customer Support Automation",
"calls": 8547,
"success_rate": 97.2,
"avg_response": "1.2s",
"cost": 156.78,
"status": "active",
"trend": "up"
}
],
"model_usage": [
{
"name": "GPT-4",
"calls": 15420,
"usage": 54.2,
"cost": 245.67,
"color": "blue"
},
{
"name": "Claude-3",
"calls": 8934,
"usage": 31.4,
"cost": 142.89,
"color": "purple"
}
],
"error_analysis": {
"total_errors": 247,
"error_rate": 0.87,
"top_errors": [
{
"type": "Rate Limit Exceeded",
"count": 89,
"percentage": 36.0,
"trend": "down"
},
{
"type": "Invalid Input Format",
"count": 67,
"percentage": 27.1,
"trend": "stable"
}
]
},
"geographic_data": [
{
"region": "North America",
"calls": 12547,
"percentage": 44.0,
"avg_response": "1.1s"
},
{
"region": "Europe",
"calls": 8934,
"percentage": 31.3,
"avg_response": "1.3s"
}
],
"resource_utilization": {
"cpu_usage": 68,
"memory_usage": 72,
"monthly_limits": {
"api_calls": {
"used": 28547,
"limit": 50000
},
"storage": {
"used": 2.4,
"limit": 10.0
}
}
}
}
}GET /api/v1/users (Manager/Admin only)
Get list of users in the tenant.
Query Parameters:
search(string): Search by name or emailrole(string): Filter by role (admin, manager, user)status(string): Filter by status (active, inactive)
Response:
{
"status": "success",
"data": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"role": "user",
"status": "active",
"last_login": "2024-01-20T09:30:00Z",
"created_at": "2024-01-15T10:30:00Z",
"permissions": ["create_agents", "view_analytics"]
}
]
}GET /api/v1/users/{id} (Manager/Admin only)
Get detailed information about a specific user.
PUT /api/v1/users/{id} (Manager/Admin only)
Update user information and permissions.
Request:
{
"name": "John Smith",
"email": "john.smith@example.com",
"role": "manager",
"permissions": ["create_agents", "view_analytics", "manage_users"],
"status": "active"
}PUT /api/v1/users/{id}/status (Manager/Admin only)
Activate or deactivate a user account.
Request:
{
"status": "inactive",
"reason": "User requested account suspension"
}DELETE /api/v1/users/{id} (Admin only)
Permanently delete a user account.
GET /api/v1/billing/subscription
Get current subscription information.
Response:
{
"status": "success",
"data": {
"subscription": {
"id": "sub_1234567890",
"plan": {
"name": "Pro Plan",
"price": 99.00,
"currency": "USD",
"interval": "monthly",
"features": [
"Up to 25 AI Agents",
"50,000 API calls/month",
"Advanced Analytics",
"Priority Support"
]
},
"status": "active",
"current_period_start": "2024-01-01T00:00:00Z",
"current_period_end": "2024-02-01T00:00:00Z",
"trial_end": null,
"cancel_at_period_end": false
},
"usage": {
"current_period": {
"api_calls": 28547,
"api_calls_limit": 50000,
"agents": 12,
"agents_limit": 25
},
"billing_cycle_usage": 57.1
}
}
}POST /api/v1/billing/subscribe
Subscribe to a new plan or change existing subscription.
Request:
{
"plan_id": "plan_pro_monthly",
"payment_method": "pm_1234567890",
"trial_days": 14
}POST /api/v1/billing/cancel
Cancel the current subscription.
Request:
{
"cancel_at_period_end": true,
"reason": "No longer needed"
}GET /api/v1/billing/invoices
Get billing history and invoices.
Response:
{
"status": "success",
"data": [
{
"id": "in_1234567890",
"number": "INV-2024-001",
"status": "paid",
"amount": 99.00,
"currency": "USD",
"period": {
"start": "2024-01-01T00:00:00Z",
"end": "2024-02-01T00:00:00Z"
},
"paid_at": "2024-01-01T12:00:00Z",
"invoice_pdf": "https://example.com/invoices/inv_123.pdf"
}
]
}GET /api/master/tenants
Get list of all tenants (admin only).
Headers:
Authorization: Bearer {admin_token}Response:
{
"status": "success",
"data": [
{
"id": 1,
"name": "TechCorp Solutions",
"domain": "techcorp.saas-platform.com",
"plan": "enterprise",
"status": "active",
"users_count": 125,
"agents_count": 45,
"monthly_revenue": 2500.00,
"created_at": "2024-01-15T10:30:00Z"
}
]
}POST /api/master/tenants
Create a new tenant.
Request:
{
"name": "New Company Inc",
"domain": "newcompany",
"plan": "pro",
"admin_user": {
"name": "Admin User",
"email": "admin@newcompany.com",
"password": "SecurePass123!"
}
}GET /api/master/tenants/{id}
Get detailed information about a specific tenant.
GET /api/master/tenants/{id}/stats
Get comprehensive statistics for a tenant.
Response:
{
"status": "success",
"data": {
"overview": {
"users": 125,
"agents": 45,
"api_calls_month": 125000,
"revenue_month": 2500.00
},
"usage_trends": {
"api_calls_daily": [1240, 1356, 1189, 1445],
"active_users_daily": [89, 92, 85, 96]
},
"performance": {
"success_rate": 97.2,
"avg_response_time": 1.1,
"error_rate": 2.8
}
}
}GET /api/health
Check system health and status.
Response:
{
"status": "ok",
"timestamp": "2024-01-20T10:30:00Z",
"version": "v1.2.0",
"services": {
"database": "healthy",
"redis": "healthy",
"ai_models": "healthy",
"storage": "healthy"
},
"metrics": {
"uptime": 99.9,
"response_time": 245,
"active_connections": 1247
}
}The platform supports webhooks for real-time event notifications:
agent.executed- AI agent task execution completedagent.failed- AI agent task execution faileduser.created- New user registeredsubscription.updated- Subscription plan changedbilling.payment_succeeded- Payment processed successfullybilling.payment_failed- Payment processing failed
{
"event": "agent.executed",
"timestamp": "2024-01-20T10:30:00Z",
"tenant_id": 1,
"data": {
"agent_id": 5,
"execution_id": "exec_123456",
"status": "success",
"duration": 1.2,
"cost": 0.025
}
}POST /api/stripe/webhook
Handle Stripe webhook events for billing.
const SaaSClient = require('@yourcompany/saas-sdk');
const client = new SaaSClient({
apiKey: 'your_api_key',
baseUrl: 'https://api.yourcompany.com/v1'
});
// Execute AI agent
const result = await client.agents.execute(1, {
input: { message: "Hello, how can you help me?" }
});
console.log(result.output.message);from saas_platform import SaaSClient
client = SaaSClient(
api_key='your_api_key',
base_url='https://api.yourcompany.com/v1'
)
# Get analytics
analytics = client.analytics.get(period='30d')
print(f"Total API calls: {analytics['overview_metrics']['total_api_calls']}")# Login
curl -X POST https://api.yourcompany.com/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"password"}'
# Execute agent
curl -X POST https://api.yourcompany.com/v1/agents/1/execute \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"input":{"message":"Hello"}}'
# Get analytics
curl -X GET https://api.yourcompany.com/v1/analytics?period=30d \
-H "Authorization: Bearer YOUR_TOKEN"Import our comprehensive Postman collection:
https://api.yourcompany.com/postman/collection.json
Last Updated: January 20, 2024
API Version: v1.2.0