Executions API
A API de Executions permite monitorar e gerenciar as execuções de seus flows.
Visão Geral
Cada vez que um flow é executado, uma execução (execution) é criada. As executions contêm informações sobre:
- Status da execução (running, completed, failed)
- Dados de entrada e saída
- Logs de cada nó
- Tempo de execução
- Erros e warnings
Endpoints
Listar Execuções
Lista todas as execuções de flows.
GET /executions
Query Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
page |
integer | Número da página (padrão: 1) |
limit |
integer | Itens por página (padrão: 20, máx: 100) |
flowId |
string | Filtrar por flow específico |
status |
string | Filtrar por status: running, completed, failed, cancelled |
startDate |
string | Data inicial (ISO 8601) |
endDate |
string | Data final (ISO 8601) |
sortBy |
string | Campo para ordenação: startedAt, completedAt, duration |
order |
string | Ordem: asc, desc (padrão: desc) |
Exemplo de Requisição
curl -X GET "https://api.lumina.app.br/v1/executions?status=completed&limit=10" \
-H "Authorization: Bearer lumina_sk_your_api_key"
Resposta de Sucesso (200)
{
"success": true,
"data": [
{
"id": "exec_abc123",
"flowId": "flow_xyz789",
"flowName": "Processar Pedidos WhatsApp",
"status": "completed",
"trigger": {
"type": "webhook",
"data": {
"userId": "user_456",
"orderId": "order_789"
}
},
"startedAt": "2025-01-15T10:30:00Z",
"completedAt": "2025-01-15T10:30:03Z",
"duration": 3000,
"nodesExecuted": 5,
"errorCount": 0,
"warningCount": 1
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 1523,
"totalPages": 153,
"hasNext": true,
"hasPrev": false
}
}
Obter Execução
Retorna detalhes completos de uma execução específica.
GET /executions/:id
Path Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
id |
string | ID da execução |
Query Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
includeLogs |
boolean | Incluir logs completos (padrão: false) |
includeNodeOutputs |
boolean | Incluir outputs de todos os nós (padrão: false) |
Exemplo de Requisição
curl -X GET "https://api.lumina.app.br/v1/executions/exec_abc123?includeLogs=true" \
-H "Authorization: Bearer lumina_sk_your_api_key"
Resposta de Sucesso (200)
{
"success": true,
"data": {
"id": "exec_abc123",
"flowId": "flow_xyz789",
"flowName": "Processar Pedidos WhatsApp",
"flowVersion": 3,
"status": "completed",
"trigger": {
"type": "webhook",
"timestamp": "2025-01-15T10:30:00Z",
"data": {
"userId": "user_456",
"orderId": "order_789",
"items": [...]
}
},
"startedAt": "2025-01-15T10:30:00Z",
"completedAt": "2025-01-15T10:30:03Z",
"duration": 3000,
"nodes": [
{
"nodeId": "node_1",
"nodeName": "Validar Estoque",
"type": "http-request",
"status": "completed",
"startedAt": "2025-01-15T10:30:00.100Z",
"completedAt": "2025-01-15T10:30:01.200Z",
"duration": 1100,
"retries": 0,
"output": {
"available": true,
"quantity": 50
}
},
{
"nodeId": "node_2",
"nodeName": "Verificar Disponibilidade",
"type": "if-else",
"status": "completed",
"startedAt": "2025-01-15T10:30:01.250Z",
"completedAt": "2025-01-15T10:30:01.300Z",
"duration": 50,
"output": {
"branch": "true"
}
},
{
"nodeId": "node_3",
"nodeName": "Criar Pedido",
"type": "http-request",
"status": "completed",
"startedAt": "2025-01-15T10:30:01.350Z",
"completedAt": "2025-01-15T10:30:02.800Z",
"duration": 1450,
"retries": 0,
"output": {
"orderId": "order_999",
"status": "created"
}
}
],
"output": {
"success": true,
"orderId": "order_999",
"message": "Pedido criado com sucesso"
},
"metadata": {
"source": "webhook",
"ip": "192.168.1.100",
"userAgent": "WhatsApp-Webhook/1.0"
},
"errorCount": 0,
"warningCount": 1,
"warnings": [
{
"nodeId": "node_3",
"message": "Response time above threshold",
"timestamp": "2025-01-15T10:30:02.800Z"
}
]
}
}
Resposta de Erro (404)
{
"success": false,
"error": {
"code": "NOT_FOUND",
"message": "Execução não encontrada"
}
}
Obter Logs de Execução
Retorna os logs detalhados de uma execução.
GET /executions/:id/logs
Path Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
id |
string | ID da execução |
Query Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
level |
string | Filtrar por nível: info, warning, error |
nodeId |
string | Filtrar por nó específico |
Exemplo de Requisição
curl -X GET "https://api.lumina.app.br/v1/executions/exec_abc123/logs" \
-H "Authorization: Bearer lumina_sk_your_api_key"
Resposta de Sucesso (200)
{
"success": true,
"data": [
{
"timestamp": "2025-01-15T10:30:00.050Z",
"level": "info",
"nodeId": null,
"message": "Execution started",
"data": {
"executionId": "exec_abc123",
"flowId": "flow_xyz789"
}
},
{
"timestamp": "2025-01-15T10:30:00.100Z",
"level": "info",
"nodeId": "node_1",
"message": "Node execution started: Validar Estoque"
},
{
"timestamp": "2025-01-15T10:30:01.200Z",
"level": "info",
"nodeId": "node_1",
"message": "HTTP request completed",
"data": {
"method": "GET",
"url": "https://api.example.com/stock/prod_789",
"status": 200,
"duration": 1100
}
},
{
"timestamp": "2025-01-15T10:30:02.800Z",
"level": "warning",
"nodeId": "node_3",
"message": "Response time above threshold",
"data": {
"duration": 1450,
"threshold": 1000
}
},
{
"timestamp": "2025-01-15T10:30:03.000Z",
"level": "info",
"nodeId": null,
"message": "Execution completed successfully",
"data": {
"duration": 3000,
"nodesExecuted": 5
}
}
]
}
Cancelar Execução
Cancela uma execução em andamento.
POST /executions/:id/cancel
Path Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
id |
string | ID da execução |
Request Body
{
"reason": "Cancelado manualmente pelo usuário"
}
Exemplo de Requisição
curl -X POST "https://api.lumina.app.br/v1/executions/exec_abc123/cancel" \
-H "Authorization: Bearer lumina_sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"reason": "Duplicated execution detected"
}'
Resposta de Sucesso (200)
{
"success": true,
"data": {
"id": "exec_abc123",
"status": "cancelled",
"cancelledAt": "2025-01-15T10:31:00Z",
"reason": "Duplicated execution detected"
}
}
Resposta de Erro (400)
{
"success": false,
"error": {
"code": "INVALID_STATUS",
"message": "Execução já foi finalizada e não pode ser cancelada",
"details": {
"currentStatus": "completed"
}
}
}
Reexecutar Flow
Cria uma nova execução usando os mesmos dados de entrada de uma execução anterior.
POST /executions/:id/retry
Path Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
id |
string | ID da execução original |
Request Body
{
"overrideData": {
"userId": "user_new_123"
},
"fromNode": null
}
| Campo | Tipo | Descrição |
|---|---|---|
overrideData |
object | Sobrescrever dados de entrada (opcional) |
fromNode |
string | Iniciar de um nó específico (opcional) |
Exemplo de Requisição
curl -X POST "https://api.lumina.app.br/v1/executions/exec_abc123/retry" \
-H "Authorization: Bearer lumina_sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{}'
Resposta de Sucesso (202)
{
"success": true,
"data": {
"executionId": "exec_new456",
"originalExecutionId": "exec_abc123",
"status": "running",
"startedAt": "2025-01-15T10:35:00Z"
}
}
Estatísticas de Execuções
Retorna estatísticas agregadas de execuções.
GET /executions/stats
Query Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
flowId |
string | Filtrar por flow específico |
startDate |
string | Data inicial (ISO 8601) |
endDate |
string | Data final (ISO 8601) |
groupBy |
string | Agrupar por: day, week, month |
Exemplo de Requisição
curl -X GET "https://api.lumina.app.br/v1/executions/stats?flowId=flow_xyz789&groupBy=day" \
-H "Authorization: Bearer lumina_sk_your_api_key"
Resposta de Sucesso (200)
{
"success": true,
"data": {
"summary": {
"totalExecutions": 1523,
"completed": 1450,
"failed": 68,
"cancelled": 5,
"running": 0,
"successRate": 95.2,
"averageDuration": 2850,
"totalDuration": 4340550
},
"byStatus": {
"completed": 1450,
"failed": 68,
"cancelled": 5
},
"byDay": [
{
"date": "2025-01-10",
"completed": 145,
"failed": 8,
"cancelled": 1,
"averageDuration": 2900
},
{
"date": "2025-01-11",
"completed": 162,
"failed": 5,
"cancelled": 0,
"averageDuration": 2750
}
],
"slowestExecutions": [
{
"executionId": "exec_slow1",
"duration": 28500,
"startedAt": "2025-01-14T15:20:00Z"
}
],
"mostCommonErrors": [
{
"error": "Network timeout",
"count": 25,
"percentage": 36.8
},
{
"error": "Invalid response format",
"count": 18,
"percentage": 26.5
}
]
}
}
Deletar Execução
Deleta o registro de uma execução.
DELETE /executions/:id
Path Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
id |
string | ID da execução |
Exemplo de Requisição
curl -X DELETE "https://api.lumina.app.br/v1/executions/exec_abc123" \
-H "Authorization: Bearer lumina_sk_your_api_key"
Resposta de Sucesso (204)
No Content
Deletar Execuções em Lote
Deleta múltiplas execuções de uma vez.
DELETE /executions
Request Body
{
"flowId": "flow_xyz789",
"status": "completed",
"olderThan": "2024-12-31T23:59:59Z"
}
| Campo | Tipo | Descrição |
|---|---|---|
flowId |
string | Filtrar por flow (opcional) |
status |
string | Filtrar por status (opcional) |
olderThan |
string | Deletar apenas execuções mais antigas que esta data |
executionIds |
array | Lista de IDs específicos (opcional) |
Exemplo de Requisição
curl -X DELETE "https://api.lumina.app.br/v1/executions" \
-H "Authorization: Bearer lumina_sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"status": "completed",
"olderThan": "2024-12-31T23:59:59Z"
}'
Resposta de Sucesso (200)
{
"success": true,
"data": {
"deletedCount": 1250,
"status": "Executions deleted successfully"
}
}
Status de Execução
Uma execução pode ter os seguintes status:
| Status | Descrição |
|---|---|
pending |
Aguardando início |
running |
Em execução |
completed |
Concluída com sucesso |
failed |
Falhou com erro |
cancelled |
Cancelada manualmente |
timeout |
Tempo limite excedido |
Exemplos de Uso
Node.js
const axios = require('axios');
const api = axios.create({
baseURL: 'https://api.lumina.app.br/v1',
headers: {
'Authorization': `Bearer ${process.env.LUMINA_API_KEY}`
}
});
// Listar execuções de um flow
async function listFlowExecutions(flowId, status = null) {
const params = { flowId, limit: 50 };
if (status) params.status = status;
const response = await api.get('/executions', { params });
return response.data.data;
}
// Obter detalhes de execução com logs
async function getExecutionDetails(executionId) {
const response = await api.get(`/executions/${executionId}`, {
params: {
includeLogs: true,
includeNodeOutputs: true
}
});
return response.data.data;
}
// Obter logs de execução
async function getExecutionLogs(executionId, level = null) {
const params = level ? { level } : {};
const response = await api.get(`/executions/${executionId}/logs`, { params });
return response.data.data;
}
// Cancelar execução
async function cancelExecution(executionId, reason) {
const response = await api.post(`/executions/${executionId}/cancel`, {
reason
});
return response.data.data;
}
// Reexecutar flow
async function retryExecution(executionId, overrideData = null) {
const body = overrideData ? { overrideData } : {};
const response = await api.post(`/executions/${executionId}/retry`, body);
return response.data.data;
}
// Obter estatísticas
async function getExecutionStats(flowId, days = 7) {
const endDate = new Date();
const startDate = new Date();
startDate.setDate(startDate.getDate() - days);
const response = await api.get('/executions/stats', {
params: {
flowId,
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
groupBy: 'day'
}
});
return response.data.data;
}
// Monitorar execução até conclusão
async function monitorExecution(executionId, pollInterval = 2000) {
return new Promise((resolve, reject) => {
const interval = setInterval(async () => {
try {
const execution = await api.get(`/executions/${executionId}`);
const status = execution.data.data.status;
if (['completed', 'failed', 'cancelled', 'timeout'].includes(status)) {
clearInterval(interval);
resolve(execution.data.data);
}
} catch (error) {
clearInterval(interval);
reject(error);
}
}, pollInterval);
});
}
Python
import requests
import os
import time
from datetime import datetime, timedelta
API_KEY = os.environ.get('LUMINA_API_KEY')
BASE_URL = 'https://api.lumina.app.br/v1'
class ExecutionsAPI:
def __init__(self):
self.headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
def list_executions(self, flow_id=None, status=None, limit=20):
params = {'limit': limit}
if flow_id:
params['flowId'] = flow_id
if status:
params['status'] = status
response = requests.get(
f'{BASE_URL}/executions',
headers=self.headers,
params=params
)
return response.json()['data']
def get_execution(self, execution_id, include_logs=False):
params = {'includeLogs': include_logs, 'includeNodeOutputs': True}
response = requests.get(
f'{BASE_URL}/executions/{execution_id}',
headers=self.headers,
params=params
)
return response.json()['data']
def get_logs(self, execution_id, level=None):
params = {'level': level} if level else {}
response = requests.get(
f'{BASE_URL}/executions/{execution_id}/logs',
headers=self.headers,
params=params
)
return response.json()['data']
def cancel_execution(self, execution_id, reason):
response = requests.post(
f'{BASE_URL}/executions/{execution_id}/cancel',
headers=self.headers,
json={'reason': reason}
)
return response.json()['data']
def retry_execution(self, execution_id, override_data=None):
body = {'overrideData': override_data} if override_data else {}
response = requests.post(
f'{BASE_URL}/executions/{execution_id}/retry',
headers=self.headers,
json=body
)
return response.json()['data']
def get_stats(self, flow_id=None, days=7):
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
params = {
'startDate': start_date.isoformat(),
'endDate': end_date.isoformat(),
'groupBy': 'day'
}
if flow_id:
params['flowId'] = flow_id
response = requests.get(
f'{BASE_URL}/executions/stats',
headers=self.headers,
params=params
)
return response.json()['data']
def monitor_execution(self, execution_id, poll_interval=2):
"""Monitor execution until completion"""
while True:
execution = self.get_execution(execution_id)
status = execution['status']
if status in ['completed', 'failed', 'cancelled', 'timeout']:
return execution
time.sleep(poll_interval)
Webhooks de Execução
Você pode receber notificações em tempo real sobre execuções através de webhooks.
Eventos Disponíveis
execution.started: Execução iniciadaexecution.completed: Execução concluída com sucessoexecution.failed: Execução falhouexecution.cancelled: Execução cancelada
Payload do Webhook
{
"event": "execution.completed",
"timestamp": "2025-01-15T10:30:03Z",
"data": {
"executionId": "exec_abc123",
"flowId": "flow_xyz789",
"flowName": "Processar Pedidos WhatsApp",
"status": "completed",
"duration": 3000,
"output": {...}
}
}