> ## 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 por Entidade

> Lista todos os eventos de usuário associados a uma entidade específica na API gu1 — útil para auditorias, depuração de regras e linhas do tempo.

## Visão Geral

Recupera todos os eventos associados a uma entidade específica, fornecendo uma linha do tempo completa de atividades. Este endpoint pesquisa entre múltiplos identificadores de entidade (`entity_id`, `entity_external_id`, `tax_id`) para garantir que você obtenha todos os eventos relacionados à entidade, independentemente de qual identificador foi usado ao criar os eventos.

<Tip>
  📋 Este endpoint pesquisa automaticamente por ID de entidade, ID externo e ID fiscal, então você obterá todos os eventos independentemente de qual identificador foi usado quando foram criados.
</Tip>

<Tip>
  Para apenas saber se há eventos (sim/não), use [Tem eventos?](/pt/api-reference/events/has-events-by-entity) (`GET …/has-events`) em vez de listar com `limit=1`.
</Tip>

## Endpoint

```
GET https://api.gu1.ai/events/user/entity/{entityId}
```

## Autenticação

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

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

## Parâmetros de Caminho

<ParamField path="entityId" type="string" required>
  UUID da entidade cujos eventos você deseja recuperar
</ParamField>

## Parâmetros de Consulta

<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[].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[].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 para esta entidade
  </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>

<ResponseField name="entity" type="object">
  Informações da entidade

  <ResponseField name="entity.id" type="string">
    UUID da entidade
  </ResponseField>

  <ResponseField name="entity.external_id" type="string">
    Identificador externo da entidade
  </ResponseField>

  <ResponseField name="entity.tax_id" type="string">
    ID fiscal
  </ResponseField>

  <ResponseField name="entity.name" type="string">
    Nome da entidade
  </ResponseField>

  <ResponseField name="entity.type" type="string">
    Tipo de entidade (person, company, etc.)
  </ResponseField>
</ResponseField>

## Exemplos

### Consulta Básica

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.gu1.ai/events/user/entity/550e8400-e29b-41d4-a716-446655440000 \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const entityId = '550e8400-e29b-41d4-a716-446655440000';

  const response = await fetch(
    `https://api.gu1.ai/events/user/entity/${entityId}`,
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

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

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

  entity_id = '550e8400-e29b-41d4-a716-446655440000'

  response = requests.get(
      f'https://api.gu1.ai/events/user/entity/{entity_id}',
      headers={'Authorization': 'Bearer YOUR_API_KEY'}
  )

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

### Com Paginação

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.gu1.ai/events/user/entity/550e8400-e29b-41d4-a716-446655440000?limit=50&offset=0" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const entityId = '550e8400-e29b-41d4-a716-446655440000';

  const response = await fetch(
    `https://api.gu1.ai/events/user/entity/${entityId}?limit=50&offset=0`,
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  console.log(`Page 1 of ${Math.ceil(data.pagination.total / 50)} pages`);
  ```

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

  entity_id = '550e8400-e29b-41d4-a716-446655440000'

  response = requests.get(
      f'https://api.gu1.ai/events/user/entity/{entity_id}',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={'limit': 50, 'offset': 0}
  )

  data = response.json()
  print(f"Page 1 of {data['pagination']['total'] // 50 + 1} pages")
  ```
</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",
      "timestamp": "2026-01-30T14:30:00Z",
      "deviceId": "840e89e4d46efd67",
      "ipAddress": "10.40.64.231",
      "country": "AR",
      "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",
      "timestamp": "2026-01-30T12:15:00Z",
      "deviceId": "840e89e4d46efd67",
      "ipAddress": "10.40.64.231",
      "country": "AR",
      "metadata": {
        "amount": 5000,
        "currency": "ARS"
      },
      "createdAt": "2026-01-30T12:15:00Z"
    }
  ],
  "pagination": {
    "total": 145,
    "limit": 100,
    "offset": 0,
    "hasMore": true
  },
  "entity": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "external_id": "user_12345",
    "tax_id": "20242455496",
    "name": "John Doe",
    "type": "person"
  }
}
```

## Respostas de Erro

### 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"
  }
}
```

### 404 Not Found

```json theme={null}
{
  "success": false,
  "error": {
    "code": "ENTITY_NOT_FOUND",
    "message": "Entity with ID 550e8400-e29b-41d4-a716-446655440000 not found"
  }
}
```

### 500 Internal Server Error

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

## Casos de Uso

### Trilha de Auditoria da Entidade

Gerar uma trilha de auditoria completa para uma entidade:

```javascript theme={null}
async function getEntityAuditTrail(entityId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/entity/${entityId}?limit=1000`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  const auditTrail = {
    entity: data.entity,
    totalEvents: data.pagination.total,
    events: data.events.map(event => ({
      timestamp: event.timestamp,
      action: event.eventType,
      device: event.deviceId,
      location: `${event.ipAddress} (${event.country})`,
      metadata: event.metadata
    }))
  };

  return auditTrail;
}
```

### Revisão de Conformidade

Revisar atividade da entidade para conformidade:

```javascript theme={null}
async function complianceReview(entityId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/entity/${entityId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  // Verificar bandeiras vermelhas
  const loginAttempts = data.events.filter(e => e.eventType === 'LOGIN_FAILED');
  const transfers = data.events.filter(e => e.eventType === 'TRANSFER_SUCCESS');
  const credentialChanges = data.events.filter(e =>
    ['PASSWORD_CHANGE', 'EMAIL_CHANGE', 'PHONE_CHANGE'].includes(e.eventType)
  );

  return {
    entityInfo: data.entity,
    redFlags: {
      failedLogins: loginAttempts.length,
      totalTransfers: transfers.length,
      credentialChanges: credentialChanges.length
    },
    requiresReview: loginAttempts.length > 5 || credentialChanges.length > 3
  };
}
```

### Visualização da Linha do Tempo da Entidade

Construir uma linha do tempo para visualização:

```javascript theme={null}
async function buildEntityTimeline(entityId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/entity/${entityId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  // Agrupar eventos por data
  const timeline = data.events.reduce((acc, event) => {
    const date = event.timestamp.split('T')[0];
    if (!acc[date]) {
      acc[date] = [];
    }
    acc[date].push({
      time: event.timestamp,
      type: event.eventType,
      details: event.metadata
    });
    return acc;
  }, {});

  return {
    entity: data.entity,
    timeline
  };
}
```

### Avaliação de Risco

Avaliar risco da entidade baseado no histórico de eventos:

```javascript theme={null}
async function assessEntityRisk(entityId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/entity/${entityId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  let riskScore = 0;
  const riskFactors = [];

  // Verificar logins falhos
  const failedLogins = data.events.filter(e => e.eventType === 'LOGIN_FAILED').length;
  if (failedLogins > 3) {
    riskScore += 20;
    riskFactors.push(`${failedLogins} tentativas de login falhas`);
  }

  // Verificar uso de VPN
  const vpnEvents = data.events.filter(e => e.metadata?.isVpn).length;
  if (vpnEvents > 5) {
    riskScore += 15;
    riskFactors.push(`${vpnEvents} eventos através de VPN`);
  }

  // Verificar transferências rápidas
  const transfers = data.events.filter(e => e.eventType === 'TRANSFER_SUCCESS');
  const recentTransfers = transfers.filter(e =>
    new Date(e.timestamp) > new Date(Date.now() - 86400000)
  );
  if (recentTransfers.length > 5) {
    riskScore += 25;
    riskFactors.push(`${recentTransfers.length} transferências nas últimas 24 horas`);
  }

  return {
    entity: data.entity,
    riskScore: Math.min(riskScore, 100),
    riskLevel: riskScore > 50 ? 'HIGH' : riskScore > 25 ? 'MEDIUM' : 'LOW',
    riskFactors
  };
}
```

## Melhores Práticas de Paginação

### Carregar Todos os Eventos

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

  while (hasMore) {
    const response = await fetch(
      `https://api.gu1.ai/events/user/entity/${entityId}?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 {
    entity: data.entity,
    events: 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="Listar Eventos" icon="list" href="/pt/api-reference/events/list">
    Consultar eventos com filtros
  </Card>

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

  <Card title="Análise de Risco" icon="shield-check" href="/pt/use-cases/transaction-monitoring/overview">
    Analisar risco da entidade
  </Card>
</CardGroup>
