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
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/register | POST | None | Create new account |
/login | POST | None | Login and get JWT token |
/me | GET | JWT | Get current user info |
/change-password | POST | JWT | Change account password |
/refresh | POST | JWT | Refresh JWT token |
/logout | POST | JWT | Logout (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
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/ | POST | JWT | Generate new access token |
/ | GET | JWT | List all access tokens |
/{key_id}/revoke | POST | JWT | Revoke access token |
/{key_id} | DELETE | JWT | Delete access token |
/{key_id}/limits | PUT | JWT | Set spending limits |
/{key_id}/limits | GET | JWT | Get spending limits |
/{key_id}/limits | DELETE | JWT | Remove spending limits |
/{key_id}/limits/reset | POST | JWT | Reset 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
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/credits/balance | GET | JWT | Get current balance |
/credits/add | POST | JWT | Add credits manually (admin) |
Transaction Endpoints
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/transactions | GET | JWT | List all transactions |
/transactions/{id} | GET | JWT | Get transaction details |
/transactions/stats | GET | JWT | Get transaction statistics |
x402 Payment Endpoints
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/payments/methods | GET | JWT | List supported crypto currencies |
/payments | POST | JWT | Create new payment |
/payments | GET | JWT | List all payments |
/payments/{id} | GET | JWT | Get payment details |
/payments/{id}/confirm | POST | JWT | Manually 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
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/health | GET | None | Health check (public) |
/system/info | GET | API Key | System information |
/system/metrics | GET | API Key | System metrics |
/system/resources | GET | API Key | Resource usage |
Agent Management
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/agents | POST | API Key | Create new agent |
/agents | GET | API Key | List all agents |
/agents/{agent_id} | GET | API Key | Get agent details |
/agents/{agent_id} | PUT | API Key | Update agent |
/agents/{agent_id} | DELETE | API Key | Delete agent |
/agents/generate | POST | API Key | Generate text with agent |
/agents/chat | POST | API Key | Chat completion |
Memory System
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/memory | POST | API Key | Store memory |
/memory/{memory_id} | GET | API Key | Retrieve memory |
/memory/query | POST | API Key | Query memories |
/memory/search | POST | API Key | Search memories |
/memory/stats | GET | API Key | Memory statistics |
Task Orchestration
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/tasks | POST | API Key | Submit new task |
/tasks | GET | API Key | List tasks |
/tasks/{task_id} | GET | API Key | Get task status |
/tasks/{task_id}/cancel | POST | API Key | Cancel task |
RAG (Retrieval Augmented Generation)
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/rag/index | POST | API Key | Index document |
/rag/retrieve | POST | API Key | Retrieve documents |
/rag/generate | POST | API Key | Generate with RAG |
/rag/stats | GET | API Key | RAG statistics |
Search
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/search/index | POST | API Key | Index for search |
/search | POST | API Key | Perform search |
Story Generation
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/story/generate | POST | API Key | Generate story |
/story | GET | API Key | List 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
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/health | GET | None | Health check (public) |
/process | POST | API Key | Process multi-modal input |
/analyze | POST | API Key | Analyze content |
/generate | POST | API Key | Generate content |
/transform | POST | API Key | Transform 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
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/process | POST | API Key | Process with Yggdrasil |
/analyze | POST | API Key | Advanced analysis |
/generate | POST | API Key | Generate content |
/optimize | POST | API Key | Optimize 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
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/upload | POST | JWT | Upload document |
/ | GET | JWT | List documents |
/{doc_id} | GET | JWT | Get document |
/{doc_id} | DELETE | JWT | Delete document |
/{doc_id}/process | POST | JWT | Process document |
/{doc_id}/extract | POST | JWT | Extract 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
Legal Domain
Base Path: /api/legal
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/analyze | POST | JWT | Analyze legal document |
/summarize | POST | JWT | Summarize legal text |
/extract | POST | JWT | Extract clauses |
/compare | POST | JWT | Compare contracts |
Professional Domain
Base Path: /api/professional
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/analyze | POST | JWT | Professional analysis |
/generate | POST | JWT | Generate content |
/optimize | POST | JWT | Optimize content |
Scholar Domain
Base Path: /api/scholar
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/research | POST | JWT | Research assistance |
/cite | POST | JWT | Generate citations |
/summarize | POST | JWT | Summarize papers |
/analyze | POST | JWT | Analyze research |
Creative Domain
Base Path: /api/creative
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/generate | POST | JWT | Generate creative content |
/enhance | POST | JWT | Enhance content |
/brainstorm | POST | JWT | Brainstorming assistance |
Product Documentation
Base Path: /api/docs
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/generate | POST | JWT | Generate documentation |
/improve | POST | JWT | Improve docs |
/structure | POST | JWT | Structure content |
9. Monitoring Routes
Base Path: /api/monitoring
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/usage | GET | JWT | Usage statistics |
/usage/summary | GET | JWT | Usage summary |
/costs | GET | JWT | Cost breakdown |
/keys/{key_id}/usage | GET | JWT | Per-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
| Endpoint | Protocol | Auth | Description |
|---|---|---|---|
/collaborate | WebSocket | Query Param | Real-time collaboration |
/stream | WebSocket | Query Param | Stream 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
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/chat/completions | POST | API Key | Chat completions (OpenAI format) |
/completions | POST | API Key | Text completions |
/embeddings | POST | API Key | Generate embeddings |
/models | GET | API Key | List 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.0Or:
Authorization: Bearer YOUR_JWT_OR_ACCESS_TOKEN
Content-Type: application/json
User-Agent: YourApp/1.0Standard 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
| Parameter | Type | Description | Example |
|---|---|---|---|
limit | integer | Max results to return | ?limit=50 |
offset | integer | Pagination offset | ?offset=100 |
sort | string | Sort field | ?sort=created_at |
order | string | Sort order (asc/desc) | ?order=desc |
start_date | ISO8601 | Filter start date | ?start_date=2024-01-01 |
end_date | ISO8601 | Filter end date | ?end_date=2024-01-31 |
status | string | Filter 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: 1705327200Rate Limit Tiers
| Tier | Requests/Minute | Requests/Hour | Requests/Day |
|---|---|---|---|
| Free | 10 | 100 | 1,000 |
| Basic | 100 | 1,000 | 10,000 |
| Pro | 1,000 | 10,000 | 100,000 |
| Enterprise | Custom | Custom | Custom |
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-KeyAPI 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/healthExpected 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 backoff3. 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
- Chapter 5: Payment & Credits - Learn about the payment system
- Chapter 7: API Pricing - Understand pricing structure
- Chapter 11: Code Examples - See more integration examples