Skip to content

api_documentation

Garot Conklin edited this page Jun 1, 2025 · 1 revision

ContractAI API Documentation

Comprehensive API documentation for ContractAI platform integration

Overview

This document provides detailed information about the ContractAI REST API, including endpoints, authentication, request/response formats, and integration patterns.

API Architecture

graph TD
    A[API Gateway] --> B[Authentication]
    A --> C[Rate Limiting]
    A --> D[Request Router]

    B --> B1[API Keys]
    B --> B2[OAuth 2.0]
    B --> B3[JWT]

    C --> C1[Request Limits]
    C --> C2[Quota Management]
    C --> C3[Throttling]

    D --> D1[Agent API]
    D --> D2[Knowledge API]
    D --> D3[Monitor API]

    D1 --> E1[Agent Manager]
    D2 --> E2[Knowledge Base]
    D3 --> E3[Monitoring]
Loading

Authentication

Authentication Flow

sequenceDiagram
    participant C as Client
    participant A as API Gateway
    participant I as Identity Provider
    participant S as Service

    C->>A: Request with Credentials
    A->>I: Validate Credentials
    I->>A: Token Response
    A->>S: Forward Request with Token
    S->>A: Service Response
    A->>C: API Response
Loading

OAuth 2.0 Flow

sequenceDiagram
    participant U as User
    participant C as Client
    participant A as Auth Server
    participant R as Resource Server

    U->>C: Access Request
    C->>A: Authorization Request
    A->>U: Login Prompt
    U->>A: Authenticate
    A->>C: Auth Code
    C->>A: Token Request
    A->>C: Access Token
    C->>R: Resource Request
    R->>C: Protected Resource
Loading

API Endpoints

Agent Management

graph TD
    A[Agent API] --> B[Create Agent]
    A --> C[Manage Agent]
    A --> D[Monitor Agent]

    B --> B1[POST /agents]
    B --> B2[Configure Agent]
    B --> B3[Deploy Agent]

    C --> C1[GET /agents/{id}]
    C --> C2[PUT /agents/{id}]
    C --> C3[DELETE /agents/{id}]

    D --> D1[GET /agents/{id}/status]
    D --> D2[GET /agents/{id}/metrics]
    D --> D3[GET /agents/{id}/logs]
Loading

Knowledge Base

graph TD
    A[Knowledge API] --> B[Query]
    A --> C[Manage]
    A --> D[Search]

    B --> B1[GET /knowledge/query]
    B --> B2[POST /knowledge/ask]
    B --> B3[GET /knowledge/context]

    C --> C1[POST /knowledge/documents]
    C --> C2[PUT /knowledge/documents/{id}]
    C --> C3[DELETE /knowledge/documents/{id}]

    D --> D1[GET /knowledge/search]
    D --> D2[GET /knowledge/suggest]
    D --> D3[GET /knowledge/related]
Loading

Monitoring

graph TD
    A[Monitor API] --> B[Status]
    A --> C[Metrics]
    A --> D[Alerts]

    B --> B1[GET /monitor/status]
    B --> B2[GET /monitor/health]
    B --> B3[GET /monitor/version]

    C --> C1[GET /monitor/metrics]
    C --> C2[POST /monitor/metrics]
    C --> C3[GET /monitor/trends]

    D --> D1[GET /monitor/alerts]
    D --> D2[POST /monitor/alerts]
    D --> D3[PUT /monitor/alerts/{id}]
Loading

Request/Response Patterns

Standard Request Flow

sequenceDiagram
    participant C as Client
    participant G as Gateway
    participant V as Validator
    participant S as Service
    participant D as Database

    C->>G: HTTP Request
    G->>V: Validate Request
    V->>G: Validation Result
    G->>S: Process Request
    S->>D: Query/Update
    D->>S: Data Result
    S->>G: Service Response
    G->>C: HTTP Response
Loading

Error Handling

graph TD
    A[Error Response] --> B[Client Errors]
    A --> C[Server Errors]
    A --> D[Validation Errors]

    B --> B1[400 Bad Request]
    B --> B2[401 Unauthorized]
    B --> B3[403 Forbidden]

    C --> C1[500 Server Error]
    C --> C2[502 Bad Gateway]
    C --> C3[503 Unavailable]

    D --> D1[422 Validation]
    D --> D2[429 Rate Limit]
    D --> D3[409 Conflict]
Loading

Rate Limiting

Rate Limit Flow

graph TD
    A[Request] --> B{Check Limit}
    B -->|Under Limit| C[Process]
    B -->|Over Limit| D[Reject]

    C --> C1[Update Counter]
    C --> C2[Process Request]
    C --> C3[Send Response]

    D --> D1[429 Response]
    D --> D2[Retry After]
    D --> D3[Log Limit]
Loading

Webhooks

Webhook Flow

sequenceDiagram
    participant S as Service
    participant W as Webhook
    participant C as Client

    S->>W: Event Trigger
    W->>C: POST Request
    C->>W: 200 OK
    W->>S: Delivery Status

    Note over W,C: Retry on Failure
    Note over W,C: Exponential Backoff
Loading

SDK Integration

SDK Architecture

graph TD
    A[SDK] --> B[Client]
    A --> C[Models]
    A --> D[Utils]

    B --> B1[API Client]
    B --> B2[Auth Client]
    B --> B3[Webhook Client]

    C --> C1[Request Models]
    C --> C2[Response Models]
    C --> C3[Error Models]

    D --> D1[Validation]
    D --> D2[Serialization]
    D --> D3[Helpers]
Loading

Integration Flow

graph TD
    A[Integration] --> B[Initialize]
    A --> C[Configure]
    A --> D[Use]

    B --> B1[Create Client]
    B --> B2[Set Credentials]
    B --> B3[Verify Connection]

    C --> C1[Set Options]
    C --> C2[Add Handlers]
    C --> C3[Setup Webhooks]

    D --> D1[Make Requests]
    D --> D2[Handle Events]
    D --> D3[Process Data]
Loading

Best Practices

API Usage

graph TD
    A[Best Practices] --> B[Performance]
    A --> C[Security]
    A --> D[Reliability]

    B --> B1[Caching]
    B --> B2[Pagination]
    B --> B3[Compression]

    C --> C1[HTTPS]
    C --> C2[Token Management]
    C --> C3[Input Validation]

    D --> D1[Retry Logic]
    D --> D2[Error Handling]
    D --> D3[Monitoring]
Loading

Security Guidelines

graph TD
    A[Security] --> B[Authentication]
    A --> C[Authorization]
    A --> D[Data Protection]

    B --> B1[Secure Storage]
    B --> B2[Token Rotation]
    B --> B3[Session Management]

    C --> C1[Role-Based]
    C --> C2[Scope-Based]
    C --> C3[Resource-Based]

    D --> D1[Encryption]
    D --> D2[Sanitization]
    D --> D3[Validation]
Loading

Additional Resources

API Resources

graph TD
    A[Resources] --> B[Documentation]
    A --> C[Tools]
    A --> D[Support]

    B --> B1[API Reference]
    B --> B2[Integration Guide]
    B --> B3[Examples]

    C --> C1[SDK]
    T --> T2[CLI]
    T --> T3[Postman]

    D --> D1[Support Portal]
    D --> D2[Status Page]
    D --> D3[Community]
Loading

Need help with the API? Contact our API team at api@contractai.com or visit our API Portal

Base URL

Production: https://api.contractai.com/v1
Staging: https://api.staging.contractai.com/v1
Development: https://api.dev.contractai.com/v1

Authentication

API Keys

All API requests require authentication using API keys. Include your API key in the X-API-Key header:

curl -H "X-API-Key: your-api-key" https://api.contractai.com/v1/agents

OAuth 2.0

For enterprise integrations, OAuth 2.0 is supported:

# Get access token
curl -X POST https://api.contractai.com/v1/oauth/token \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "client_credentials",
    "client_id": "your-client-id",
    "client_secret": "your-client-secret"
  }'

# Use access token
curl -H "Authorization: Bearer your-access-token" https://api.contractai.com/v1/agents

JWT Authentication

For secure agent-to-agent communication:

import jwt
import time

def generate_agent_token(agent_id: str, secret: str) -> str:
    payload = {
        "agent_id": agent_id,
        "iat": int(time.time()),
        "exp": int(time.time()) + 3600  # 1 hour expiration
    }
    return jwt.encode(payload, secret, algorithm="HS256")

Rate Limiting

  • Standard Tier: 100 requests per minute
  • Enterprise Tier: 1000 requests per minute
  • Custom Limits: Available for enterprise customers

Rate limit headers are included in all responses:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1625097600

API Endpoints

Agents

List Agents

GET /agents

Query Parameters:
- environment (string, optional): Filter by environment
- status (string, optional): Filter by status
- capability (string, optional): Filter by capability

Response:
{
  "agents": [
    {
      "id": "agent-123",
      "name": "primary-operations-agent",
      "status": "active",
      "environment": "production",
      "capabilities": ["infrastructure-monitoring", "incident-response"],
      "created_at": "2024-03-15T10:00:00Z",
      "last_active": "2024-03-15T15:30:00Z"
    }
  ],
  "pagination": {
    "total": 1,
    "page": 1,
    "per_page": 20
  }
}

Create Agent

POST /agents

Request Body:
{
  "name": "new-agent",
  "environment": "production",
  "capabilities": [
    "infrastructure-monitoring",
    "cost-optimization"
  ],
  "knowledge_sources": [
    {
      "type": "aws-bedrock",
      "region": "us-east-1"
    }
  ]
}

Response:
{
  "id": "agent-456",
  "name": "new-agent",
  "status": "initializing",
  "created_at": "2024-03-15T16:00:00Z",
  "deployment_url": "https://api.contractai.com/v1/agents/agent-456/deploy"
}

Get Agent Status

GET /agents/{agent_id}

Response:
{
  "id": "agent-123",
  "name": "primary-operations-agent",
  "status": "active",
  "health": {
    "overall": "healthy",
    "components": {
      "knowledge_base": "healthy",
      "monitoring": "healthy",
      "action_execution": "healthy"
    }
  },
  "metrics": {
    "requests_processed": 1500,
    "average_response_time": 0.8,
    "error_rate": 0.01
  }
}

Knowledge Base

Query Knowledge Base

POST /knowledge/query

Request Body:
{
  "query": "Show me our database backup procedures",
  "context": {
    "environment": "production",
    "service": "database"
  },
  "options": {
    "max_results": 5,
    "min_confidence": 0.8
  }
}

Response:
{
  "results": [
    {
      "content": "Database backup procedures...",
      "source": "documentation/database/backup.md",
      "confidence": 0.95,
      "metadata": {
        "last_updated": "2024-03-01T00:00:00Z",
        "author": "System Team"
      }
    }
  ],
  "suggestions": [
    "Would you like to see the backup schedule?",
    "Would you like to see the recovery procedures?"
  ]
}

Update Knowledge Base

POST /knowledge/update

Request Body:
{
  "operation": "add",
  "content": {
    "type": "procedure",
    "title": "New Backup Procedure",
    "content": "Updated backup steps...",
    "metadata": {
      "category": "database",
      "priority": "high"
    }
  }
}

Response:
{
  "status": "success",
  "document_id": "doc-789",
  "indexed_at": "2024-03-15T16:30:00Z"
}

Monitoring

Get System Status

GET /monitoring/status

Query Parameters:
- agent_id (string, required)
- service (string, optional)
- metric (string, optional)
- time_range (string, optional): "1h", "24h", "7d", "30d"

Response:
{
  "status": {
    "overall": "healthy",
    "services": {
      "database": {
        "status": "healthy",
        "metrics": {
          "cpu_usage": 45.2,
          "memory_usage": 60.1,
          "connections": 85
        }
      }
    }
  },
  "alerts": [
    {
      "id": "alert-123",
      "severity": "warning",
      "message": "High CPU usage detected",
      "timestamp": "2024-03-15T16:45:00Z"
    }
  ]
}

Configure Monitoring

POST /monitoring/configure

Request Body:
{
  "agent_id": "agent-123",
  "services": ["database", "application"],
  "metrics": {
    "database": {
      "cpu_usage": {
        "threshold": 80,
        "duration": "5m"
      },
      "connections": {
        "threshold": 100,
        "duration": "2m"
      }
    }
  },
  "notifications": {
    "channels": ["email", "slack"],
    "recipients": ["team@company.com", "#alerts"]
  }
}

Response:
{
  "status": "success",
  "configuration_id": "config-456",
  "applied_at": "2024-03-15T17:00:00Z"
}

Actions

Execute Action

POST /actions/execute

Request Body:
{
  "agent_id": "agent-123",
  "action": {
    "type": "scale_service",
    "parameters": {
      "service": "database",
      "target_capacity": 2
    }
  },
  "approval_required": true
}

Response:
{
  "action_id": "action-789",
  "status": "pending_approval",
  "approval_url": "https://api.contractai.com/v1/actions/action-789/approve",
  "estimated_completion": "2024-03-15T17:05:00Z"
}

Get Action Status

GET /actions/{action_id}

Response:
{
  "id": "action-789",
  "status": "completed",
  "result": {
    "success": true,
    "details": {
      "previous_capacity": 1,
      "new_capacity": 2,
      "completion_time": "2024-03-15T17:04:30Z"
    }
  },
  "logs": [
    {
      "timestamp": "2024-03-15T17:04:00Z",
      "message": "Starting service scaling",
      "level": "info"
    }
  ]
}

Error Handling

Error Response Format

{
  "error": {
    "code": "invalid_request",
    "message": "Invalid parameter value",
    "details": {
      "parameter": "environment",
      "reason": "must be one of: production, staging, development"
    }
  },
  "request_id": "req-123"
}

Common Error Codes

Code Description HTTP Status
invalid_request Invalid request parameters 400
unauthorized Authentication failed 401
forbidden Insufficient permissions 403
not_found Resource not found 404
rate_limited Rate limit exceeded 429
internal_error Server error 500

Webhooks

Configure Webhook

POST /webhooks

Request Body:
{
  "url": "https://your-domain.com/webhook",
  "events": ["agent.status_change", "alert.created"],
  "secret": "your-webhook-secret"
}

Response:
{
  "webhook_id": "webhook-123",
  "status": "active",
  "created_at": "2024-03-15T17:30:00Z"
}

Webhook Payload

{
  "event": "agent.status_change",
  "timestamp": "2024-03-15T17:35:00Z",
  "data": {
    "agent_id": "agent-123",
    "previous_status": "active",
    "new_status": "degraded",
    "reason": "high_error_rate"
  },
  "signature": "sha256=..."
}

SDK Examples

Python SDK

from contractai import ContractAI

# Initialize client
client = ContractAI(api_key="your-api-key")

# Create agent
agent = client.agents.create(
    name="monitoring-agent",
    environment="production",
    capabilities=["infrastructure-monitoring"]
)

# Query knowledge base
results = client.knowledge.query(
    query="Database backup procedures",
    context={"environment": "production"}
)

# Execute action
action = client.actions.execute(
    agent_id=agent.id,
    action={
        "type": "scale_service",
        "parameters": {"service": "database", "target_capacity": 2}
    }
)

Node.js SDK

const { ContractAI } = require("contractai-sdk");

// Initialize client
const client = new ContractAI({ apiKey: "your-api-key" });

// Get agent status
async function getAgentStatus(agentId) {
  const status = await client.agents.getStatus(agentId);
  console.log(`Agent status: ${status.health.overall}`);
}

// Configure monitoring
async function setupMonitoring(agentId) {
  await client.monitoring.configure({
    agentId,
    services: ["database"],
    metrics: {
      database: {
        cpu_usage: { threshold: 80, duration: "5m" },
      },
    },
  });
}

Best Practices

1. API Usage

  • Use appropriate authentication method
  • Implement retry logic with exponential backoff
  • Cache responses when appropriate
  • Monitor rate limits
  • Use webhooks for real-time updates

2. Security

  • Rotate API keys regularly
  • Use environment variables for credentials
  • Validate webhook signatures
  • Implement proper error handling
  • Use HTTPS for all requests

3. Performance

  • Use pagination for large result sets
  • Implement request batching
  • Cache frequently accessed data
  • Monitor API usage and limits
  • Use appropriate time ranges for queries

Additional Resources


Need help? Contact our API support team at api@contractai.com or visit our API Support Portal

ContractAI Documentation

Getting Started

Product Strategy

Technical Documentation

Development Resources

User Documentation

Operations & Support

Business Strategy

Market Positioning

Brand & Design

Project Management

Reference Implementations

Additional Resources

Clone this wiki locally