Estatísticas
curl --request GET \
--url http://api.gu1.ai/events/user/stats \
--header 'Authorization: Bearer <token>'import requests
url = "http://api.gu1.ai/events/user/stats"
headers = {"Authorization": "Bearer <token>"}
response = requests.get(url, headers=headers)
print(response.text)const options = {method: 'GET', headers: {Authorization: 'Bearer <token>'}};
fetch('http://api.gu1.ai/events/user/stats', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/events/user/stats",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/events/user/stats"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("http://api.gu1.ai/events/user/stats")
.header("Authorization", "Bearer <token>")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/events/user/stats")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(url)
request["Authorization"] = 'Bearer <token>'
response = http.request(request)
puts response.read_body{
"success": true,
"stats": [
{
"stats[].event_type": "<string>",
"stats[].count": 123,
"stats[].last_occurrence": "<string>"
}
]
}Referência API
Estatísticas
Obter estatísticas agregadas de eventos por tipo — para rastreamento de comportamento de usuários e detecção de fraude na gu1, com exemplos para stats.
GET
/
events
/
user
/
stats
Estatísticas
curl --request GET \
--url http://api.gu1.ai/events/user/stats \
--header 'Authorization: Bearer <token>'import requests
url = "http://api.gu1.ai/events/user/stats"
headers = {"Authorization": "Bearer <token>"}
response = requests.get(url, headers=headers)
print(response.text)const options = {method: 'GET', headers: {Authorization: 'Bearer <token>'}};
fetch('http://api.gu1.ai/events/user/stats', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/events/user/stats",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/events/user/stats"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("http://api.gu1.ai/events/user/stats")
.header("Authorization", "Bearer <token>")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/events/user/stats")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(url)
request["Authorization"] = 'Bearer <token>'
response = http.request(request)
puts response.read_body{
"success": true,
"stats": [
{
"stats[].event_type": "<string>",
"stats[].count": 123,
"stats[].last_occurrence": "<string>"
}
]
}Visão Geral
Recupera estatísticas agregadas sobre eventos de usuários, agrupadas por tipo de evento. Este endpoint fornece uma visão rápida da distribuição de eventos, contagens e timestamps da última ocorrência, perfeito para construir dashboards e monitorar padrões de atividade do usuário.Endpoint
GET https://api.gu1.ai/events/user/stats
Autenticação
Requer uma chave de API válida no cabeçalho Authorization:Authorization: Bearer YOUR_API_KEY
Parâmetros de Consulta
string
Filtrar estatísticas por identificador de usuário. Se não fornecido, retorna estatísticas de todos os usuários em sua organização.Exemplo:
?user_id=user_12345Resposta
boolean
Indica se a requisição foi bem-sucedida
array
Exemplos
Obter Estatísticas para Todos os Usuários
curl https://api.gu1.ai/events/user/stats \
-H "Authorization: Bearer YOUR_API_KEY"
const response = await fetch('https://api.gu1.ai/events/user/stats', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(data.stats);
import requests
response = requests.get(
'https://api.gu1.ai/events/user/stats',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(data['stats'])
Obter Estatísticas para Usuário Específico
curl "https://api.gu1.ai/events/user/stats?user_id=user_12345" \
-H "Authorization: Bearer YOUR_API_KEY"
const response = await fetch(
'https://api.gu1.ai/events/user/stats?user_id=user_12345',
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const data = await response.json();
console.log(data.stats);
import requests
response = requests.get(
'https://api.gu1.ai/events/user/stats',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
params={'user_id': 'user_12345'}
)
data = response.json()
print(data['stats'])
Exemplo de Resposta
{
"success": true,
"stats": [
{
"event_type": "LOGIN_SUCCESS",
"count": 45,
"last_occurrence": "2026-01-30T14:30:00Z"
},
{
"event_type": "LOGIN_FAILED",
"count": 3,
"last_occurrence": "2026-01-30T08:15:00Z"
},
{
"event_type": "TRANSFER_SUCCESS",
"count": 12,
"last_occurrence": "2026-01-30T12:00:00Z"
},
{
"event_type": "PROFILE_UPDATED",
"count": 2,
"last_occurrence": "2026-01-25T10:30:00Z"
},
{
"event_type": "PASSWORD_CHANGE",
"count": 1,
"last_occurrence": "2026-01-20T16:45:00Z"
}
]
}
Respostas de Erro
401 Unauthorized
{
"success": false,
"error": {
"code": "UNAUTHORIZED",
"message": "Invalid or missing API key"
}
}
403 Forbidden
{
"success": false,
"error": {
"code": "FORBIDDEN",
"message": "Insufficient permissions to read events"
}
}
500 Internal Server Error
{
"success": false,
"error": {
"code": "STATS_FETCH_FAILED",
"message": "Failed to fetch event statistics"
}
}
Casos de Uso
Resumo do Dashboard
Construa um dashboard mostrando a distribuição de eventos:async function buildEventDashboard(userId) {
const response = await fetch(
`https://api.gu1.ai/events/user/stats?user_id=${userId}`,
{
headers: { 'Authorization': `Bearer ${API_KEY}` }
}
);
const data = await response.json();
// Agrupar por categoria
const authEvents = data.stats.filter(s =>
['LOGIN_SUCCESS', 'LOGIN_FAILED', 'LOGOUT'].includes(s.event_type)
);
const transferEvents = data.stats.filter(s =>
['TRANSFER_SUCCESS', 'TRANSFER_FAILED'].includes(s.event_type)
);
return {
authentication: {
total: authEvents.reduce((sum, e) => sum + e.count, 0),
events: authEvents
},
transfers: {
total: transferEvents.reduce((sum, e) => sum + e.count, 0),
events: transferEvents
}
};
}
Monitoramento de Fraude
Monitore padrões de atividade suspeita:async function detectSuspiciousActivity(userId) {
const response = await fetch(
`https://api.gu1.ai/events/user/stats?user_id=${userId}`,
{
headers: { 'Authorization': `Bearer ${API_KEY}` }
}
);
const data = await response.json();
const alerts = [];
// Verificar tentativas de login falhas
const failedLogins = data.stats.find(s => s.event_type === 'LOGIN_FAILED');
if (failedLogins && failedLogins.count > 5) {
alerts.push({
type: 'HIGH_FAILED_LOGINS',
count: failedLogins.count,
lastOccurrence: failedLogins.last_occurrence
});
}
// Verificar atividade de transferência
const transfers = data.stats.find(s => s.event_type === 'TRANSFER_SUCCESS');
if (transfers && transfers.count > 10) {
alerts.push({
type: 'HIGH_TRANSFER_VOLUME',
count: transfers.count,
lastOccurrence: transfers.last_occurrence
});
}
return alerts;
}
Relatório de Atividade do Usuário
Gerar relatórios de atividade:async function generateActivityReport(userId) {
const response = await fetch(
`https://api.gu1.ai/events/user/stats?user_id=${userId}`,
{
headers: { 'Authorization': `Bearer ${API_KEY}` }
}
);
const data = await response.json();
const report = {
userId,
generatedAt: new Date().toISOString(),
totalEvents: data.stats.reduce((sum, s) => sum + s.count, 0),
eventsByType: data.stats.map(s => ({
type: s.event_type,
count: s.count,
lastActivity: s.last_occurrence
})),
mostRecentActivity: data.stats.reduce((latest, s) =>
new Date(s.last_occurrence) > new Date(latest.last_occurrence)
? s
: latest
)
};
return report;
}
Métricas de Análise
Calcular métricas principais:async function calculateMetrics(userId) {
const response = await fetch(
`https://api.gu1.ai/events/user/stats?user_id=${userId}`,
{
headers: { 'Authorization': `Bearer ${API_KEY}` }
}
);
const data = await response.json();
// Calcular taxas de sucesso
const loginSuccess = data.stats.find(s => s.event_type === 'LOGIN_SUCCESS')?.count || 0;
const loginFailed = data.stats.find(s => s.event_type === 'LOGIN_FAILED')?.count || 0;
const loginSuccessRate = loginSuccess / (loginSuccess + loginFailed) * 100;
const transferSuccess = data.stats.find(s => s.event_type === 'TRANSFER_SUCCESS')?.count || 0;
const transferFailed = data.stats.find(s => s.event_type === 'TRANSFER_FAILED')?.count || 0;
const transferSuccessRate = transferSuccess / (transferSuccess + transferFailed) * 100;
return {
loginSuccessRate: loginSuccessRate.toFixed(2) + '%',
transferSuccessRate: transferSuccessRate.toFixed(2) + '%',
totalLogins: loginSuccess + loginFailed,
totalTransfers: transferSuccess + transferFailed
};
}
Análise Comparativa
Comparar atividade entre usuários:async function compareUsers(userIds) {
const userStats = await Promise.all(
userIds.map(async userId => {
const response = await fetch(
`https://api.gu1.ai/events/user/stats?user_id=${userId}`,
{
headers: { 'Authorization': `Bearer ${API_KEY}` }
}
);
const data = await response.json();
return {
userId,
totalEvents: data.stats.reduce((sum, s) => sum + s.count, 0),
stats: data.stats
};
})
);
// Ordenar por atividade total
return userStats.sort((a, b) => b.totalEvents - a.totalEvents);
}
Exemplos de Visualização
Preparação de Dados para Gráficos
Preparar dados para gráficos:async function prepareChartData(userId) {
const response = await fetch(
`https://api.gu1.ai/events/user/stats?user_id=${userId}`,
{
headers: { 'Authorization': `Bearer ${API_KEY}` }
}
);
const data = await response.json();
// Para gráfico de pizza
const pieData = data.stats.map(s => ({
name: s.event_type,
value: s.count
}));
// Para gráfico de barras
const barData = data.stats.map(s => ({
category: s.event_type,
count: s.count
}));
return { pieData, barData };
}
Próximos Passos
Listar Eventos
Consultar eventos individuais
Criar Evento
Rastrear novos eventos
Listar por Entidade
Obter eventos para entidade específica
Análises
Construir dashboards de análise
Was this page helpful?