> ## 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 entidades (pessoas e empresas)

> Consultar e filtrar pessoas ou empresas em sua organização — no modelo universal de entidades gu1 para KYC, KYB e análise de risco.

## Visão Geral

Recupera uma lista de entidades com filtragem opcional por tipo, país, identificação fiscal ou ID externo. Retorna até 100 entidades por solicitação.

## Endpoint

```
GET http://api.gu1.ai/entities
```

## Autenticação

Requer uma chave de API válida no cabeçalho de autorização:

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

## Parâmetros de Consulta

<ParamField query="type" type="string">
  Filtrar por tipo de entidade. Valores disponíveis:

  * `person`
  * `company`
</ParamField>

<ParamField query="country" type="string">
  Filtrar por código de país ISO 3166-1 alfa-2 (ex: "US", "BR", "AR")
</ParamField>

<ParamField query="taxId" type="string">
  Filtrar por número de identificação fiscal exato
</ParamField>

<ParamField query="externalId" type="string">
  Filtrar por seu identificador externo
</ParamField>

## Resposta

<ResponseField name="entities" type="array">
  Array de objetos de entidade, cada um contendo:

  * `id` - ID interno do gu1
  * `externalId` - Seu ID externo
  * `organizationId` - ID da sua organização
  * `type` - Tipo de entidade
  * `name` - Nome da entidade
  * `taxId` - Identificação fiscal
  * `countryCode` - Código do país
  * `nationality` - Nacionalidade (ISO 3166-1 alpha-2 na raiz, ou `null`)
  * `riskScore` - Pontuação de risco (0-100)
  * `riskFactors` - Array de fatores de risco
  * `status` - Status da entidade
  * `kycVerified` - Status de verificação KYC
  * `kycProvider` - Nome do provedor KYC
  * `kycData` - Dados de verificação KYC
  * `entityData` - Dados específicos do tipo
  * `attributes` - Atributos personalizados
  * `createdAt` - Timestamp de criação
  * `updatedAt` - Timestamp da última atualização
  * `deletedAt` - Timestamp de exclusão (null se ativo)
</ResponseField>

## Exemplos

### Listar Todas as Entidades

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/entities" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://api.gu1.ai/entities', {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY'
    }
  });

  const data = await response.json();
  console.log(`Found ${data.entities.length} entities`);
  ```

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

  response = requests.get(
      'http://api.gu1.ai/entities',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY'
      }
  )

  data = response.json()
  print(f"Found {len(data['entities'])} entities")
  ```
</CodeGroup>

### Filtrar por Tipo de Entidade

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/entities?type=company" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities?type=company',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  const companies = data.entities;
  console.log(`Found ${companies.length} companies`);
  ```

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

  response = requests.get(
      'http://api.gu1.ai/entities',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={'type': 'company'}
  )

  companies = response.json()['entities']
  print(f"Found {len(companies)} companies")
  ```
</CodeGroup>

### Filtrar por País

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/entities?country=BR&type=company" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities?country=BR&type=company',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  console.log(`Found ${data.entities.length} Brazilian companies`);
  ```

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

  response = requests.get(
      'http://api.gu1.ai/entities',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={
          'country': 'BR',
          'type': 'company'
      }
  )

  brazilian_companies = response.json()['entities']
  print(f"Found {len(brazilian_companies)} Brazilian companies")
  ```
</CodeGroup>

### Buscar por ID Externo

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/entities?externalId=customer_12345" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities?externalId=customer_12345',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  const entity = data.entities[0]; // External IDs should be unique
  console.log('Found entity:', entity.name);
  ```

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

  response = requests.get(
      'http://api.gu1.ai/entities',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={'externalId': 'customer_12345'}
  )

  entities = response.json()['entities']
  if entities:
      print(f"Found entity: {entities[0]['name']}")
  ```
</CodeGroup>

### Buscar por Identificação Fiscal

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/entities?taxId=20-12345678-9" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities?taxId=20-12345678-9',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  if (data.entities.length > 0) {
    console.log('Entity found:', data.entities[0].name);
  }
  ```

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

  response = requests.get(
      'http://api.gu1.ai/entities',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={'taxId': '20-12345678-9'}
  )

  entities = response.json()['entities']
  if entities:
      print(f"Entity found: {entities[0]['name']}")
  ```
</CodeGroup>

## Exemplo de Resposta

```json theme={null}
{
  "entities": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "externalId": "customer_12345",
      "organizationId": "8e2f89ab-c216-4eb4-90eb-ca5d44499aaa",
      "type": "person",
      "name": "María González",
      "taxId": "20-12345678-9",
      "countryCode": "AR",
      "nationality": "AR",
      "riskScore": 25,
      "riskFactors": [
        {
          "factor": "new_customer",
          "impact": 15,
          "description": "Customer registered within last 30 days"
        }
      ],
      "status": "active",
      "kycVerified": true,
      "kycProvider": "gueno_ai",
      "kycData": {
        "verificationDate": "2024-10-03T14:30:00Z",
        "overallStatus": "approved"
      },
      "entityData": {
        "person": {
          "firstName": "María",
          "lastName": "González",
          "dateOfBirth": "1985-03-15",
          "nationality": "AR",
          "occupation": "Software Engineer",
          "income": 85000
        }
      },
      "attributes": {
        "email": "maria.gonzalez@example.com",
        "phone": "+54 11 1234-5678"
      },
      "createdAt": "2024-10-03T14:30:00.000Z",
      "updatedAt": "2024-10-03T14:35:00.000Z",
      "deletedAt": null
    },
    {
      "id": "660e9511-f39c-52e5-b827-557766551111",
      "externalId": "company_789",
      "organizationId": "8e2f89ab-c216-4eb4-90eb-ca5d44499aaa",
      "type": "company",
      "name": "Tech Solutions S.A.",
      "taxId": "12.345.678/0001-90",
      "countryCode": "BR",
      "nationality": "BR",
      "riskScore": 35,
      "riskFactors": [
        {
          "factor": "new_business",
          "impact": 20,
          "description": "Company incorporated less than 2 years ago"
        }
      ],
      "status": "active",
      "kycVerified": true,
      "kycProvider": "gueno_ai",
      "kycData": {
        "verificationDate": "2024-10-03T15:00:00Z",
        "overallStatus": "approved"
      },
      "entityData": {
        "company": {
          "legalName": "Tech Solutions Sociedade Anônima",
          "tradeName": "Tech Solutions",
          "incorporationDate": "2020-06-15",
          "industry": "Software Development",
          "employeeCount": 50,
          "revenue": 5000000
        }
      },
      "attributes": {
        "website": "https://techsolutions.com.br",
        "registeredAddress": "Av. Paulista, 1000, São Paulo"
      },
      "createdAt": "2024-10-03T15:00:00.000Z",
      "updatedAt": "2024-10-03T15:05:00.000Z",
      "deletedAt": null
    }
  ]
}
```

## Casos de Uso

### Monitoramento de Entidades de Alto Risco

Consulte todas as entidades e filtre por pontuação de risco em sua aplicação:

```javascript theme={null}
const response = await fetch('http://api.gu1.ai/entities', {
  headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
});

const data = await response.json();
const highRiskEntities = data.entities.filter(e => e.riskScore > 70);

console.log(`Found ${highRiskEntities.length} high-risk entities requiring review`);
highRiskEntities.forEach(entity => {
  console.log(`- ${entity.name} (Risk: ${entity.riskScore})`);
});
```

### Painel de Conformidade KYC

Obtenha todas as entidades não verificadas para o painel de conformidade:

```python theme={null}
import requests

response = requests.get(
    'http://api.gu1.ai/entities',
    headers={'Authorization': 'Bearer YOUR_API_KEY'},
    params={'type': 'person'}
)

entities = response.json()['entities']
unverified = [e for e in entities if not e['kycVerified']]

print(f"Unverified customers: {len(unverified)}")
for entity in unverified:
    print(f"- {entity['name']} ({entity['externalId']})")
```

### Análise de Volume de Transações

Liste todas as transações para um período específico (combine com filtragem de data em sua aplicação):

```javascript theme={null}
const response = await fetch(
  'http://api.gu1.ai/entities?type=transaction',
  {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  }
);

const data = await response.json();
const transactions = data.entities;

const totalVolume = transactions.reduce((sum, txn) => {
  return sum + (txn.entityData?.transaction?.amount || 0);
}, 0);

console.log(`Total transaction volume: $${totalVolume.toLocaleString()}`);
console.log(`Transaction count: ${transactions.length}`);
```

### Conformidade Específica por País

Obtenha todas as entidades de um país específico para relatórios regulatórios:

```python theme={null}
import requests

response = requests.get(
    'http://api.gu1.ai/entities',
    headers={'Authorization': 'Bearer YOUR_API_KEY'},
    params={'country': 'US'}
)

us_entities = response.json()['entities']

# Separate by type
companies = [e for e in us_entities if e['type'] == 'company']
persons = [e for e in us_entities if e['type'] == 'person']

print(f"US Companies: {len(companies)}")
print(f"US Persons: {len(persons)}")
```

## Paginação

A API atualmente retorna até 100 entidades por solicitação. Se você tiver mais de 100 entidades e precisar de paginação:

1. **Use filtros específicos** para restringir os resultados (tipo, país, etc.)
2. **Implemente paginação no lado do cliente** armazenando o último timestamp de `createdAt`
3. **Entre em contato com o suporte** para recursos de paginação empresarial

Exemplo com paginação baseada em timestamp:

```javascript theme={null}
let allEntities = [];
let lastCreatedAt = null;

async function fetchAllEntities() {
  const response = await fetch('http://api.gu1.ai/entities?type=company', {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });

  const data = await response.json();

  // Filter by last timestamp if this is not the first batch
  const newEntities = lastCreatedAt
    ? data.entities.filter(e => new Date(e.createdAt) > new Date(lastCreatedAt))
    : data.entities;

  allEntities = allEntities.concat(newEntities);

  if (newEntities.length > 0) {
    lastCreatedAt = newEntities[newEntities.length - 1].createdAt;
  }

  return allEntities;
}
```

## Respostas de Erro

### 401 Unauthorized

```json theme={null}
{
  "error": "Invalid or missing API key"
}
```

### 500 Internal Server Error

```json theme={null}
{
  "error": "Failed to search entities"
}
```

## Limites

* **Máximo de resultados por solicitação**: 100 entidades
* **Parâmetros de consulta**: Podem ser combinados para filtragem avançada
* **Limites de taxa**: Aplicam-se com base no nível do seu plano

## Próximos Passos

* [Obter Detalhes da Entidade](/api-reference/entities/get) - Recuperar informações completas de uma entidade específica
* [Criar Entidade](/api-reference/entities/create) - Adicionar novas entidades à sua organização
* [Atualizar Entidade](/api-reference/entities/update) - Modificar atributos da entidade
* [Operações em Lote](/pt/api-reference/entities/upsert) - Processar múltiplas entidades de uma vez
