Skip to content

API Documentation Overview

Purpose: Comprehensive API reference for all MachineAvatars backend services
Audience: Developers, Integration Partners, Technical Teams
Owner: Backend Lead, API Team
Last Updated: 2025-12-29
Version: 2.0


Executive Summary

MachineAvatars provides a comprehensive REST API across 23 microservices, enabling developers to integrate AI-powered chatbots into any application. Our APIs follow OpenAPI 3.0 standards, support JSON request/response formats, and include interactive Swagger documentation.

Key Features:

  • 23 Microservices with dedicated REST APIs
  • JWT Authentication for secure access
  • Rate Limiting to prevent abuse
  • Versioned APIs (backward compatibility guaranteed)
  • Interactive Docs (Swagger UI)
  • Webhook Support for real-time events

API Architecture

Service Catalog

Service Port Base URL OpenAPI Spec Purpose
Gateway 8000 /api/v1/ OpenAPI Spec API routing, load balancing
Auth Service 8001 /api/v1/auth/ OpenAPI Spec Authentication, JWT tokens
User Service 8002 /api/v1/users/ OpenAPI Spec User management, profiles
Create Chatbot 8003 /api/v1/chatbots/ OpenAPI Spec Chatbot creation
Selection Chatbot 8004 /api/v1/selection/ OpenAPI Spec Chatbot selection
Data Crawling 8005 /api/v1/crawl/ OpenAPI Spec Document ingestion
State 3D 8006 /api/v1/state-3d/ OpenAPI Spec 3D chatbot state
State Text 8007 /api/v1/state-text/ OpenAPI Spec Text chatbot state
State Voice 8008 /api/v1/state-voice/ OpenAPI Spec Voice chatbot state
System Prompt 8009 /api/v1/prompts/ OpenAPI Spec Prompt management
Maintenance 8010 /api/v1/maintenance/ OpenAPI Spec Chatbot maintenance
Response 3D 8011 /api/v1/chat-3d/ OpenAPI Spec 3D chatbot responses
Response Text 8012 /api/v1/chat-text/ OpenAPI Spec Text responses
Response Voice 8013 /api/v1/chat-voice/ OpenAPI Spec Voice responses
Chat History 8014 /api/v1/history/ OpenAPI Spec Conversation history
Client Data 8015 /api/v1/analytics/ OpenAPI Spec Analytics collection
LLM Model 8016 /api/v1/llm/ OpenAPI Spec LLM selection
Homepage 8017 /api/v1/homepage/ OpenAPI Spec Homepage chatbot
Remote Physio 8018 /api/v1/physio/ OpenAPI Spec Physiotherapy chatbot
Payment 8019 /api/v1/payment/ OpenAPI Spec Subscriptions, billing
Superadmin 8020 /api/v1/admin/ OpenAPI Spec Admin operations

Authentication

JWT Token-Based Authentication

All API requests require authentication (except /health endpoints and webhook callbacks).

Obtaining a Token

Endpoint: POST /api/v1/auth/login

Request:

{
  "email": "user@example.com",
  "password": "SecurePassword123!"
}

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "user_id": "user_12345"
}

Using the Token

Include in Authorization header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Example Request:

curl -X GET https://api.machineavatars.com/api/v1/users/me \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Token Lifecycle

Event Action Token Validity
Login Generate new token 1 hour
Refresh POST /auth/refresh Extends by 1 hour
Logout POST /auth/logout Token invalidated
Expiration Automatic after 1 hour Must re-authenticate

API Versioning

Version Strategy

Current Version: v1
URL Pattern: /api/v1/{resource}

Versioning Policy:

  • Backward Compatibility: v1 endpoints will NOT break existing integrations
  • Deprecation Notice: 6 months before removing old versions
  • Version Header: Optional API-Version: v2 header support

Future Versions:

  • /api/v2/ - Planned Q3 2025 (breaking changes, new features)

Error Handling

Standard Error Response Format

All errors follow consistent structure:

{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "User-friendly error message",
    "details": "Technical details for debugging",
    "timestamp": "2025-12-29T10:30:00Z",
    "request_id": "req_abc123"
  }
}

HTTP Status Codes

Status Code Meaning Common Causes
200 OK Success Request processed successfully
201 Created Resource created POST request successful
400 Bad Request Invalid input Missing required fields, invalid JSON
401 Unauthorized Authentication required Missing or invalid token
403 Forbidden Insufficient permissions User not authorized for resource
404 Not Found Resource not found Invalid endpoint or resource ID
409 Conflict Resource conflict Duplicate creation attempt
429 Too Many Requests Rate limit exceeded Too many API calls
500 Internal Server Error Server error Unexpected server issue
503 Service Unavailable Service down Maintenance or outage

Error Codes Reference

Error Code HTTP Status Description Solution
INVALID_TOKEN 401 JWT token invalid or expired Re-authenticate via /auth/login
MISSING_FIELD 400 Required field missing Check request body
INVALID_FORMAT 400 Field format invalid (email, phone) Validate input format
RESOURCE_NOT_FOUND 404 Resource doesn't exist Verify resource ID
DUPLICATE_RESOURCE 409 Resource already exists Check for existing resource
RATE_LIMIT_EXCEEDED 429 Too many requests Wait before retrying
INTERNAL_ERROR 500 Server-side error Contact support with request_id

Rate Limiting

Rate Limit Policy

Purpose: Prevent abuse and ensure fair usage

Tier Requests/Minute Requests/Hour Requests/Day
Free Trial 60 1,000 10,000
Starter 120 5,000 50,000
Professional 300 15,000 200,000
Business 600 30,000 500,000
Enterprise Unlimited Unlimited Unlimited

Rate Limit Headers

Every API response includes rate limit information:

X-RateLimit-Limit: 120
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

Example:

curl -I https://api.machineavatars.com/api/v1/users/me

HTTP/1.1 200 OK
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

Rate Limit Exceeded Response

{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Please retry after 60 seconds.",
    "retry_after": 60,
    "limit": 120,
    "reset_at": "2025-12-29T10:31:00Z"
  }
}

Request/Response Formats

Content Types

Request:

  • Content-Type: application/json (required for POST/PUT/PATCH)
  • Content-Type: multipart/form-data (for file uploads)

Response:

  • Content-Type: application/json (default)
  • Content-Type: application/octet-stream (for file downloads)

Pagination

For list endpoints returning multiple items:

Request Parameters:

GET /api/v1/chatbots?page=2&limit=20

Response:

{
  "data": [
    { "id": "cb_1", "name": "Support Bot" },
    { "id": "cb_2", "name": "Sales Bot" }
  ],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total_items": 150,
    "total_pages": 8,
    "has_next": true,
    "has_prev": true
  }
}

Filtering & Sorting

Filter by fields:

GET /api/v1/chatbots?status=active&type=3d

Sort results:

GET /api/v1/chatbots?sort_by=created_at&order=desc

Common Parameters: | Parameter | Type | Description | Example | |-----------|------|-------------|---------| | page | integer | Page number (1-indexed) | ?page=3 | | limit | integer | Items per page (max 100) | ?limit=50 | | sort_by | string | Field to sort by | ?sort_by=name | | order | string | Sort order (asc/desc) | ?order=desc | | search | string | Search query | ?search=support |


Webhooks

Event Notifications

MachineAvatars can notify your application of events via webhooks.

Supported Events:

  • chatbot.created - New chatbot created
  • conversation.started - User initiated conversation
  • conversation.ended - Conversation completed
  • payment.succeeded - Subscription payment successful
  • payment.failed - Payment failed
  • subscription.cancelled - Subscription cancelled

Webhook Configuration

Endpoint: POST /api/v1/webhooks/configure

Request:

{
  "url": "https://your-app.com/webhooks/machineavatars",
  "events": ["chatbot.created", "conversation.started"],
  "secret": "whsec_your_signing_secret"
}

Response:

{
  "webhook_id": "wh_abc123",
  "status": "active",
  "created_at": "2025-12-29T10:30:00Z"
}

Webhook Payload Example

Event: conversation.started

{
  "event": "conversation.started",
  "timestamp": "2025-12-29T10:30:15Z",
  "data": {
    "conversation_id": "conv_xyz789",
    "chatbot_id": "cb_12345",
    "user_id": "anonymous_abc",
    "started_at": "2025-12-29T10:30:15Z"
  }
}

Webhook Security

Signature Verification:

Every webhook request includes a signature header:

X-MachineAvatars-Signature: sha256=5d41402abc4b2a76b9719d911017c592

Verify signature (Python):

import hmac
import hashlib

def verify_webhook(payload, signature, secret):
    expected_sig = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(f"sha256={expected_sig}", signature)

Common API Patterns

Creating a Chatbot (End-to-End)

Step 1: Create Chatbot

POST /api/v1/chatbots/create
{
  "name": "Support Bot",
  "type": "3d",
  "avatar_id": "avatar_female_01",
  "language": "en-US"
}

Step 2: Upload Knowledge Base

POST /api/v1/crawl/upload-pdf
Content-Type: multipart/form-data

file: knowledge_base.pdf
chatbot_id: cb_12345

Step 3: Test Chatbot

POST /api/v1/chat-3d/respond
{
  "chatbot_id": "cb_12345",
  "message": "Hello, how can you help me?",
  "user_id": "test_user"
}

Step 4: Deploy

<iframe
  src="https://chat.machineavatars.com/cb_12345"
  width="400"
  height="600"
></iframe>

SDK & Client Libraries

Official SDKs

Coming Soon:

  • Python SDK (Q1 2025)
  • JavaScript/Node.js SDK (Q1 2025)
  • React Component (Q2 2025)

Community SDKs:

  • Developers can build their own using OpenAPI specs

Sample Code (cURL)

Authentication:

curl -X POST https://api.machineavatars.com/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"pass123"}'

Create Chatbot:

curl -X POST https://api.machineavatars.com/api/v1/chatbots/create \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"Support Bot","type":"3d"}'

Send Message:

curl -X POST https://api.machineavatars.com/api/v1/chat-3d/respond \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"chatbot_id":"cb_123","message":"Hello"}'

Interactive Documentation

Swagger UI

Access interactive API docs:

Development: http://localhost:8000/docs
Production: https://api.machineavatars.com/docs

Features:

  • ✅ Try API calls directly from browser
  • ✅ See request/response examples
  • ✅ Download OpenAPI specs
  • ✅ Generate client code

ReDoc

Alternative documentation interface:

URL: https://api.machineavatars.com/redoc

Features:

  • Clean, responsive design
  • Search functionality
  • Code examples in multiple languages

API Best Practices

1. Always Include Request IDs

Why: Helps track requests for debugging

How:

X-Request-ID: uuid-generated-by-client

2. Use Idempotency Keys for Critical Operations

For payment/subscription operations:

Idempotency-Key: unique-key-12345

Ensures operation only happens once even if retried


3. Handle Rate Limits Gracefully

Implement exponential backoff:

import time

def api_call_with_retry(url, max_retries=3):
    for attempt in range(max_retries):
        response = requests.get(url)
        if response.status_code == 429:
            retry_after = int(response.headers.get('Retry-After', 60))
            time.sleep(retry_after)
            continue
        return response

4. Validate Input Before Sending

Common validations:

  • Email format: user@domain.com
  • Phone: +1234567890
  • URL: https://example.com
  • Required fields present

5. Use Webhooks Instead of Polling

❌ Bad (Polling every 10 seconds):

while True:
    status = check_conversation_status(conv_id)
    if status == "completed":
        break
    time.sleep(10)

✅ Good (Webhook notification):

@app.route('/webhook', methods=['POST'])
def handle_webhook():
    event = request.json
    if event['event'] == 'conversation.ended':
        process_conversation(event['data'])

Support & Resources

Documentation

  • [API Reference (OpenAPI)]

Developer Resources

Technical Support

  • Email: developers@machineavatars.com
  • Response Time: \u003c 24 hours
  • Enterprise: Dedicated Slack channel


Last Updated: 2025-12-29
Version: 2.0
Owner: Backend Lead, API Team
Review Cycle: Monthly
Next Review: 2025-02-01


"Great APIs are invisible - they just work."