> ## 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 (personas y empresas)

> Consulta y filtra personas o empresas en tu organización — en el modelo universal de entidades gu1 para KYC, KYB y análisis de riesgo.

## Descripción general

Recupera una lista de entidades con filtrado opcional por tipo, país, identificación fiscal o ID externo. Devuelve hasta 100 entidades por solicitud.

## Endpoint

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

## Autenticación

Requiere una clave API válida en el encabezado de autorización:

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

## Parámetros de consulta

<ParamField query="type" type="string">
  Filtrar por tipo de entidad. Valores disponibles:

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

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

<ParamField query="taxId" type="string">
  Filtrar por número de identificación fiscal exacto
</ParamField>

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

## Respuesta

<ResponseField name="entities" type="array">
  Array de objetos de entidad, cada uno contiene:

  * `id` - ID interno de gu1
  * `externalId` - Tu ID externo
  * `organizationId` - ID de tu organización
  * `type` - Tipo de entidad
  * `name` - Nombre de la entidad
  * `taxId` - ID fiscal
  * `countryCode` - Código de país
  * `nationality` - Nacionalidad (ISO 3166-1 alfa-2 en raíz, o `null`)
  * `riskScore` - Puntuación de riesgo (0-100)
  * `riskFactors` - Array de factores de riesgo
  * `status` - Estado de la entidad
  * `kycVerified` - Estado de verificación KYC
  * `kycProvider` - Nombre del proveedor KYC
  * `kycData` - Datos de verificación KYC
  * `entityData` - Datos específicos del tipo
  * `attributes` - Atributos personalizados
  * `createdAt` - Marca de tiempo de creación
  * `updatedAt` - Marca de tiempo de última actualización
  * `deletedAt` - Marca de tiempo de eliminación (null si está activa)
</ResponseField>

## Ejemplos

### Listar todas las 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 entidad

<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 identificación 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>

## Ejemplo de respuesta

```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

### Monitoreo de entidades de alto riesgo

Consulta todas las entidades y filtra por puntuación de riesgo en tu aplicación:

```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})`);
});
```

### Panel de cumplimiento KYC

Obtén todas las entidades no verificadas para el panel de cumplimiento:

```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álisis de volumen de transacciones

Lista todas las transacciones para un período específico (combina con filtrado de fechas en tu aplicación):

```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}`);
```

### Cumplimiento específico por país

Obtén todas las entidades de un país específico para reportes regulatorios:

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

## Paginación

La API actualmente devuelve hasta 100 entidades por solicitud. Si tienes más de 100 entidades y necesitas paginación:

1. **Usa filtros específicos** para reducir los resultados (tipo, país, etc.)
2. **Implementa paginación del lado del cliente** almacenando la última marca de tiempo `createdAt`
3. **Contacta con soporte** para funciones de paginación empresarial

Ejemplo con paginación basada en marca de tiempo:

```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;
}
```

## Respuestas de error

### 401 No autorizado

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

### 500 Error interno del servidor

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

## Límites

* **Máximo de resultados por solicitud**: 100 entidades
* **Parámetros de consulta**: Se pueden combinar para filtrado avanzado
* **Límites de tasa**: Se aplican según el nivel de tu plan

## Próximos pasos

* [Obtener detalles de entidad](/api-reference/entities/get) - Recupera información completa para una entidad específica
* [Crear entidad](/api-reference/entities/create) - Agrega nuevas entidades a tu organización
* [Actualizar entidad](/api-reference/entities/update) - Modifica atributos de entidad
* [Operaciones por lotes](/es/api-reference/entities/upsert) - Procesa múltiples entidades a la vez
