Referência da API
Referência completa da API para integração com a plataforma Assistant. Inclui autenticação, endpoints, esquemas de solicitação/resposta, e exemplos práticos de código.
Autenticação
A API suporta dois métodos de autenticação:
- Autenticação com chave API: Use os cabeçalhos X-API-Key e X-API-Secret para acesso direto à API
- Autenticação com token JWT: Use tokens Bearer obtidos do endpoint de token widget para solicitações baseadas em navegador
Endpoint de Token Widget
Gere tokens JWT de curta duração para autenticação de widgets. Este endpoint permite que os widgets obtenham tokens seguros usando apenas o client_id, evitando a necessidade de expor o client_secret em ambientes de navegador.
{"client_id": "YOUR_CLIENT_ID"}Resposta:
{ "token": "eyJ...", "expires_in": 3600, "token_type": "Bearer"}Limitação de taxa
As solicitações da API são limitadas a 1000 por hora por organização. As informações de limitação de taxa estão incluídas nos cabeçalhos de resposta.
Tratamento de erros
Todos os erros da API retornam respostas JSON estruturadas com códigos de status, detalhes de erro e campos de dados opcionais.
{ "status": "error", "status_code": 401, "detail": "Authentication required - ...", "data": null}Endpoints da API
Assistentes
Gerenciar personas de assistente de IA com configurações personalizadas.
Listar assistentes
curl -X GET https://app.companin.tech/api/v1/assistants/ \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET"Criar assistente
curl -X POST https://app.companin.tech/api/v1/assistants/ \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET" \ -H "Content-Type: application/json" \ -d '{ "name": "Customer Support Bot", "description": "Helpful assistant for customer inquiries", "tone": "professional", "language": "en", "default_tasks": ["answer_questions", "provide_support"], "is_active": true }'Sessões
Criar sessões de visitantes anônimos para interações temporárias.
Criar sessão
curl -X POST https://app.companin.tech/api/v1/sessions/ \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET" \ -H "Content-Type: application/json" \ -d '{ "assistant_id": "550e8400-e29b-41d4-a716-446655440000", "visitor_id": "visitor-123", "locale": "en", "metadata": { "source": "website", "page": "/contact" } }'Enviar mensagem na sessão
curl -X POST https://app.companin.tech/api/v1/sessions/${SESSION_ID}/messages \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET" \ -H "Content-Type: application/json" \ -d '{ "content": "Hello, I need help with my order", "metadata": { "user_type": "customer" } }'Conversas
Criar conversas persistentes para usuários autenticados.
Criar conversa
curl -X POST https://app.companin.tech/api/v1/conversations/ \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET" \ -H "Content-Type: application/json" \ -d '{ "assistant_id": "550e8400-e29b-41d4-a716-446655440000", "customer_id": "user-456", "title": "Order Support", "locale": "en" }'Enviar mensagem na conversa
curl -X POST https://app.companin.tech/api/v1/conversations/${CONVERSATION_ID}/messages \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET" \ -H "Content-Type: application/json" \ -d '{ "content": "Can you help me track my order?", "metadata": { "order_id": "12345" } }'Contextos do usuário
Armazenar e gerenciar contexto do usuário para interações personalizadas.
Criar contexto do usuário
curl -X POST https://app.companin.tech/api/v1/contexts/ \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET" \ -H "Content-Type: application/json" \ -d '{ "user_reference": "user-456", "traits": { "name": "John Doe", "email": "john@example.com", "subscription_tier": "premium", "preferences": { "language": "en", "notifications": true } } }'Base de conhecimentos
Fazer upload e gerenciar fontes de conhecimento para seus assistentes.
Fazer upload de arquivo de conhecimento
curl -X POST https://app.companin.tech/api/v1/knowledge/files/ \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET" \ -F "title=Product Manual" \ -F "file_type=pdf" \ -F "file=@product_manual.pdf"Adicionar par de perguntas e respostas
curl -X POST https://app.companin.tech/api/v1/knowledge/qa/ \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET" \ -H "Content-Type: application/json" \ -d '{ "question": "What are your business hours?", "answer": "We are open Monday to Friday, 9 AM to 6 PM EST.", "tags": ["hours", "support"] }'Casos de uso
Chatbot de Suporte ao Cliente
// 1. Obter token do widget para chat baseado em navegadorasync function getWidgetToken() { const response = await fetch('https://app.companin.tech/api/v1/auth/widget-token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ client_id: 'YOUR_CLIENT_ID' }) }); return (await response.json()).token;}// 2. Criar uma sessão para visitante anônimoasync function startSupportSession(token, assistantId) { const response = await fetch('https://app.companin.tech/api/v1/sessions/', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ assistant_id: assistantId, visitor_id: 'visitor-' + Date.now(), metadata: { source: 'support_widget' } }) }); return await response.json();}// 3. Enviar mensagem do cliente e obter resposta da IAasync function sendMessage(token, sessionId, message) { const response = await fetch(`https://app.companin.tech/api/v1/sessions/${sessionId}/messages`, { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ content: message, metadata: { user_type: 'customer' } }) }); return await response.json();}// Exemplo de usoconst token = await getWidgetToken();const session = await startSupportSession(token, 'assistant-uuid');const result = await sendMessage(token, session.data.id, 'Preciso de ajuda com meu pedido');Assistente de Produto de E-commerce
// 1. Criar contexto do usuário para personalizaçãoasync function createUserContext(userId, userData) { const response = await fetch('https://app.companin.tech/api/v1/contexts/', { method: 'POST', headers: { 'X-API-Key': 'YOUR_CLIENT_ID', 'X-API-Secret': 'YOUR_CLIENT_SECRET', 'Content-Type': 'application/json' }, body: JSON.stringify({ user_reference: userId, traits: { name: userData.name, purchase_history: userData.purchases, preferences: userData.preferences } }) }); return await response.json();}// 2. Criar conversa persistente com contextoasync function startPersonalizedChat(assistantId, userId) { const response = await fetch('https://app.companin.tech/api/v1/conversations/', { method: 'POST', headers: { 'X-API-Key': 'YOUR_CLIENT_ID', 'X-API-Secret': 'YOUR_CLIENT_SECRET', 'Content-Type': 'application/json' }, body: JSON.stringify({ assistant_id: assistantId, customer_id: userId, user_context_id: userId, title: 'Product Recommendations', metadata: { source: 'product_page' } }) }); return await response.json();}// 3. Conversar com conhecimento do produtoasync function askAboutProduct(conversationId, question) { const response = await fetch(`https://app.companin.tech/api/v1/conversations/${conversationId}/messages`, { method: 'POST', headers: { 'X-API-Key': 'YOUR_CLIENT_ID', 'X-API-Secret': 'YOUR_CLIENT_SECRET', 'Content-Type': 'application/json' }, body: JSON.stringify({ content: question, metadata: { context: 'product_inquiry' } }) }); return await response.json();}// Exemplo de usoawait createUserContext('user-123', { name: 'Alice', purchases: ['laptop-1', 'mouse-2'], preferences: { category: 'electronics' }});const conversation = await startPersonalizedChat('assistant-uuid', 'user-123');const result = await askAboutProduct(conversation.data.id, 'Qual laptop você recomenda?');Sistema de Gestão do Conhecimento
// 1. Fazer upload da documentação do produtoasync function uploadDocumentation(file, title) { const formData = new FormData(); formData.append('title', title); formData.append('file_type', 'pdf'); formData.append('file', file); const response = await fetch('https://app.companin.tech/api/v1/knowledge/files/', { method: 'POST', headers: { 'X-API-Key': 'YOUR_CLIENT_ID', 'X-API-Secret': 'YOUR_CLIENT_SECRET' }, body: formData }); return await response.json();}// 2. Adicionar entradas de FAQasync function addFAQ(question, answer, tags) { const response = await fetch('https://app.companin.tech/api/v1/knowledge/qa/', { method: 'POST', headers: { 'X-API-Key': 'YOUR_CLIENT_ID', 'X-API-Secret': 'YOUR_CLIENT_SECRET', 'Content-Type': 'application/json' }, body: JSON.stringify({ question, answer, tags, source: 'manual' }) }); return await response.json();}// 3. Adicionar conteúdo webasync function addWebContent(url, title) { const response = await fetch('https://app.companin.tech/api/v1/knowledge/urls/', { method: 'POST', headers: { 'X-API-Key': 'YOUR_CLIENT_ID', 'X-API-Secret': 'YOUR_CLIENT_SECRET', 'Content-Type': 'application/json' }, body: JSON.stringify({ url, title }) }); return await response.json();}// Exemplo de usoconst fileUpload = await uploadDocumentation(pdfFile, 'User Manual v2.0');const faq = await addFAQ( 'Como redefino minha senha?', 'Vá para configurações e clique em "Redefinir senha"...', ['password', 'security']);const webContent = await addWebContent( 'https://example.tech/blog/new-features', 'Anúncio de novos recursos');Exemplos
Obter Token Widget
curl -X POST https://app.companin.tech/api/v1/auth/widget-token \ -H "Content-Type: application/json" \ -d '{"client_id":"YOUR_CLIENT_ID"}'Criar Sessão
fetch('https://app.companin.tech/api/v1/sessions', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ assistant_id: 'ASSISTANT_UUID' })})Suporte CORS
- Todos os endpoints suportam CORS para integrações web
- As solicitações preflight são tratadas automaticamente
- As credenciais são suportadas para solicitações autenticadas