> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gu1.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Listar eventos de usuário

> Consultar eventos de usuários com filtros avançados — para rastreamento de comportamento de usuários e detecção de fraude na gu1, com exemplos para list.

## Visão Geral

Recupera eventos de usuários com recursos poderosos de filtragem. Use este endpoint para consultar eventos por usuário, entidade, tipo de evento, intervalo de datas e muito mais. Perfeito para construir trilhas de auditoria, ferramentas de investigação de fraude e dashboards de análise.

<Note>
  **Lógica OU para IDs de Entidade**: Ao consultar por identificadores de entidade (`entity_id`, `entity_external_id`, `tax_id`), o sistema usa lógica OU, retornando eventos que correspondam a qualquer um dos identificadores fornecidos.
</Note>

## Endpoint

```
GET https://api.gu1.ai/events/user
```

## Autenticação

Requer uma chave de API válida no cabeçalho Authorization:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Parâmetros de Consulta

<ParamField query="user_id" type="string">
  Filtrar eventos por identificador de usuário

  Exemplo: `?user_id=user_12345`
</ParamField>

<ParamField query="entity_id" type="string">
  Filtrar eventos por UUID de entidade

  Exemplo: `?entity_id=550e8400-e29b-41d4-a716-446655440000`
</ParamField>

<ParamField query="entity_external_id" type="string">
  Filtrar eventos por identificador externo de entidade

  Exemplo: `?entity_external_id=user_12345`
</ParamField>

<ParamField query="tax_id" type="string">
  Filtrar eventos por número de identificação fiscal

  Exemplo: `?tax_id=20242455496`
</ParamField>

<ParamField query="event_type" type="string">
  Filtrar eventos por tipo (ex: LOGIN\_SUCCESS, TRANSFER\_SUCCESS)

  Exemplo: `?event_type=LOGIN_SUCCESS`
</ParamField>

<ParamField query="start_date" type="string">
  Filtrar eventos após esta data (formato ISO 8601)

  Exemplo: `?start_date=2026-01-01T00:00:00Z`
</ParamField>

<ParamField query="end_date" type="string">
  Filtrar eventos antes desta data (formato ISO 8601)

  Exemplo: `?end_date=2026-01-31T23:59:59Z`
</ParamField>

<ParamField query="limit" type="number" default="100">
  Número máximo de eventos a retornar por página (máx: 1000)

  Exemplo: `?limit=50`
</ParamField>

<ParamField query="offset" type="number" default="0">
  Número de eventos a pular para paginação

  Exemplo: `?offset=100`
</ParamField>

## Resposta

<ResponseField name="success" type="boolean">
  Indica se a requisição foi bem-sucedida
</ResponseField>

<ResponseField name="events" type="array">
  Array de objetos de eventos ordenados por timestamp (mais recente primeiro)

  <ResponseField name="events[].id" type="string">
    UUID do evento
  </ResponseField>

  <ResponseField name="events[].eventType" type="string">
    Tipo de evento
  </ResponseField>

  <ResponseField name="events[].userId" type="string">
    Identificador do usuário
  </ResponseField>

  <ResponseField name="events[].entityId" type="string">
    UUID da entidade
  </ResponseField>

  <ResponseField name="events[].entityExternalId" type="string">
    Identificador externo da entidade
  </ResponseField>

  <ResponseField name="events[].taxId" type="string">
    ID fiscal
  </ResponseField>

  <ResponseField name="events[].timestamp" type="string">
    Timestamp do evento (ISO 8601)
  </ResponseField>

  <ResponseField name="events[].deviceId" type="string">
    Identificador do dispositivo
  </ResponseField>

  <ResponseField name="events[].ipAddress" type="string">
    Endereço IP
  </ResponseField>

  <ResponseField name="events[].country" type="string">
    Código do país
  </ResponseField>

  <ResponseField name="events[].isVpn" type="boolean">
    Flag de detecção de VPN
  </ResponseField>

  <ResponseField name="events[].isProxy" type="boolean">
    Flag de detecção de proxy
  </ResponseField>

  <ResponseField name="events[].metadata" type="object">
    Metadados específicos do evento
  </ResponseField>

  <ResponseField name="events[].createdAt" type="string">
    Timestamp de criação do registro
  </ResponseField>
</ResponseField>

<ResponseField name="pagination" type="object">
  Informações de paginação

  <ResponseField name="pagination.total" type="number">
    Número total de eventos correspondentes aos filtros
  </ResponseField>

  <ResponseField name="pagination.limit" type="number">
    Tamanho de página usado
  </ResponseField>

  <ResponseField name="pagination.offset" type="number">
    Offset usado
  </ResponseField>

  <ResponseField name="pagination.hasMore" type="boolean">
    Se há mais páginas disponíveis
  </ResponseField>
</ResponseField>

## Exemplos

### Consulta Básica

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.gu1.ai/events/user?entity_external_id=user_12345" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'https://api.gu1.ai/events/user?entity_external_id=user_12345',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  console.log(data.events);
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'https://api.gu1.ai/events/user',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={'entity_external_id': 'user_12345'}
  )

  data = response.json()
  print(data['events'])
  ```
</CodeGroup>

### Filtrar por Tipo de Evento

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.gu1.ai/events/user?entity_external_id=user_12345&event_type=LOGIN_SUCCESS" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'https://api.gu1.ai/events/user?entity_external_id=user_12345&event_type=LOGIN_SUCCESS',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'https://api.gu1.ai/events/user',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={
          'entity_external_id': 'user_12345',
          'event_type': 'LOGIN_SUCCESS'
      }
  )
  ```
</CodeGroup>

### Filtrar por Intervalo de Datas

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.gu1.ai/events/user?entity_external_id=user_12345&start_date=2026-01-01T00:00:00Z&end_date=2026-01-31T23:59:59Z" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const startDate = new Date('2026-01-01').toISOString();
  const endDate = new Date('2026-01-31').toISOString();

  const response = await fetch(
    `https://api.gu1.ai/events/user?entity_external_id=user_12345&start_date=${startDate}&end_date=${endDate}`,
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );
  ```

  ```python Python theme={null}
  from datetime import datetime
  import requests

  start_date = datetime(2026, 1, 1).isoformat() + 'Z'
  end_date = datetime(2026, 1, 31, 23, 59, 59).isoformat() + 'Z'

  response = requests.get(
      'https://api.gu1.ai/events/user',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={
          'entity_external_id': 'user_12345',
          'start_date': start_date,
          'end_date': end_date
      }
  )
  ```
</CodeGroup>

## Exemplo de Resposta

```json theme={null}
{
  "success": true,
  "events": [
    {
      "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "eventType": "LOGIN_SUCCESS",
      "userId": "user_12345",
      "entityId": "550e8400-e29b-41d4-a716-446655440000",
      "entityExternalId": "user_12345",
      "taxId": "20242455496",
      "timestamp": "2026-01-30T14:30:00Z",
      "deviceId": "840e89e4d46efd67",
      "ipAddress": "10.40.64.231",
      "country": "AR",
      "isVpn": false,
      "isProxy": false,
      "metadata": {},
      "createdAt": "2026-01-30T14:30:00Z"
    },
    {
      "id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
      "eventType": "TRANSFER_SUCCESS",
      "userId": "user_12345",
      "entityId": "550e8400-e29b-41d4-a716-446655440000",
      "entityExternalId": "user_12345",
      "taxId": "20242455496",
      "timestamp": "2026-01-30T12:15:00Z",
      "deviceId": "840e89e4d46efd67",
      "ipAddress": "10.40.64.231",
      "country": "AR",
      "metadata": {
        "amount": 5000,
        "currency": "ARS",
        "destinationAccountId": "0170042640000004234411"
      },
      "createdAt": "2026-01-30T12:15:00Z"
    }
  ],
  "pagination": {
    "total": 145,
    "limit": 100,
    "offset": 0,
    "hasMore": true
  }
}
```

## Respostas de Erro

### 400 Bad Request

```json theme={null}
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid date format"
  }
}
```

### 401 Unauthorized

```json theme={null}
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing API key"
  }
}
```

### 403 Forbidden

```json theme={null}
{
  "success": false,
  "error": {
    "code": "FORBIDDEN",
    "message": "Insufficient permissions to read events"
  }
}
```

### 500 Internal Server Error

```json theme={null}
{
  "success": false,
  "error": {
    "code": "EVENTS_FETCH_FAILED",
    "message": "Failed to fetch events"
  }
}
```

## Casos de Uso

### Trilha de Auditoria

Construa uma trilha de auditoria completa para conformidade:

```javascript theme={null}
async function getAuditTrail(entityExternalId, startDate, endDate) {
  const response = await fetch(
    `https://api.gu1.ai/events/user?` +
    `entity_external_id=${entityExternalId}&` +
    `start_date=${startDate}&` +
    `end_date=${endDate}&` +
    `limit=1000`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();
  return data.events.map(event => ({
    timestamp: event.timestamp,
    action: event.eventType,
    user: event.userId,
    device: event.deviceId,
    ipAddress: event.ipAddress
  }));
}
```

### Investigação de Fraude

Investigue atividade suspeita:

```javascript theme={null}
async function investigateSuspiciousActivity(entityExternalId) {
  // Obter logins falhos recentes
  const failedLogins = await fetch(
    `https://api.gu1.ai/events/user?` +
    `entity_external_id=${entityExternalId}&` +
    `event_type=LOGIN_FAILED&` +
    `start_date=${new Date(Date.now() - 86400000).toISOString()}`, // Última hora
    { headers: { 'Authorization': `Bearer ${API_KEY}` } }
  );

  // Obter transferências recentes
  const transfers = await fetch(
    `https://api.gu1.ai/events/user?` +
    `entity_external_id=${entityExternalId}&` +
    `event_type=TRANSFER_SUCCESS&` +
    `start_date=${new Date(Date.now() - 86400000).toISOString()}`,
    { headers: { 'Authorization': `Bearer ${API_KEY}` } }
  );

  return {
    failedLogins: (await failedLogins.json()).events,
    transfers: (await transfers.json()).events
  };
}
```

### Linha do Tempo do Usuário

Construa uma linha do tempo de atividade do usuário:

```javascript theme={null}
async function getUserTimeline(userId, limit = 50) {
  const response = await fetch(
    `https://api.gu1.ai/events/user?user_id=${userId}&limit=${limit}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();
  return data.events;
}
```

## Dicas de Filtragem

### Múltiplos Identificadores de Entidade

Você pode fornecer múltiplos identificadores de entidade para lançar uma rede mais ampla:

```javascript theme={null}
// Retornará eventos correspondentes a QUALQUER um desses identificadores
const response = await fetch(
  `https://api.gu1.ai/events/user?` +
  `entity_external_id=user_12345&` +
  `tax_id=20242455496`,
  { headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
```

### Combinando Filtros

Combine múltiplos filtros para consultas precisas:

```javascript theme={null}
// Obter transferências falhas na última semana
const lastWeek = new Date(Date.now() - 7 * 86400000).toISOString();

const response = await fetch(
  `https://api.gu1.ai/events/user?` +
  `entity_external_id=user_12345&` +
  `event_type=TRANSFER_FAILED&` +
  `start_date=${lastWeek}`,
  { headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
```

## Melhores Práticas de Paginação

### Iterar Através de Todas as Páginas

```javascript theme={null}
async function getAllEvents(entityExternalId) {
  const allEvents = [];
  let offset = 0;
  const limit = 100;
  let hasMore = true;

  while (hasMore) {
    const response = await fetch(
      `https://api.gu1.ai/events/user?` +
      `entity_external_id=${entityExternalId}&` +
      `limit=${limit}&offset=${offset}`,
      { headers: { 'Authorization': `Bearer ${API_KEY}` } }
    );

    const data = await response.json();
    allEvents.push(...data.events);

    hasMore = data.pagination.hasMore;
    offset += limit;
  }

  return allEvents;
}
```

## Próximos Passos

<CardGroup cols={2}>
  <Card title="Criar Evento" icon="plus" href="/pt/api-reference/events/create">
    Rastrear novos eventos
  </Card>

  <Card title="Estatísticas de Eventos" icon="chart-bar" href="/pt/api-reference/events/stats">
    Obter estatísticas agregadas
  </Card>

  <Card title="Listar por Entidade" icon="user" href="/pt/api-reference/events/list-by-entity">
    Obter eventos para uma entidade específica
  </Card>

  <Card title="Detecção de Fraude" icon="shield-check" href="/pt/use-cases/transaction-monitoring/fraud-detection">
    Construa regras de fraude com eventos
  </Card>
</CardGroup>
