API FeaturesRouting

Chapter 4: API Routing

Overview

The Polysystems Backend API is organized into logical groups of endpoints, each serving specific functionality. This chapter provides a comprehensive guide to all available routes, their authentication requirements, and usage patterns.

API Architecture

The API follows a hierarchical routing structure:

https://api.polysystems.ai
├── /api/auth/*              (Authentication - JWT)
├── /api/keys/*              (Access Token Management - JWT)
├── /api/payments/*          (Payments & Credits - JWT)
├── /api/monitoring/*        (Usage Monitoring - JWT)
├── /api/hub/*               (Polysystems Hub - API Key)
├── /api/omm/*               (OMM Services - API Key)
├── /api/yggdrasil/*         (Yggdrasil Services - API Key)
├── /api/documents/*         (Document Processing - JWT)
├── /api/legal/*             (Legal Domain - JWT)
├── /api/professional/*      (Professional Domain - JWT)
├── /api/scholar/*           (Scholar Domain - JWT)
├── /api/creative/*          (Creative Domain - JWT)
├── /api/docs/*              (Product Docs - JWT)
├── /api/ws/*                (WebSocket Services)
└── /v1/*                    (OpenAI Compatible - API Key)

Authentication Types

JWT Protected Routes

Require Authorization: Bearer <JWT_TOKEN> header

  • Account management
  • Payment operations
  • Access token CRUD
  • Domain-specific services

API Key Protected Routes

Require X-API-Key: <ACCESS_TOKEN> or Authorization: Bearer <ACCESS_TOKEN>

  • Hub services
  • OMM services
  • Yggdrasil services
  • V1 compatibility endpoints

Route Groups

1. Authentication Routes

Base Path: /api/auth

EndpointMethodAuthDescription
/registerPOSTNoneCreate new account
/loginPOSTNoneLogin and get JWT token
/meGETJWTGet current user info
/change-passwordPOSTJWTChange account password
/refreshPOSTJWTRefresh JWT token
/logoutPOSTJWTLogout (invalidate token)

Example: User Registration

curl -X POST https://api.polysystems.ai/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePass123!",
    "username": "myusername"
  }'

Example: Get User Info

curl -X GET https://api.polysystems.ai/api/auth/me \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

2. Access Key Management Routes

Base Path: /api/keys

EndpointMethodAuthDescription
/POSTJWTGenerate new access token
/GETJWTList all access tokens
/{key_id}/revokePOSTJWTRevoke access token
/{key_id}DELETEJWTDelete access token
/{key_id}/limitsPUTJWTSet spending limits
/{key_id}/limitsGETJWTGet spending limits
/{key_id}/limitsDELETEJWTRemove spending limits
/{key_id}/limits/resetPOSTJWTReset spending counters

Example: Generate Access Token

curl -X POST https://api.polysystems.ai/api/keys \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production API Key",
    "expires_at": null
  }'

Example: Set Spending Limits

curl -X PUT https://api.polysystems.ai/api/keys/key-123/limits \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "daily_limit": 10.00,
    "monthly_limit": 250.00,
    "per_request_limit": 1.00
  }'

3. Payment & Credits Routes

Base Path: /api/payments

Credits Endpoints

EndpointMethodAuthDescription
/credits/balanceGETJWTGet current balance
/credits/addPOSTJWTAdd credits manually (admin)

Transaction Endpoints

EndpointMethodAuthDescription
/transactionsGETJWTList all transactions
/transactions/{id}GETJWTGet transaction details
/transactions/statsGETJWTGet transaction statistics

x402 Payment Endpoints

EndpointMethodAuthDescription
/payments/methodsGETJWTList supported crypto currencies
/paymentsPOSTJWTCreate new payment
/paymentsGETJWTList all payments
/payments/{id}GETJWTGet payment details
/payments/{id}/confirmPOSTJWTManually confirm payment

Example: Check Balance

curl -X GET https://api.polysystems.ai/api/payments/credits/balance \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Example: Create Payment

curl -X POST https://api.polysystems.ai/api/payments/payments \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "amount_usd": 50.00,
    "currency": "ETH"
  }'

Example: List Transactions

curl -X GET https://api.polysystems.ai/api/payments/transactions?limit=10&offset=0 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

4. Polysystems Hub Routes

Base Path: /api/hub

Health & System

EndpointMethodAuthDescription
/healthGETNoneHealth check (public)
/system/infoGETAPI KeySystem information
/system/metricsGETAPI KeySystem metrics
/system/resourcesGETAPI KeyResource usage

Agent Management

EndpointMethodAuthDescription
/agentsPOSTAPI KeyCreate new agent
/agentsGETAPI KeyList all agents
/agents/{agent_id}GETAPI KeyGet agent details
/agents/{agent_id}PUTAPI KeyUpdate agent
/agents/{agent_id}DELETEAPI KeyDelete agent
/agents/generatePOSTAPI KeyGenerate text with agent
/agents/chatPOSTAPI KeyChat completion

Memory System

EndpointMethodAuthDescription
/memoryPOSTAPI KeyStore memory
/memory/{memory_id}GETAPI KeyRetrieve memory
/memory/queryPOSTAPI KeyQuery memories
/memory/searchPOSTAPI KeySearch memories
/memory/statsGETAPI KeyMemory statistics

Task Orchestration

EndpointMethodAuthDescription
/tasksPOSTAPI KeySubmit new task
/tasksGETAPI KeyList tasks
/tasks/{task_id}GETAPI KeyGet task status
/tasks/{task_id}/cancelPOSTAPI KeyCancel task

RAG (Retrieval Augmented Generation)

EndpointMethodAuthDescription
/rag/indexPOSTAPI KeyIndex document
/rag/retrievePOSTAPI KeyRetrieve documents
/rag/generatePOSTAPI KeyGenerate with RAG
/rag/statsGETAPI KeyRAG statistics
EndpointMethodAuthDescription
/search/indexPOSTAPI KeyIndex for search
/searchPOSTAPI KeyPerform search

Story Generation

EndpointMethodAuthDescription
/story/generatePOSTAPI KeyGenerate story
/storyGETAPI KeyList stories

Example: Chat Completion

curl -X POST https://api.polysystems.ai/api/hub/agents/chat \
  -H "X-API-Key: YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What is machine learning?"}
    ],
    "model": "gpt-4",
    "temperature": 0.7,
    "max_tokens": 500
  }'

Example: Store Memory

curl -X POST https://api.polysystems.ai/api/hub/memory \
  -H "X-API-Key: YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "user_preference",
    "value": "prefers dark mode",
    "metadata": {
      "user_id": "user-123",
      "timestamp": "2024-01-15T12:00:00Z"
    }
  }'

Example: Submit Task

curl -X POST https://api.polysystems.ai/api/hub/tasks \
  -H "X-API-Key: YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "task_type": "data_processing",
    "parameters": {
      "input_file": "data.csv",
      "output_format": "json"
    },
    "priority": "high"
  }'

5. OMM (Omni-Modal Model) Routes

Base Path: /api/omm

EndpointMethodAuthDescription
/healthGETNoneHealth check (public)
/processPOSTAPI KeyProcess multi-modal input
/analyzePOSTAPI KeyAnalyze content
/generatePOSTAPI KeyGenerate content
/transformPOSTAPI KeyTransform between modalities

Example: Process Multi-Modal Input

curl -X POST https://api.polysystems.ai/api/omm/process \
  -H "X-API-Key: YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": [
      {
        "type": "text",
        "content": "Analyze this image"
      },
      {
        "type": "image",
        "url": "https://example.com/image.jpg"
      }
    ],
    "task": "description"
  }'

6. Yggdrasil Routes

Base Path: /api/yggdrasil

EndpointMethodAuthDescription
/processPOSTAPI KeyProcess with Yggdrasil
/analyzePOSTAPI KeyAdvanced analysis
/generatePOSTAPI KeyGenerate content
/optimizePOSTAPI KeyOptimize outputs

Example: Yggdrasil Processing

curl -X POST https://api.polysystems.ai/api/yggdrasil/process \
  -H "X-API-Key: YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Input content here",
    "processing_type": "advanced_analysis",
    "parameters": {
      "depth": "comprehensive"
    }
  }'

7. Document Processing Routes

Base Path: /api/documents

EndpointMethodAuthDescription
/uploadPOSTJWTUpload document
/GETJWTList documents
/{doc_id}GETJWTGet document
/{doc_id}DELETEJWTDelete document
/{doc_id}/processPOSTJWTProcess document
/{doc_id}/extractPOSTJWTExtract data

Example: Upload Document

curl -X POST https://api.polysystems.ai/api/documents/upload \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -F "file=@document.pdf" \
  -F "metadata={\"title\":\"Contract\",\"type\":\"legal\"}"

8. Domain-Specific Routes

Base Path: /api/legal

EndpointMethodAuthDescription
/analyzePOSTJWTAnalyze legal document
/summarizePOSTJWTSummarize legal text
/extractPOSTJWTExtract clauses
/comparePOSTJWTCompare contracts

Professional Domain

Base Path: /api/professional

EndpointMethodAuthDescription
/analyzePOSTJWTProfessional analysis
/generatePOSTJWTGenerate content
/optimizePOSTJWTOptimize content

Scholar Domain

Base Path: /api/scholar

EndpointMethodAuthDescription
/researchPOSTJWTResearch assistance
/citePOSTJWTGenerate citations
/summarizePOSTJWTSummarize papers
/analyzePOSTJWTAnalyze research

Creative Domain

Base Path: /api/creative

EndpointMethodAuthDescription
/generatePOSTJWTGenerate creative content
/enhancePOSTJWTEnhance content
/brainstormPOSTJWTBrainstorming assistance

Product Documentation

Base Path: /api/docs

EndpointMethodAuthDescription
/generatePOSTJWTGenerate documentation
/improvePOSTJWTImprove docs
/structurePOSTJWTStructure content

9. Monitoring Routes

Base Path: /api/monitoring

EndpointMethodAuthDescription
/usageGETJWTUsage statistics
/usage/summaryGETJWTUsage summary
/costsGETJWTCost breakdown
/keys/{key_id}/usageGETJWTPer-key usage

Example: Get Usage Statistics

curl -X GET "https://api.polysystems.ai/api/monitoring/usage?start_date=2024-01-01&end_date=2024-01-31" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

10. WebSocket Routes

Base Path: /api/ws

EndpointProtocolAuthDescription
/collaborateWebSocketQuery ParamReal-time collaboration
/streamWebSocketQuery ParamStream responses

Example: WebSocket Connection

const token = 'YOUR_ACCESS_TOKEN';
const ws = new WebSocket(`wss://api.polysystems.ai/api/ws/collaborate?token=${token}`);
 
ws.onopen = () => {
  console.log('Connected');
  ws.send(JSON.stringify({
    action: 'join',
    room: 'project-123'
  }));
};
 
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
};

11. V1 Compatibility Routes (OpenAI-Compatible)

Base Path: /v1

EndpointMethodAuthDescription
/chat/completionsPOSTAPI KeyChat completions (OpenAI format)
/completionsPOSTAPI KeyText completions
/embeddingsPOSTAPI KeyGenerate embeddings
/modelsGETAPI KeyList available models

Example: OpenAI-Compatible Chat

curl -X POST https://api.polysystems.ai/v1/chat/completions \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4",
    "messages": [
      {"role": "user", "content": "Hello!"}
    ]
  }'

Request/Response Formats

Standard Request Headers

X-API-Key: ps_live_your_access_token
Content-Type: application/json
User-Agent: YourApp/1.0

Or:

Authorization: Bearer YOUR_JWT_OR_ACCESS_TOKEN
Content-Type: application/json
User-Agent: YourApp/1.0

Standard Response Format

Success Response

{
  "data": {
    // Response data
  },
  "metadata": {
    "request_id": "req-123e4567-e89b-12d3-a456-426614174000",
    "timestamp": "2024-01-15T12:00:00Z",
    "cost": 0.0020
  }
}

Error Response

{
  "error": "Error Type",
  "message": "Detailed error message",
  "request_id": "req-123e4567-e89b-12d3-a456-426614174000",
  "timestamp": "2024-01-15T12:00:00Z"
}

Query Parameters

Common Query Parameters

ParameterTypeDescriptionExample
limitintegerMax results to return?limit=50
offsetintegerPagination offset?offset=100
sortstringSort field?sort=created_at
orderstringSort order (asc/desc)?order=desc
start_dateISO8601Filter start date?start_date=2024-01-01
end_dateISO8601Filter end date?end_date=2024-01-31
statusstringFilter by status?status=active

Example with Query Parameters

curl -X GET "https://api.polysystems.ai/api/payments/transactions?limit=20&offset=0&sort=created_at&order=desc" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Rate Limiting

All API endpoints are subject to rate limiting. Rate limit information is included in response headers:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1705327200

Rate Limit Tiers

TierRequests/MinuteRequests/HourRequests/Day
Free101001,000
Basic1001,00010,000
Pro1,00010,000100,000
EnterpriseCustomCustomCustom

CORS Support

The API supports Cross-Origin Resource Sharing (CORS):

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key

API Versioning

Currently, the API is at version 1.0. Future versions will be accessible via:

https://api.polysystems.ai/v2/...
https://api.polysystems.ai/v3/...

Version 1 will be maintained for backward compatibility.

Testing Endpoints

Health Checks (No Auth Required)

# Hub Health
curl https://api.polysystems.ai/api/hub/health
 
# OMM Health
curl https://api.polysystems.ai/api/omm/health

Expected Response:

{
  "status": "healthy",
  "version": "1.0.0",
  "timestamp": "2024-01-15T12:00:00Z"
}

Best Practices

1. Use Appropriate Routes

  • Use JWT-protected routes for account management
  • Use API Key-protected routes for production API calls
  • Use domain-specific routes for specialized tasks

2. Implement Retry Logic

import time
import requests
 
def api_call_with_retry(url, headers, data, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = requests.post(url, headers=headers, json=data)
            if response.status_code == 200:
                return response.json()
            elif response.status_code == 429:  # Rate limit
                wait_time = int(response.headers.get('Retry-After', 60))
                time.sleep(wait_time)
            else:
                response.raise_for_status()
        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # Exponential backoff

3. Cache Responses When Appropriate

from functools import lru_cache
import requests
 
@lru_cache(maxsize=128)
def get_pricing_info(api_key):
    """Cache pricing info as it doesn't change frequently"""
    response = requests.get(
        'https://api.polysystems.ai/api/pricing',
        headers={'X-API-Key': api_key}
    )
    return response.json()

4. Handle Errors Gracefully

try:
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()
    return response.json()
except requests.exceptions.HTTPError as e:
    if e.response.status_code == 402:
        print("Insufficient credits. Please top up your account.")
    elif e.response.status_code == 429:
        print("Rate limit exceeded. Please slow down requests.")
    elif e.response.status_code == 401:
        print("Authentication failed. Check your API key.")
    else:
        print(f"API error: {e}")

Complete Example: Multi-Step Workflow

import os
import requests
 
BASE_URL = "https://api.polysystems.ai"
JWT_TOKEN = os.getenv('PS_JWT_TOKEN')
API_KEY = os.getenv('PS_API_KEY')
 
# Step 1: Check balance
balance_response = requests.get(
    f"{BASE_URL}/api/payments/credits/balance",
    headers={"Authorization": f"Bearer {JWT_TOKEN}"}
)
balance = balance_response.json()['balance']
print(f"Current balance: ${balance}")
 
# Step 2: Check spending limits
limits_response = requests.get(
    f"{BASE_URL}/api/keys/key-123/limits",
    headers={"Authorization": f"Bearer {JWT_TOKEN}"}
)
limits = limits_response.json()
print(f"Daily remaining: ${limits['daily_remaining']}")
 
# Step 3: Make API call
chat_response = requests.post(
    f"{BASE_URL}/api/hub/agents/chat",
    headers={
        "X-API-Key": API_KEY,
        "Content-Type": "application/json"
    },
    json={
        "messages": [
            {"role": "user", "content": "Explain quantum computing"}
        ],
        "model": "gpt-4"
    }
)
result = chat_response.json()
print(f"Response: {result}")
 
# Step 4: Check usage
usage_response = requests.get(
    f"{BASE_URL}/api/monitoring/usage",
    headers={"Authorization": f"Bearer {JWT_TOKEN}"}
)
usage = usage_response.json()
print(f"Total requests today: {usage['requests_today']}")
print(f"Total cost today: ${usage['cost_today']}")

Summary

In this chapter, you learned:

  • ✅ Complete API route structure and organization
  • ✅ Authentication requirements for each route group
  • ✅ All available endpoints and their purposes
  • ✅ Request and response formats
  • ✅ Query parameters and pagination
  • ✅ Rate limiting and CORS support
  • ✅ Best practices for API integration
  • ✅ Complete workflow examples

Next Steps