Integration Guide

🔌 Guia de Integração - CSuite

Versão: 1.0
Última Atualização: 2025-01-02
Responsável: Equipe de Desenvolvimento


📋 Índice

  1. Visão Geral
  2. Autenticação
  3. APIs Disponíveis
  4. Integração com Context API
  5. Integração com Executive API
  6. Webhooks
  7. Rate Limiting
  8. Tratamento de Erros
  9. Exemplos

🎯 Visão Geral

Este guia descreve como integrar sistemas externos com o CSuite, incluindo autenticação, APIs disponíveis e melhores práticas.

Casos de Uso


🔐 Autenticação

API Keys

Obter API Key:
1. Acessar portal de administração
2. Criar nova API Key
3. Copiar e armazenar de forma segura

Usar API Key:

curl -H "X-API-Key: your-api-key" \
  http://localhost:8080/api/v1/endpoint

JWT Tokens

Obter Token:

curl -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "user",
    "password": "password"
  }'

Resposta:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 3600
}

Usar Token:

curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  http://localhost:8080/api/v1/endpoint

🔌 APIs Disponíveis

Context API

Base URL: http://localhost:8080/api/v1/context

Endpoints:
- GET /context/{entity_id} - Obter contexto de entidade
- POST /context - Criar contexto
- PUT /context/{context_id} - Atualizar contexto
- DELETE /context/{context_id} - Deletar contexto

Mais informações: Context API Documentation


Executive API

Base URL: http://localhost:8080/api/v1/executive

Endpoints:
- POST /decisions - Criar decisão
- GET /decisions/{decision_id} - Obter decisão
- GET /decisions - Listar decisões
- GET /outcomes/{outcome_id} - Obter outcome

Mais informações: Executive API Documentation


Operations API

Base URL: http://localhost:8080/api/v1/operations

Endpoints:
- GET /policies - Listar políticas
- GET /policies/{policy_id} - Obter política
- GET /agents - Listar agentes
- GET /agents/{agent_id} - Obter agente

Mais informações: Operations API Documentation


📊 Integração com Context API

Obter Contexto

Request:

curl -X GET \
  http://localhost:8080/api/v1/context/123 \
  -H "Authorization: Bearer <token>"

Response:

{
  "context_id": 123,
  "entity_id": 456,
  "entity_type": "revenda",
  "data": {
    "vendas_12m": 1000,
    "estoque_atual": 500
  },
  "created_at": "2025-01-02T10:00:00Z",
  "updated_at": "2025-01-02T10:00:00Z"
}

Criar Contexto

Request:

curl -X POST \
  http://localhost:8080/api/v1/context \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "entity_id": 456,
    "entity_type": "revenda",
    "data": {
      "vendas_12m": 1000,
      "estoque_atual": 500
    }
  }'

Response:

{
  "context_id": 789,
  "entity_id": 456,
  "entity_type": "revenda",
  "data": {
    "vendas_12m": 1000,
    "estoque_atual": 500
  },
  "created_at": "2025-01-02T10:00:00Z"
}

🎯 Integração com Executive API

Criar Decisão

Request:

curl -X POST \
  http://localhost:8080/api/v1/executive/decisions \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "context_id": 123,
    "entity_id": 456,
    "entity_type": "revenda"
  }'

Response:

{
  "decision_id": 101,
  "context_id": 123,
  "status": "pending",
  "created_at": "2025-01-02T10:00:00Z"
}

Obter Decisão

Request:

curl -X GET \
  http://localhost:8080/api/v1/executive/decisions/101 \
  -H "Authorization: Bearer <token>"

Response:

{
  "decision_id": 101,
  "context_id": 123,
  "status": "completed",
  "outcomes": [
    {
      "policy_code": "INV_LOW_TURN",
      "severity": "high",
      "message": "Estoque com baixa rotatividade"
    }
  ],
  "created_at": "2025-01-02T10:00:00Z",
  "completed_at": "2025-01-02T10:00:05Z"
}

🔔 Webhooks

Configurar Webhook

Criar webhook:

curl -X POST \
  http://localhost:8080/api/v1/webhooks \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/webhook",
    "events": ["decision.completed", "outcome.created"],
    "secret": "webhook-secret"
  }'

Receber Webhook

Payload:

{
  "event": "decision.completed",
  "timestamp": "2025-01-02T10:00:00Z",
  "data": {
    "decision_id": 101,
    "status": "completed",
    "outcomes": [...]
  }
}

Verificar assinatura:

import hmac
import hashlib

def verify_webhook_signature(payload, signature, secret):
    expected_signature = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature, expected_signature)

⚡ Rate Limiting

Limites

Por API Key:
- Padrão: 1000 requests/hora
- Premium: 10000 requests/hora

Por IP:
- Padrão: 100 requests/minuto

Headers de Rate Limit

Response headers:

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

Tratamento

Quando exceder limite:
- Status: 429 Too Many Requests
- Retry-After: Tempo em segundos até próximo reset

Exemplo:

import time
import requests

def make_request_with_retry(url, headers, max_retries=3):
    for attempt in range(max_retries):
        response = requests.get(url, headers=headers)

        if response.status_code == 429:
            retry_after = int(response.headers.get('Retry-After', 60))
            time.sleep(retry_after)
            continue

        return response

    raise Exception("Max retries exceeded")

❌ Tratamento de Erros

Códigos de Status

Sucesso:
- 200 OK - Requisição bem-sucedida
- 201 Created - Recurso criado
- 204 No Content - Sucesso sem conteúdo

Erro do Cliente:
- 400 Bad Request - Requisição inválida
- 401 Unauthorized - Não autenticado
- 403 Forbidden - Sem permissão
- 404 Not Found - Recurso não encontrado
- 429 Too Many Requests - Rate limit excedido

Erro do Servidor:
- 500 Internal Server Error - Erro interno
- 502 Bad Gateway - Erro no gateway
- 503 Service Unavailable - Serviço indisponível

Formato de Erro

Response:

{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Invalid entity_id",
    "details": {
      "field": "entity_id",
      "reason": "Must be a positive integer"
    }
  }
}

Tratamento

Exemplo em Python:

import requests

def handle_api_error(response):
    if response.status_code == 400:
        error = response.json()["error"]
        print(f"Bad Request: {error['message']}")
        return None
    elif response.status_code == 401:
        print("Unauthorized: Check your credentials")
        return None
    elif response.status_code == 429:
        retry_after = response.headers.get('Retry-After')
        print(f"Rate limit exceeded. Retry after {retry_after} seconds")
        return None
    elif response.status_code >= 500:
        print("Server error: Try again later")
        return None

    return response.json()

💡 Exemplos

Python

Exemplo completo:

import requests
import time

class CSuiteClient:
    def __init__(self, base_url, api_key):
        self.base_url = base_url
        self.headers = {
            "X-API-Key": api_key,
            "Content-Type": "application/json"
        }

    def get_context(self, entity_id):
        url = f"{self.base_url}/api/v1/context/{entity_id}"
        response = requests.get(url, headers=self.headers)

        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"Error: {response.status_code}")

    def create_decision(self, context_id, entity_id):
        url = f"{self.base_url}/api/v1/executive/decisions"
        payload = {
            "context_id": context_id,
            "entity_id": entity_id,
            "entity_type": "revenda"
        }
        response = requests.post(url, json=payload, headers=self.headers)

        if response.status_code == 201:
            return response.json()
        else:
            raise Exception(f"Error: {response.status_code}")

# Uso
client = CSuiteClient("http://localhost:8080", "your-api-key")
context = client.get_context(123)
decision = client.create_decision(context["context_id"], 456)

JavaScript/Node.js

Exemplo:

const axios = require('axios');

class CSuiteClient {
  constructor(baseUrl, apiKey) {
    this.baseUrl = baseUrl;
    this.client = axios.create({
      baseURL: baseUrl,
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      }
    });
  }

  async getContext(entityId) {
    const response = await this.client.get(`/api/v1/context/${entityId}`);
    return response.data;
  }

  async createDecision(contextId, entityId) {
    const response = await this.client.post('/api/v1/executive/decisions', {
      context_id: contextId,
      entity_id: entityId,
      entity_type: 'revenda'
    });
    return response.data;
  }
}

// Uso
const client = new CSuiteClient('http://localhost:8080', 'your-api-key');
const context = await client.getContext(123);
const decision = await client.createDecision(context.context_id, 456);

🔗 Documentos Relacionados


Última Revisão: 2025-01-02
Próxima Revisão: 2025-04-02 (trimestral)

🔊 Text-to-Speech

1.0x
1.0
Pronto para reproduzir