Endpoints da API REST
Referência completa de todos os endpoints disponíveis na API Tarefa AI. Todos os endpoints requerem autenticação, exceto os marcados como públicos.
Base URL
Production: https://api.tarefaai.com
Development: http://localhost:3000
Autenticação
Todos os endpoints (exceto públicos) requerem autenticação via:
- Cookie:
local-session(web apps) - Header:
Authorization: Bearer {token}(API/mobile)
Health Check
GET /api/health
Verifica status da API (público).
Request:
curl -X GET https://api.tarefaai.com/api/healthResponse (200 OK):
{
"status": "healthy",
"timestamp": "2025-01-17T10:00:00.000Z",
"version": "1.0.0",
"uptime": 3600
}Usuários
GET /api/user
Obtém dados do usuário autenticado.
Request:
curl -X GET https://api.tarefaai.com/api/user \
-H "Authorization: Bearer {token}"Response (200 OK):
{
"success": true,
"user": {
"id": 123,
"stackUserId": "user_abc123",
"email": "joao@example.com",
"name": "João Silva",
"role": "USER",
"timezone": "America/Sao_Paulo",
"isActive": true,
"trialEndsAt": "2025-02-17T10:00:00.000Z",
"createdAt": "2025-01-17T10:00:00.000Z",
"stats": {
"totalTasks": 15,
"activeTasks": 8,
"totalExecutions": 250,
"successRate": 94.5
}
}
}PATCH /api/user
Atualiza dados do usuário.
Request:
curl -X PATCH https://api.tarefaai.com/api/user \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"name": "João Pedro Silva",
"timezone": "America/Sao_Paulo"
}'Request Body:
interface UpdateUserRequest {
name?: string;
timezone?: string;
encryptedAnthropicKey?: string;
}Response (200 OK):
{
"success": true,
"user": {
"id": 123,
"name": "João Pedro Silva",
"timezone": "America/Sao_Paulo",
"updatedAt": "2025-01-17T10:30:00.000Z"
}
}Tarefas
POST /api/agent/create-task
Cria uma nova tarefa agendada.
Request:
curl -X POST https://api.tarefaai.com/api/agent/create-task \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"name": "Resumo Diário de Notícias",
"prompt": "Resuma as principais notícias de tecnologia do dia",
"scheduledFor": "2025-01-18T09:00:00.000Z",
"recurrence": "daily",
"timezone": "America/Sao_Paulo"
}'Request Body:
interface CreateTaskRequest {
name: string;
prompt: string;
scheduledFor: string; // ISO 8601 datetime
recurrence: "once" | "daily" | "weekly" | "monthly";
timezone: string;
}Response (201 Created):
{
"success": true,
"taskId": 456
}Validações:
name: 3-100 caracteresprompt: mínimo 10 caracteresscheduledFor: data futuratimezone: timezone válido (IANA format)
GET /api/tasks
Lista todas as tarefas do usuário (endpoint via Server Action).
GET /api/tasks/:id
Obtém detalhes de uma tarefa específica.
Response (200 OK):
{
"success": true,
"task": {
"id": 456,
"userId": 123,
"name": "Resumo Diário de Notícias",
"description": "Criado via Agent Mode - 17/01/2025 10:00:00",
"prompt": "Resuma as principais notícias de tecnologia do dia",
"scheduledFor": "2025-01-18T09:00:00.000Z",
"nextExecutionAt": "2025-01-19T09:00:00.000Z",
"recurrence": "daily",
"recurrencePattern": "0 0 * * *",
"timezone": "America/Sao_Paulo",
"claudeModel": "perplexity/sonar-reasoning-pro",
"maxTokens": 4096,
"temperature": 100,
"status": "active",
"executionCount": 5,
"lastExecutionAt": "2025-01-17T09:00:00.000Z",
"createdAt": "2025-01-17T10:00:00.000Z",
"updatedAt": "2025-01-17T10:00:00.000Z"
}
}Agent Mode
POST /api/agent/process
Processa uma tarefa imediatamente via Agent Mode (IA conversacional).
Request:
curl -X POST https://api.tarefaai.com/api/agent/process \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"message": "Crie um resumo das notícias de tech de hoje",
"context": {
"timezone": "America/Sao_Paulo",
"preferences": {
"length": "medium"
}
}
}'Request Body:
interface AgentProcessRequest {
message: string;
context?: {
timezone?: string;
preferences?: Record<string, any>;
};
}Response (200 OK):
{
"success": true,
"response": {
"content": "Aqui está o resumo das principais notícias...",
"tokensUsed": {
"input": 150,
"output": 450,
"total": 600
},
"model": "perplexity/sonar-reasoning-pro",
"processingTimeMs": 2340
},
"suggestions": [
"Deseja agendar este resumo diariamente?",
"Gostaria de receber via webhook?"
]
}Upload de Arquivos
POST /api/upload
Faz upload de arquivo para uso em tarefas (imagens, PDFs, texto).
Request:
curl -X POST https://api.tarefaai.com/api/upload \
-H "Authorization: Bearer {token}" \
-F "file=@documento.pdf"Limites:
- Tamanho máximo: 10MB
- Tipos permitidos: JPG, PNG, WebP, GIF, PDF, TXT, MD, CSV, JSON
Response (200 OK):
{
"url": "https://blob.vercel-storage.com/tasks/123/1674820800-documento.pdf",
"name": "documento.pdf",
"size": 2048576,
"type": "application/pdf",
"uploadedAt": "2025-01-17T10:00:00.000Z",
"storage": "blob"
}Response (Fallback Base64 - Development):
{
"url": "data:application/pdf;base64,JVBERi0xLjQK...",
"name": "documento.pdf",
"size": 2048576,
"type": "application/pdf",
"uploadedAt": "2025-01-17T10:00:00.000Z",
"storage": "base64"
}DELETE /api/upload
Remove arquivo do storage.
Request:
curl -X DELETE https://api.tarefaai.com/api/upload \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"url": "https://blob.vercel-storage.com/tasks/123/1674820800-documento.pdf"
}'Response (200 OK):
{
"success": true
}Erro (403 Forbidden):
{
"error": "Unauthorized to delete this file"
}Integrações
POST /api/integrations/notion/validate
Valida API key do Notion.
Request:
curl -X POST https://api.tarefaai.com/api/integrations/notion/validate \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"apiKey": "secret_abc123..."
}'Response (200 OK):
{
"valid": true,
"workspace": {
"name": "Meu Workspace",
"owner": "João Silva",
"id": "workspace_123"
}
}Erro (400 Bad Request):
{
"valid": false,
"error": "Invalid Notion API key"
}POST /api/integrations/figma/validate
Valida token do Figma.
Request:
curl -X POST https://api.tarefaai.com/api/integrations/figma/validate \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"token": "figd_abc123..."
}'Response (200 OK):
{
"valid": true,
"user": {
"name": "João Silva",
"email": "joao@example.com",
"id": "123456789"
}
}Cupons
POST /api/coupons/activate
Ativa um cupom de trial extension ou desconto.
Request:
curl -X POST https://api.tarefaai.com/api/coupons/activate \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"code": "WELCOME30"
}'Response (200 OK):
{
"success": true,
"message": "Cupom ativado com sucesso",
"coupon": {
"code": "WELCOME30",
"type": "TRIAL_EXTENSION",
"value": 30,
"appliedAt": "2025-01-17T10:00:00.000Z"
},
"user": {
"trialEndsAt": "2025-02-16T10:00:00.000Z"
}
}Erros:
// 404 - Cupom não encontrado
{
"success": false,
"error": "Cupom não encontrado ou inativo"
}
// 400 - Cupom expirado
{
"success": false,
"error": "Cupom expirado"
}
// 400 - Cupom já utilizado
{
"success": false,
"error": "Você já usou este cupom"
}
// 400 - Limite de usos atingido
{
"success": false,
"error": "Cupom atingiu o limite de usos"
}Admin - Estatísticas
GET /api/admin/stats
Obtém estatísticas do sistema (apenas admin).
Request:
curl -X GET https://api.tarefaai.com/api/admin/stats \
-H "Authorization: Bearer {token}" \
-H "X-Admin-Key: {admin_secret}"Response (200 OK):
{
"users": {
"total": 1250,
"active": 980,
"inactive": 270,
"newLast30Days": 85
},
"tasks": {
"total": 5600,
"active": 3200,
"inactive": 2400
},
"executions": {
"total": 125000,
"last30Days": 15600,
"byStatus": {
"completed": 118500,
"failed": 4500,
"pending": 1500,
"running": 500
},
"successRate": 94.8
},
"coupons": {
"total": 50,
"active": 30,
"inactive": 20
},
"topUsers": [
{
"userId": 123,
"userName": "João Silva",
"userEmail": "joao@example.com",
"executionCount": 450
}
]
}Admin - Usuários
GET /api/admin/users
Lista todos os usuários (apenas admin).
Request:
curl -X GET "https://api.tarefaai.com/api/admin/users?limit=50&offset=0&search=joao" \
-H "Authorization: Bearer {token}" \
-H "X-Admin-Key: {admin_secret}"Query Parameters:
interface UsersQuery {
limit?: number; // Default: 50
offset?: number; // Default: 0
search?: string; // Busca por email ou nome
role?: "USER" | "ADMIN";
isActive?: boolean;
}Response (200 OK):
{
"success": true,
"data": {
"users": [
{
"id": 123,
"stackUserId": "user_abc123",
"email": "joao@example.com",
"name": "João Silva",
"role": "USER",
"isActive": true,
"trialEndsAt": "2025-02-17T10:00:00.000Z",
"createdAt": "2025-01-17T10:00:00.000Z",
"stats": {
"totalTasks": 15,
"totalExecutions": 250
}
}
],
"pagination": {
"total": 1250,
"limit": 50,
"offset": 0,
"pages": 25
}
}
}GET /api/admin/users/:id
Obtém detalhes de um usuário específico (apenas admin).
Response (200 OK):
{
"success": true,
"user": {
"id": 123,
"stackUserId": "user_abc123",
"email": "joao@example.com",
"name": "João Silva",
"role": "USER",
"isActive": true,
"timezone": "America/Sao_Paulo",
"trialEndsAt": "2025-02-17T10:00:00.000Z",
"createdAt": "2025-01-17T10:00:00.000Z",
"updatedAt": "2025-01-17T10:00:00.000Z",
"stats": {
"totalTasks": 15,
"activeTasks": 8,
"totalExecutions": 250,
"successRate": 94.5,
"failedExecutions": 12
},
"recentActivity": [
{
"type": "task_created",
"timestamp": "2025-01-17T09:00:00.000Z",
"details": "Criou tarefa: Resumo Diário"
}
]
}
}PATCH /api/admin/users/:id
Atualiza dados de um usuário (apenas admin).
Request:
curl -X PATCH https://api.tarefaai.com/api/admin/users/123 \
-H "Authorization: Bearer {token}" \
-H "X-Admin-Key: {admin_secret}" \
-H "Content-Type: application/json" \
-d '{
"role": "ADMIN",
"isActive": true,
"trialEndsAt": "2025-03-17T10:00:00.000Z"
}'Request Body:
interface UpdateUserAdminRequest {
role?: "USER" | "ADMIN";
isActive?: boolean;
trialEndsAt?: string; // ISO 8601
}Response (200 OK):
{
"success": true,
"user": {
"id": 123,
"role": "ADMIN",
"isActive": true,
"trialEndsAt": "2025-03-17T10:00:00.000Z",
"updatedAt": "2025-01-17T10:30:00.000Z"
}
}DELETE /api/admin/users/:id
Remove um usuário (apenas admin).
Response (200 OK):
{
"success": true,
"message": "Usuário removido com sucesso"
}Admin - Cupons
GET /api/admin/coupons
Lista todos os cupons (apenas admin).
Request:
curl -X GET "https://api.tarefaai.com/api/admin/coupons?limit=50&offset=0" \
-H "Authorization: Bearer {token}" \
-H "X-Admin-Key: {admin_secret}"Response (200 OK):
{
"success": true,
"data": {
"coupons": [
{
"id": 1,
"code": "WELCOME30",
"isActive": true,
"maxUses": 100,
"usedCount": 45,
"expiresAt": "2025-12-31T23:59:59.000Z",
"createdByEmail": "admin@tarefaai.com",
"createdAt": "2025-01-01T00:00:00.000Z",
"updatedAt": "2025-01-17T10:00:00.000Z"
}
],
"stats": {
"totalCoupons": 50,
"activeCoupons": 30,
"totalUses": 450
},
"pagination": {
"limit": 50,
"offset": 0,
"total": 50
}
}
}POST /api/admin/coupons
Cria um novo cupom (apenas admin).
Request:
curl -X POST https://api.tarefaai.com/api/admin/coupons \
-H "Authorization: Bearer {token}" \
-H "X-Admin-Key: {admin_secret}" \
-H "Content-Type: application/json" \
-d '{
"maxUses": 100,
"expiresAt": "2025-12-31T23:59:59.000Z"
}'Request Body:
interface CreateCouponRequest {
maxUses?: number | null; // null = ilimitado
expiresAt?: string | null; // ISO 8601, null = sem expiração
}Response (201 Created):
{
"success": true,
"data": {
"id": 51,
"code": "ABC123XYZ",
"isActive": true,
"maxUses": 100,
"usedCount": 0,
"expiresAt": "2025-12-31T23:59:59.000Z",
"createdByEmail": "admin@tarefaai.com",
"createdAt": "2025-01-17T10:00:00.000Z"
},
"message": "Coupon ABC123XYZ created successfully"
}GET /api/admin/coupons/:id
Obtém detalhes de um cupom (apenas admin).
Response (200 OK):
{
"success": true,
"coupon": {
"id": 1,
"code": "WELCOME30",
"isActive": true,
"maxUses": 100,
"usedCount": 45,
"expiresAt": "2025-12-31T23:59:59.000Z",
"createdByEmail": "admin@tarefaai.com",
"createdAt": "2025-01-01T00:00:00.000Z",
"updatedAt": "2025-01-17T10:00:00.000Z"
}
}PATCH /api/admin/coupons/:id
Atualiza um cupom (apenas admin).
Request:
curl -X PATCH https://api.tarefaai.com/api/admin/coupons/1 \
-H "Authorization: Bearer {token}" \
-H "X-Admin-Key: {admin_secret}" \
-H "Content-Type: application/json" \
-d '{
"isActive": false,
"maxUses": 50
}'Request Body:
interface UpdateCouponRequest {
isActive?: boolean;
maxUses?: number | null;
expiresAt?: string | null;
}Response (200 OK):
{
"success": true,
"coupon": {
"id": 1,
"isActive": false,
"maxUses": 50,
"updatedAt": "2025-01-17T10:30:00.000Z"
}
}DELETE /api/admin/coupons/:id
Remove um cupom (apenas admin).
Response (200 OK):
{
"success": true,
"message": "Cupom removido com sucesso"
}GET /api/admin/coupons/:id/usage
Obtém histórico de uso de um cupom (apenas admin).
Response (200 OK):
{
"success": true,
"usage": [
{
"userId": 123,
"userEmail": "joao@example.com",
"userName": "João Silva",
"usedAt": "2025-01-17T10:00:00.000Z"
}
],
"summary": {
"totalUses": 45,
"maxUses": 100,
"remainingUses": 55
}
}Admin - Configurações
GET /api/admin/settings
Obtém configurações do sistema (apenas admin).
Response (200 OK):
{
"success": true,
"settings": {
"trialDurationDays": 14,
"maxTasksPerUser": 50,
"maxExecutionsPerDay": 100,
"defaultModel": "perplexity/sonar-reasoning-pro",
"maintenanceMode": false
}
}PATCH /api/admin/settings
Atualiza configurações do sistema (apenas admin).
Request:
curl -X PATCH https://api.tarefaai.com/api/admin/settings \
-H "Authorization: Bearer {token}" \
-H "X-Admin-Key: {admin_secret}" \
-H "Content-Type: application/json" \
-d '{
"trialDurationDays": 30,
"maintenanceMode": false
}'Response (200 OK):
{
"success": true,
"settings": {
"trialDurationDays": 30,
"maintenanceMode": false,
"updatedAt": "2025-01-17T10:30:00.000Z"
}
}Cron (Interno)
GET /api/cron/scheduler
Endpoint interno para Vercel Cron Jobs (não requer autenticação de usuário).
Headers Requeridos:
Authorization: Bearer {CRON_SECRET}Response (200 OK):
{
"success": true,
"processed": 45,
"failed": 2,
"duration": 3456
}TypeScript Interfaces
Tipos Globais
// Usuário
interface User {
id: number;
stackUserId: string;
email: string;
name: string;
role: "USER" | "ADMIN";
timezone: string | null;
isActive: boolean;
trialEndsAt: Date | null;
createdAt: Date;
updatedAt: Date;
}
// Tarefa
interface Task {
id: number;
userId: number;
name: string;
description: string | null;
prompt: string;
scheduledFor: Date;
nextExecutionAt: Date | null;
recurrence: "once" | "daily" | "weekly" | "monthly";
recurrencePattern: string | null;
timezone: string;
claudeModel: string;
maxTokens: number;
temperature: number;
status: "active" | "paused" | "completed" | "failed";
executionCount: number;
lastExecutionAt: Date | null;
createdAt: Date;
updatedAt: Date;
}
// Execução
interface TaskExecution {
id: number;
taskId: number;
userId: number;
status: "pending" | "running" | "completed" | "failed";
result: string | null;
error: string | null;
tokensUsed: number | null;
processingTimeMs: number | null;
createdAt: Date;
completedAt: Date | null;
}
// Resposta Padrão
interface ApiResponse<T = any> {
success: boolean;
data?: T;
error?: string;
message?: string;
}Códigos de Status HTTP
| Código | Descrição |
|---|---|
| 200 | Sucesso |
| 201 | Recurso criado |
| 204 | Sucesso sem conteúdo |
| 400 | Requisição inválida |
| 401 | Não autenticado |
| 403 | Sem permissão |
| 404 | Recurso não encontrado |
| 409 | Conflito (recurso já existe) |
| 422 | Entidade não processável (validação) |
| 429 | Rate limit excedido |
| 500 | Erro interno do servidor |
| 503 | Serviço indisponível (manutenção) |
Próximos Passos
Especificação OpenAPI: Disponível em /docs/api/openapi.yaml
Postman Collection: Disponível em /docs/api/postman-collection.json