> ## 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.

# Create an entity automatically with enrichment

> Automatically create a person or company enriched from official registries in the gu1 universal entity model for KYC, KYB, and risk analysis.

## Overview

The automatic entity creation endpoint allows you to create entities by providing minimal information (tax ID and country). The system automatically:

* Fetches company/person data from official registries
* Enriches the entity with additional information
* Creates related entities (shareholders, directors) based on the specified depth
* Executes enrichments automatically

This is ideal for KYB (Know Your Business) and KYC (Know Your Customer) processes where you want to onboard entities with complete information automatically.

## Endpoint

```
POST http://api.gu1.ai/entities/automatic
```

## Authentication

Requires a valid API key in the Authorization header:

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

## Request Body

<ParamField body="taxId" type="string" required>
  Tax identification number of the entity (e.g., CNPJ for Brazil, RFC for Mexico, CUIT for Argentina).

  Within an organization, an active **`taxId`** (normalized: letters and digits only) may belong to **only one** entity — whether `person` or `company`. If the same type already exists, the API reuses it (`alreadyExisted`). If another type already holds that tax ID, the request fails with **`409`** and code **`DUPLICATE_TAX_ID`**.

  **Type**: `string` (min length: 1)
</ParamField>

<ParamField body="country" type="string" required>
  ISO 3166-1 alpha-2 country code (e.g., "BR", "MX", "AR", "CL")

  **Type**: `string` (length: 2)
</ParamField>

<ParamField body="type" type="string" required>
  Type of entity to create:

  * `company` - Business entity
  * `person` - Individual person

  **Type**: `enum` - `'company' | 'person'`
</ParamField>

<ParamField body="nationality" type="string | null">
  Optional. ISO 3166-1 alpha-2 or a label the API maps to ISO2; stored on the **main** entity row (same validation as [Create entity](/en/api-reference/entities/create)).
</ParamField>

<ParamField body="monitoring" type="object">
  Optional. Same semantics as [Create entity](/en/api-reference/entities/create#example-gu1-sanctions-monitoring-on-create), with two maps:

  * **`main`**: watchlist for the **root** entity (`taxId` in the body) when enrichments run from `autoExecuteIntegrations`.
  * **`relationships`**: watchlist for **shareholders / related** entities at `depth` > 0 when enrichments run from `autoExecuteIntegrationsShareholders` (per `company` / `person`).

  **Today only** `global_gueno_sanctions_enrichment`. Recommended value: `{ "watchlist": true }` or `{ "watchlist": true, "riskMatrixId": "<uuid>" | null }` (legacy `boolean` also accepted).

  Each map only affects entities that actually receive that enrichment. Requires the code in the matching enrichment array and org monitoring ON in Marketplace.
</ParamField>

<ParamField body="externalId" type="string">
  Your unique identifier for this entity in your system. **Optional.**

  When omitted, `externalId` is set to the **normalized tax ID** derived from required **`taxId`**: letters and digits only, uppercase (no dots, dashes, or spaces). Example: `30-12345678-9` → `30123456789`.

  The **`taxId` column** is still saved in the [country display format](/en/api-reference/entities/tax-id-formats). Same auto-assignment rules as [Create an entity (person or company)](/en/api-reference/entities/create) when `taxId` is present.

  **Type**: `string` (optional)
</ParamField>

<ParamField body="depth" type="number" default="0">
  How many levels of shareholders/relationships to automatically create:

  * `0` - Only create the main entity (no relationships)
  * `1` - Create direct shareholders/directors
  * `2` - Create shareholders and their shareholders
  * Maximum: `5`

  **Type**: `number` (min: 0, max: 5, default: 0)
</ParamField>

<ParamField body="isClient" type="boolean" default="false">
  Mark this entity as a client/customer for tracking purposes

  **Type**: `boolean` (default: false)
</ParamField>

<ParamField body="riskMatrixId" type="string | string[]">
  One or more risk matrix UUIDs (legacy: a single UUID string). After creation, active rules tied to those matrices run (unless `skipRulesExecution` is true).

  **Type**: `string | string[] | null` (optional)
</ParamField>

<ParamField body="riskMatrixIds" type="string[]">
  Preferred for **multiple** matrices: ordered UUID list. Takes precedence over `riskMatrixId` when non-empty.

  **Type**: `string[]` (optional)
</ParamField>

<ParamField body="skipRulesExecution" type="boolean" default="false">
  Skip automatic rules execution after entity creation

  **Type**: `boolean` (optional, default: false)
</ParamField>

<ParamField body="status" type="string" default="under_review">
  Initial status for the entity. Options:

  * `active`
  * `inactive`
  * `blocked`
  * `under_review` (default)
  * `suspended`
  * `expired`
  * `deleted`
  * `rejected`

  **Type**: `enum` - `'active' | 'inactive' | 'blocked' | 'under_review' | 'suspended' | 'expired' | 'deleted' | 'rejected'` (default: 'under\_review')
</ParamField>

<ParamField body="operationalHours" type="object | null">
  Optional **main entity** operational hours (`timezone` + `weekly`). Persisted on automatic creation the same as manual entity creation. Not applied to shareholders or relationships created via `depth`.
</ParamField>

<ParamField body="autoExecuteIntegrations" type="object">
  Configure automatic execution of integrations for the main entity. See [Provider Codes Reference](/en/api-reference/integrations/provider-codes) for available codes.

  **Type**: `object` (optional)

  **Properties:**

  * `executeAllActiveEnrichments` (boolean, optional, default: `false`) - Execute all active enrichment integrations
  * `enrichments` (array, optional, default: `[]`) - Array of specific enrichment provider codes to execute
  * `enrichmentGroupRefs` (array of strings, optional) - Marketplace enrichment group slugs (enrichments only). With `executeAllActiveEnrichments: false`, groups are resolved and merged with explicit `enrichments`. With `executeAllActiveEnrichments: true`, group refs are ignored (not resolved); explicit `enrichments` may still append after the active set.
  * `excludeEnrichments` (array, optional, default: `[]`) - Provider codes to omit from the final resolved set (e.g. run all active except listed codes)

  ```typescript theme={null}
  {
    executeAllActiveEnrichments?: boolean; // default: false
    enrichments?: ValidProviderCodesEnum[]; // default: []
    enrichmentGroupRefs?: string[];
    excludeEnrichments?: ValidProviderCodesEnum[]; // default: []
  }
  ```

  **Example:**

  ```json theme={null}
  {
    "executeAllActiveEnrichments": true,
    "excludeEnrichments": ["br_bdc_shareholders_enrichment"],
    "enrichmentGroupRefs": ["my_marketplace_group_slug"]
  }
  ```
</ParamField>

<ParamField body="autoExecuteIntegrationsShareholders" type="object">
  Configure automatic execution of integrations for shareholders and related entities created during the hierarchy traversal. This allows you to specify different integrations for companies vs persons. See [Provider Codes Reference](/en/api-reference/integrations/provider-codes) for available codes.

  **Type**: `object` (optional)

  **Properties:**

  * `executeAllActiveEnrichments` (boolean, optional, default: `false`) - Execute all active enrichment integrations for all shareholders
  * `enrichments` (object, optional) - Specific enrichment provider codes by entity type:
    * `company` (array, optional, default: `[]`) - Enrichments for company shareholders
    * `person` (array, optional, default: `[]`) - Enrichments for person shareholders
  * `enrichmentGroupRefs` (array of strings, optional) - Same group slugs as on the main object; **applied to both** `company` and `person` child pipelines when `executeAllActiveEnrichments` is `false`. When `executeAllActiveEnrichments` is `true` on this object, group refs are ignored; explicit per-type `enrichments` may still append after each side’s active set.
  * `excludeEnrichments` (array, optional, default: `[]`) - Codes omitted from both `company` and `person` lists after merge

  ```typescript theme={null}
  {
    executeAllActiveEnrichments?: boolean; // default: false
    enrichments?: {
      company?: ValidProviderCodesEnum[]; // default: []
      person?: ValidProviderCodesEnum[]; // default: []
    };
    enrichmentGroupRefs?: string[];
    excludeEnrichments?: ValidProviderCodesEnum[]; // default: []
  }
  ```

  **Example:**

  ```json theme={null}
  {
    "executeAllActiveEnrichments": true,
    "excludeEnrichments": ["br_bdc_shareholders_enrichment"],
    "enrichmentGroupRefs": ["shareholder_pipeline_group_slug"]
  }
  ```
</ParamField>

## Required Enrichment Codes by Country

<Warning>
  When using specific enrichment codes (not `executeAllActiveEnrichments: true`), certain enrichments are **mandatory** for the automatic creation to work. Without them, the system cannot fetch basic entity data from official registries and the request will fail.
</Warning>

### Brazil (BR)

#### Main Entity

| Entity Type | Required Enrichment Code                 | Description                                                                                      |
| ----------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------ |
| **Company** | `br_cpfcnpj_complete_company_enrichment` | Fetches company data from CNPJ/Receita Federal (legal name, trade name, address, industry, etc.) |
| **Person**  | `br_bdc_basic_data_enrichment`           | Fetches person data via BDC/CPF (full name, date of birth, address, etc.)                        |

#### Shareholders / Related Entities (only when `depth > 0`)

| Main Entity Type | Required Enrichment Code(s)                                                       | Description                                                                        |
| ---------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| **Company**      | `br_bdc_shareholders_enrichment`                                                  | Fetches the QSA (Quadro Societário) to discover company shareholders and directors |
| **Person**       | `br_bdc_related_companies_enrichment` **AND** `br_bdc_related_persons_enrichment` | Both are required. Fetches companies and persons related to the individual         |

<Info>
  The shareholder enrichments must be included in the **main entity's** `autoExecuteIntegrations.enrichments` array (not in `autoExecuteIntegrationsShareholders`), because the system needs to run them on the main entity to discover who the shareholders are. The `autoExecuteIntegrationsShareholders` field controls what enrichments to run **on each shareholder** after they are created.
</Info>

### Argentina (AR)

#### Main Entity

| Entity Type | Required Enrichment Code                    | Description                                                                          |
| ----------- | ------------------------------------------- | ------------------------------------------------------------------------------------ |
| **Company** | `ar_nosis_extended_verification_enrichment` | Fetches company data from Nosis (legal name, CUIT status, address, activities, etc.) |
| **Person**  | `ar_nosis_extended_verification_enrichment` | Same provider for both entity types                                                  |

#### Shareholders / Related Entities

<Warning>
  Argentina does **not** support automatic shareholder/relationship creation yet. The `depth` parameter must be `0`. If `depth > 0` is provided, the request will fail with an error.
</Warning>

<ParamField body="customData" type="object">
  **Optional** — Client-provided values for the **main entity** that must **not** be replaced by registry enrichments. Does not apply to shareholders or related entities (`depth > 0`).

  After enrichments run, the API **re-applies** `customData` so values are preserved (e.g. automatic name sync from normalized data).

  **Persistence:**

  | `customData` field | Root (`entities`) | `entityData`                                                                                                                                                                                                                                                          |
  | ------------------ | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | `name`             | `name`            | —                                                                                                                                                                                                                                                                     |
  | `email`            | `email`           | `person.email` / `company.email`                                                                                                                                                                                                                                      |
  | `phone`            | `phone`           | `person.phone` / `company.phone`                                                                                                                                                                                                                                      |
  | `birthDate`        | —                 | `person.dateOfBirth` only (person)                                                                                                                                                                                                                                    |
  | `address`          | —                 | `person.address` or `company.address`                                                                                                                                                                                                                                 |
  | `gender`           | —                 | `person.gender` (optional; closed enum: `M`, `F`, `male`, `female`, `other`, `unknown` — use **`other`** for non-binary; in **AR**, only `M`/`F` apply to CUIL derivation and RENAPER. See [Create entity — Person](/en/api-reference/entities/create#person-entity)) |

  **Documented properties:** `name`, `email`, `phone`, `birthDate` (person), `address` (string or object with `fullAddress`, `street`, `city`, …), `gender` (optional enum — `other` for non-binary).

  **Additional keys (API only):** any other key in `customData` is accepted and stored under `entityData.person` or `entityData.company` with the same overwrite protection. E.g. `firstName`, `occupation`, `tradeName`. The dashboard form only sends the documented fields; API integrations may extend the object.

  **Example (person):**

  ```json theme={null}
  {
    "taxId": "23450679909",
    "country": "AR",
    "type": "person",
    "customData": {
      "name": "JOHN DOE",
      "email": "client@company.com",
      "phone": "+541112345678",
      "birthDate": "1990-05-15",
      "address": "123 Main St, Buenos Aires"
    }
  }
  ```

  **Example (company):**

  ```json theme={null}
  {
    "taxId": "30712345678",
    "country": "AR",
    "type": "company",
    "customData": {
      "name": "Acme Argentina S.A. (trade name)",
      "email": "contact@acme.com",
      "phone": "+541140000000",
      "address": {
        "fullAddress": "Av. del Libertador 100, Buenos Aires",
        "city": "Buenos Aires"
      }
    }
  }
  ```
</ParamField>

<ParamField body="attributes" type="object">
  **Optional** - Custom attributes as key-value pairs for the created entity.

  Applied only to the main entity (person or company created), not to shareholders/relationships. Useful for business segments, tags, internal IDs, or any metadata you want to associate at creation time.

  **Structure:** object with string keys and values of any type (string, number, boolean, array, etc.).

  **Example:**

  ```json theme={null}
  {
    "businessSegments": ["retail", "fintech"],
    "source": "onboarding_web",
    "tags": ["vip", "high_volume"]
  }
  ```
</ParamField>

## Query Parameters

<ParamField query="refresh" type="boolean" default="false">
  Force re-enrichment of the main entity even if it already exists in the system.

  **Type**: `boolean` (query string: `"true"` or `"false"`)

  **Behavior**:

  * When `true`: Forces fresh data fetch from official registries and enrichment providers
  * When `false` or omitted: Uses cached enrichment data if available
  * Overrides organization setting `enrichmentsConfig.reEnrichExistingEntities`

  **Use Cases**:

  * Periodic compliance reviews requiring updated information
  * Re-validating entity data after regulatory changes
  * Updating company structure after known corporate changes
  * Manual refresh triggered by compliance officers

  **Example**:

  ```bash theme={null}
  POST http://api.gu1.ai/entities/automatic?refresh=true
  ```

  **Cost Note**: May incur additional charges from third-party data providers.
</ParamField>

<ParamField query="reEnrichExistingChildEntities" type="boolean" default="false">
  Force re-enrichment of ALL shareholders and related entities in the corporate structure.

  **Type**: `boolean` (query string: `"true"` or `"false"`)

  **Behavior**:

  * When `true`: Forces fresh data fetch for the main entity AND all shareholders at all levels (up to `depth`)
  * When `false` or omitted: Only refreshes the main entity if `refresh=true`, shareholders use cached data
  * Works in combination with the `depth` parameter to determine how deep to refresh
  * Overrides organization setting for all related entities

  **Use Cases**:

  * Complete corporate structure audit
  * Due diligence requiring up-to-date ownership chain
  * Annual compliance reviews of entire corporate tree
  * Investigation of complex ownership structures

  **Example - Refresh entire structure**:

  ```bash theme={null}
  POST http://api.gu1.ai/entities/automatic?reEnrichExistingChildEntities=true&depth=3
  ```

  This will refresh the main company AND all shareholders up to 3 levels deep.

  **Performance Note**:

  * Setting this to `true` with high `depth` values (4-5) can take several minutes
  * May result in significant costs if the corporate structure is complex
  * Consider using selectively for high-risk entities only

  **Best Practice**:

  * Use `refresh=true` alone for single entity updates
  * Use `reEnrichExistingChildEntities=true` only when you need full ownership chain validation
</ParamField>

## Response

The endpoint executes synchronously and returns the complete result including the main entity and all related entities created.

<ResponseField name="success" type="boolean">
  Indicates if the entity was created successfully
</ResponseField>

<ResponseField name="data" type="object">
  Complete information about the creation:

  * `entity` (object) - The main entity created with all its data
  * `shareholders` (array) - Array of shareholder entities created (for companies)
  * `relationships` (array) - Array of related entities created (for persons)
  * `summary` (object):
    * `entitiesCreated` (number) - Total number of entities created
    * `relationshipsCreated` (number) - Total number of relationships created
    * `errorsCount` (number) - Number of errors encountered
  * `errors` (object, optional) - Details of any errors that occurred:
    * `creationFailed` (array) - Failed entity creations
    * `enrichmentFailed` (array) - Failed enrichment executions
</ResponseField>

<ResponseField name="rulesResult" type="object">
  Result of rules execution (only present when rules ran, e.g. when **skipRulesExecution** is `false` and a risk matrix is configured via `riskMatrixId` or `riskMatrixIds`), or null. When present, includes:

  * **success** (boolean) - Whether rules executed successfully
  * **rulesTriggered** (number) - Number of rules that were triggered
  * **alerts** (array) - Alerts generated by rules
  * **riskScore** (number) - Final calculated risk score
  * **decision** (string) - Final decision (APPROVE, REJECT, HOLD, REVIEW\_REQUIRED)
  * **rulesExecutionSummary** (object) - Present when rules ran. See below for structure.
</ResponseField>

<ResponseField name="rulesExecutionSummary" type="object">
  **At the root of the response** (same as transactions API). Same value as `rulesResult.rulesExecutionSummary`. **Only present when rules ran (e.g. skipRulesExecution is false and risk matrix was executed).** Summary of which rules matched (hit) vs did not match (no hit), executed actions, and total score. Omitted when rules did not run. See [Rules Execution Summary](/en/api-reference/rules-execution-summary) for the full structure and a complete example.

  * **rulesHit** (array) - Rules whose conditions were met. Each item: **name**, **description**, **score**, **priority**, **category**, **status** (e.g. `active`, `shadow`), **conditions** (array of `{ field, value, operator? }`), **actions** (alerts, suggestion, status, assignedUser).
  * **rulesNoHit** (array) - Rules that were evaluated but conditions were not met. Same structure as rulesHit (includes configured actions, not executed).
  * **actionsExecuted** (object) - Aggregated executed actions across all rules that hit: **alerts** (array of `{ name?, type?, severity?, description? }`), **suggestion** (`BLOCK` | `SUSPEND` | `FLAG`, highest weight), **status** (entity status applied, if any), **assignedUser** (`{ userId }`, if any), **customKeys** (array of strings, optional) — custom action keys from matched rules; for integrations/workflows.
  * **totalScore** (number) - Sum of **score** of all rules that hit and are **not** in `shadow` status.
</ResponseField>

## WebSocket Events

The system emits real-time events during the creation process:

### `entity:creation-started`

Emitted when the creation process begins.

```json theme={null}
{
  "taxId": "12.345.678/0001-90",
  "type": "company",
  "userId": "user_id"
}
```

### `entity:creation-completed`

Emitted when the entity and all relationships have been created.

```json theme={null}
{
  "success": true,
  "mainEntity": {
    "id": "uuid",
    "name": "Company Name",
    "taxId": "12.345.678/0001-90"
  },
  "stats": {
    "totalEntitiesCreated": 15,
    "companiesCreated": 8,
    "peopleCreated": 7,
    "relationshipsCreated": 14
  }
}
```

### `entity:creation-failed`

Emitted if the creation process fails.

```json theme={null}
{
  "success": false,
  "error": "Error message",
  "taxId": "12.345.678/0001-90"
}
```

## Gu1 Sanctions Monitoring on Automatic Create

For `POST /entities/automatic`:

| Field                      | Applies to                                                                                                      |
| -------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `monitoring.main`          | Root entity when enrichments run from `autoExecuteIntegrations`.                                                |
| `monitoring.relationships` | Each shareholder/related entity at `depth` > 0 when enrichments run from `autoExecuteIntegrationsShareholders`. |

Today the only body-monitoring code is **`global_gueno_sanctions_enrichment`**. It must appear in the enrichment array for that level **and** in `main` or `relationships` with watchlist enabled.

```json theme={null}
{
  "taxId": "30-71000001-2",
  "country": "AR",
  "type": "company",
  "depth": 1,
  "monitoring": {
    "main": {
      "global_gueno_sanctions_enrichment": {
        "watchlist": true
      }
    },
    "relationships": {
      "global_gueno_sanctions_enrichment": {
        "watchlist": true,
        "riskMatrixId": null
      }
    }
  },
  "autoExecuteIntegrations": {
    "executeAllActiveEnrichments": false,
    "enrichments": [
      "ar_afip_registration_enrichment",
      "global_gueno_sanctions_enrichment"
    ]
  },
  "autoExecuteIntegrationsShareholders": {
    "executeAllActiveEnrichments": false,
    "enrichments": {
      "company": ["global_gueno_sanctions_enrichment"],
      "person": ["global_gueno_sanctions_enrichment"]
    }
  }
}
```

Registry enrichments (e.g. `ar_afip_registration_enrichment`) ignore `monitoring` and always run as one-off queries.

<Warning>
  This payload only illustrates **`monitoring`** and Gu1 enrichment codes. A real request must still include the **mandatory registry enrichments** for the chosen `country` and `type` (see **Required Enrichment Codes by Country** above), or automatic creation will fail.
</Warning>

## Examples

### Create Company with Shareholders (Depth 1)

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/entities/automatic \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "taxId": "12.345.678/0001-90",
      "country": "BR",
      "type": "company",
      "depth": 1,
      "isClient": true,
      "autoExecuteIntegrations": {
        "executeAllActiveEnrichments": true,
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://api.gu1.ai/entities/automatic', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      taxId: '12.345.678/0001-90',
      country: 'BR',
      type: 'company',
      depth: 1,
      isClient: true,
      autoExecuteIntegrations: {
        executeAllActiveEnrichments: true,
      }
    })
  });

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

  // Listen for WebSocket events
  socket.on('entity:creation-completed', (result) => {
    console.log('Entity created:', result.mainEntity);
    console.log('Total entities created:', result.stats.totalEntitiesCreated);
  });
  ```

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

  response = requests.post(
      'http://api.gu1.ai/entities/automatic',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'taxId': '12.345.678/0001-90',
          'country': 'BR',
          'type': 'company',
          'depth': 1,
          'isClient': True,
          'autoExecuteIntegrations': {
              'executeAllActiveEnrichments': True,
          }
      }
  )

  data = response.json()
  print(data)
  ```
</CodeGroup>

### Create Person (KYC) with Specific Integrations

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/entities/automatic \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "taxId": "123.456.789-00",
      "country": "BR",
      "type": "person",
      "externalId": "customer_12345",
      "depth": 0,
      "autoExecuteIntegrations": {
        "enrichments": ["br_bdc_basic_data_enrichment"]
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://api.gu1.ai/entities/automatic', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      taxId: '123.456.789-00',
      country: 'BR',
      type: 'person',
      externalId: 'customer_12345',
      depth: 0,
      autoExecuteIntegrations: {
        enrichments: ['br_bdc_basic_data_enrichment']
      }
    })
  });

  const data = await response.json();
  ```

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

  response = requests.post(
      'http://api.gu1.ai/entities/automatic',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'taxId': '123.456.789-00',
          'country': 'BR',
          'type': 'person',
          'externalId': 'customer_12345',
          'depth': 0,
          'autoExecuteIntegrations': {
              'enrichments': ['br_bdc_basic_data_enrichment']
          }
      }
  )

  data = response.json()
  ```
</CodeGroup>

### Create Argentine Company (No Shareholders Support)

```bash theme={null}
curl -X POST http://api.gu1.ai/entities/automatic \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "taxId": "30-12345678-9",
    "country": "AR",
    "type": "company",
    "depth": 0,
    "isClient": true,
    "riskMatrixId": "risk_matrix_uuid",
    "autoExecuteIntegrations": {
      "enrichments": ["ar_nosis_extended_verification_enrichment"]
    }
  }'
```

### Create Brazilian Company with Shareholders and Selective Integrations

```bash theme={null}
curl -X POST http://api.gu1.ai/entities/automatic \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "taxId": "12.345.678/0001-90",
    "country": "BR",
    "type": "company",
    "depth": 2,
    "isClient": true,
    "riskMatrixId": "risk_matrix_uuid",
    "autoExecuteIntegrations": {
      "enrichments": ["br_cpfcnpj_complete_company_enrichment", "br_bdc_shareholders_enrichment"],
      "enrichmentGroupRefs": ["main_entity_group_slug"]
    },
    "autoExecuteIntegrationsShareholders": {
      "enrichments": {
        "company": ["br_cpfcnpj_complete_company_enrichment"],
        "person": ["br_bdc_basic_data_enrichment"]
      },
      "enrichmentGroupRefs": ["child_entities_group_slug"]
    }
  }'
```

## Response Example

### Successful Company Creation with Shareholders

```json theme={null}
{
  "success": true,
  "data": {
    "entity": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "organizationId": "org_uuid",
      "type": "company",
      "name": "Tech Solutions LTDA",
      "taxId": "12345678000190",
      "countryCode": "BR",
      "status": "under_review",
      "riskScore": null,
      "entityData": {
        "company": {
          "legalName": "Tech Solutions LTDA",
          "tradeName": "Tech Solutions",
          "incorporationDate": "2020-01-15",
          "industry": "Technology"
        }
      },
      "createdAt": "2024-12-23T10:30:00.000Z",
      "updatedAt": "2024-12-23T10:30:00.000Z"
    },
    "shareholders": [
      {
        "id": "shareholder_1_uuid",
        "type": "person",
        "name": "João Silva",
        "taxId": "12345678900",
        "countryCode": "BR",
        "entityData": {
          "person": {
            "firstName": "João",
            "lastName": "Silva"
          }
        },
        "shareholderInfo": {
          "percentage": 60.0,
          "role": "Sócio Administrador"
        }
      },
      {
        "id": "shareholder_2_uuid",
        "type": "person",
        "name": "Maria Santos",
        "taxId": "98765432100",
        "countryCode": "BR",
        "entityData": {
          "person": {
            "firstName": "Maria",
            "lastName": "Santos"
          }
        },
        "shareholderInfo": {
          "percentage": 40.0,
          "role": "Sócia"
        }
      }
    ],
    "summary": {
      "entitiesCreated": 3,
      "relationshipsCreated": 2,
      "errorsCount": 0
    }
  },
  "rulesResult": null
}
```

### Successful Person Creation

```json theme={null}
{
  "success": true,
  "data": {
    "entity": {
      "id": "person_uuid",
      "organizationId": "org_uuid",
      "type": "person",
      "name": "João Silva",
      "taxId": "12345678900",
      "countryCode": "BR",
      "status": "under_review",
      "entityData": {
        "person": {
          "firstName": "João",
          "lastName": "Silva",
          "dateOfBirth": "1985-05-15"
        }
      },
      "createdAt": "2024-12-23T10:30:00.000Z",
      "updatedAt": "2024-12-23T10:30:00.000Z"
    },
    "relationships": [],
    "summary": {
      "entitiesCreated": 1,
      "relationshipsCreated": 0,
      "errorsCount": 0
    }
  },
  "rulesResult": null
}
```

## Error Responses

### 400 Bad Request - Invalid Tax ID

```json theme={null}
{
  "success": false,
  "error": "Invalid CNPJ format for Brazil"
}
```

### 404 Not Found - Entity Not Found in Registry

```json theme={null}
{
  "success": false,
  "error": "Entity not found in official registry",
  "details": {
    "taxId": "12.345.678/0001-90",
    "country": "BR",
    "registry": "Receita Federal"
  }
}
```

### 409 Conflict - Entity Already Exists

Returned when the normalized `taxId` is already used by an **active** entity of a **different** type in the same organization (person vs company). Same-type matches are reused instead of failing.

```json theme={null}
{
  "success": false,
  "error": {
    "code": "DUPLICATE_TAX_ID",
    "message": "This tax ID is already registered for a company in this organization (Entity ID: uuid).",
    "details": {
      "existingEntityId": "uuid",
      "existingEntityType": "company"
    }
  }
}
```

### 500 Internal Server Error

```json theme={null}
{
  "success": false,
  "error": "Failed to create entity automatically",
  "details": {
    "message": "External API timeout"
  }
}
```

## Best Practices

1. **Use depth wisely**: Higher depth values (3-5) can create many entities and take longer to complete. Start with depth 0-1 for testing.

2. **Monitor WebSocket events**: While the API returns synchronously, WebSocket events are also emitted for real-time UI updates (`entity:creation-started`, `entity:creation-completed`, `entity:creation-failed`).

3. **Handle timeouts**: For complex hierarchies with high depth, the request can take several minutes. Configure appropriate HTTP timeout values in your client.

4. **Error handling**: Always check the `success` field and the `errors` object in the response. Some entities may be created successfully while others fail.

5. **Rate limiting**: Be mindful of rate limits when creating multiple entities in quick succession. The endpoint fetches data from external APIs which may have their own rate limits.

## Related Endpoints

* [Create Entity Manually](/api-reference/entities/create) - Create entities with your own data
* [Get Entity](/api-reference/entities/get) - Retrieve entity details
* [List Entities](/api-reference/entities/list) - Query your entities
